File size: 10,204 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import { readFileSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import { apiFetch, isServerUp } from "../api.mjs";
import { emit } from "../output.mjs";
import { t } from "../i18n.mjs";

const A2A_SKILLS = [
  { id: "smart-routing", name: "Smart Request Routing" },
  { id: "quota-management", name: "Quota & Cost Management" },
  { id: "provider-discovery", name: "Provider Discovery" },
  { id: "cost-analysis", name: "Cost Analysis" },
  { id: "health-report", name: "Health Report" },
];

function fmtTs(v) {
  if (!v) return "-";
  try {
    return new Date(v).toLocaleString();
  } catch {
    return String(v);
  }
}

function randomId() {
  return Math.random().toString(36).slice(2, 11);
}

async function confirm(q) {
  return new Promise((resolve) => {
    process.stdout.write(`${q} (yes/no) `);
    process.stdin.setEncoding("utf8");
    process.stdin.once("data", (c) => resolve(c.toString().trim().toLowerCase().startsWith("y")));
  });
}

const taskSchema = [
  { key: "id", header: "Task ID", width: 22 },
  { key: "skill", header: "Skill", width: 22 },
  { key: "status", header: "Status", width: 12 },
  { key: "createdAt", header: "Created", formatter: fmtTs },
  { key: "updatedAt", header: "Updated", formatter: fmtTs },
  { key: "duration", header: "Duration", formatter: (v) => (v != null ? `${v}ms` : "-") },
];

export function registerA2a(program) {
  const a2a = program.command("a2a").description("Agent-to-Agent (A2A) server");

  a2a
    .command("status")
    .description("Show A2A server status")
    .option("--json", "Output as JSON")
    .action(async (opts, cmd) => {
      const globalOpts = cmd.parent.optsWithGlobals();
      const exitCode = await runA2aStatusCommand({ ...opts, output: globalOpts.output });
      if (exitCode !== 0) process.exit(exitCode);
    });

  a2a
    .command("card")
    .description("Print the Agent Card JSON")
    .action(async (opts, cmd) => {
      const globalOpts = cmd.parent.optsWithGlobals();
      const exitCode = await runA2aCardCommand({ ...opts, output: globalOpts.output });
      if (exitCode !== 0) process.exit(exitCode);
    });

  // 5.3 — a2a skills + a2a invoke
  a2a
    .command("skills")
    .description(t("a2a.skills.description"))
    .action(async (opts, cmd) => {
      const res = await apiFetch("/.well-known/agent.json");
      if (res.ok) {
        const card = await res.json();
        emit(card.skills ?? A2A_SKILLS, cmd.optsWithGlobals());
      } else {
        emit(A2A_SKILLS, cmd.optsWithGlobals());
      }
    });

  a2a
    .command("invoke <skill>")
    .description(t("a2a.invoke.description"))
    .option("--input <json>", t("a2a.invoke.input"))
    .option("--input-file <path>", t("a2a.invoke.input_file"))
    .option("--wait", t("a2a.invoke.wait"))
    .option("--timeout <ms>", t("a2a.invoke.timeout"), parseInt, 60000)
    .action(async (skill, opts, cmd) => {
      const globalOpts = cmd.optsWithGlobals();
      const input = opts.input
        ? JSON.parse(opts.input)
        : opts.inputFile
          ? JSON.parse(readFileSync(opts.inputFile, "utf8"))
          : {};

      const rpcBody = {
        jsonrpc: "2.0",
        id: randomId(),
        method: "tasks.create",
        params: {
          skill,
          input,
          messages: [{ role: "user", parts: [{ kind: "data", data: input }] }],
        },
      };

      const res = await apiFetch("/api/a2a/tasks", { method: "POST", body: rpcBody });
      if (!res.ok) {
        process.stderr.write(`Error: ${res.status}\n`);
        process.exit(1);
      }
      const created = await res.json();
      const taskId = created.result?.taskId ?? created.taskId ?? created.id;

      if (!opts.wait) {
        emit({ taskId }, globalOpts);
        return;
      }

      const deadline = Date.now() + (opts.timeout ?? 60000);
      while (Date.now() < deadline) {
        await sleep(1000);
        const taskRes = await apiFetch(`/api/a2a/tasks/${taskId}`);
        if (!taskRes.ok) continue;
        const task = (await taskRes.json()).result ?? (await taskRes.clone().json());
        const state = task.status?.state ?? task.status;
        if (["completed", "failed", "cancelled"].includes(state)) {
          emit(task, globalOpts);
          return;
        }
      }
      process.stderr.write("Timeout waiting for task completion\n");
      process.exit(124);
    });

  // 5.4 — a2a tasks
  const tasks = a2a.command("tasks").description(t("a2a.tasks.description"));

  tasks
    .command("list")
    .option("--status <s>", t("a2a.tasks.list.status"))
    .option("--skill <s>", t("a2a.tasks.list.skill"))
    .option("--limit <n>", parseInt, 50)
    .option("--since <ts>")
    .action(async (opts, cmd) => {
      const params = new URLSearchParams({ limit: String(opts.limit ?? 50) });
      if (opts.status) params.set("status", opts.status);
      if (opts.skill) params.set("skill", opts.skill);
      if (opts.since) params.set("since", opts.since);
      const res = await apiFetch(`/api/a2a/tasks?${params}`);
      if (!res.ok) {
        process.stderr.write(`Error: ${res.status}\n`);
        process.exit(1);
      }
      const data = await res.json();
      emit(data.tasks ?? data.items ?? data, cmd.optsWithGlobals(), taskSchema);
    });

  tasks.command("get <id>").action(async (id, opts, cmd) => {
    const res = await apiFetch(`/api/a2a/tasks/${id}`);
    if (!res.ok) {
      process.stderr.write(`Not found: ${id}\n`);
      process.exit(1);
    }
    emit(await res.json(), cmd.optsWithGlobals());
  });

  tasks
    .command("cancel <id>")
    .option("--yes")
    .action(async (id, opts, cmd) => {
      if (!opts.yes) {
        const ok = await confirm(`Cancel task ${id}?`);
        if (!ok) return;
      }
      const res = await apiFetch(`/api/a2a/tasks/${id}/cancel`, { method: "POST" });
      if (!res.ok) {
        process.stderr.write(`Error: ${res.status}\n`);
        process.exit(1);
      }
      process.stdout.write("Cancelled\n");
    });

  tasks
    .command("watch <id>")
    .description(t("a2a.tasks.watch.description"))
    .action(async (id, opts, cmd) => {
      let lastState = "";
      while (true) {
        const res = await apiFetch(`/api/a2a/tasks/${id}`);
        if (res.ok) {
          const data = await res.json();
          const state = data.status?.state ?? data.status ?? "";
          if (state !== lastState) {
            process.stderr.write(`[${new Date().toISOString()}] ${state}\n`);
            lastState = state;
          }
          if (["completed", "failed", "cancelled"].includes(state)) {
            emit(data, cmd.optsWithGlobals());
            return;
          }
        }
        await sleep(1500);
      }
    });

  tasks
    .command("stream <id>")
    .description(t("a2a.tasks.stream.description"))
    .action(async (id, opts, cmd) => {
      const globalOpts = cmd.optsWithGlobals();
      const baseUrl = globalOpts.baseUrl ?? "http://localhost:20128";
      const apiKey = globalOpts.apiKey ?? "";
      const res = await fetch(`${baseUrl}/api/a2a/tasks/${id}?stream=true`, {
        headers: {
          Accept: "text/event-stream",
          ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
        },
      });
      if (!res.ok) {
        process.stderr.write(`HTTP ${res.status}\n`);
        process.exit(1);
      }
      const reader = res.body.getReader();
      const dec = new TextDecoder();
      let buf = "";
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buf += dec.decode(value, { stream: true });
        const lines = buf.split("\n");
        buf = lines.pop() ?? "";
        for (const line of lines) {
          if (line.startsWith("data: ")) {
            const raw = line.slice(6).trim();
            if (raw && raw !== "[DONE]") process.stdout.write(raw + "\n");
          }
        }
      }
    });

  tasks
    .command("logs <id>")
    .description(t("a2a.tasks.logs.description"))
    .action(async (id, opts, cmd) => {
      const res = await apiFetch(`/api/a2a/tasks/${id}?include=messages,artifacts`);
      if (!res.ok) {
        process.stderr.write(`Not found: ${id}\n`);
        process.exit(1);
      }
      const data = await res.json();
      emit(data.messages ?? data, cmd.optsWithGlobals());
    });
}

export async function runA2aStatusCommand(opts = {}) {
  const serverUp = await isServerUp();
  if (!serverUp) {
    console.error(t("common.serverOffline"));
    return 1;
  }

  try {
    const res = await apiFetch("/api/a2a/status", {
      retry: false,
      timeout: 5000,
      acceptNotOk: true,
    });
    if (!res.ok) {
      console.log("A2A status not available.");
      return 0;
    }

    const status = await res.json();

    if (opts.json || opts.output === "json") {
      console.log(JSON.stringify(status, null, 2));
      return 0;
    }

    const running = status.running ? "\x1b[32mrunning\x1b[0m" : "\x1b[31mstopped\x1b[0m";
    console.log(`  Status:    ${running}`);
    console.log(`  Protocol:  ${status.protocol || "JSON-RPC 2.0"}`);
    console.log(`  Tasks:     ${status.activeTasks || 0} active`);

    if (status.skills?.length) {
      console.log("\n  Skills:");
      for (const skill of status.skills) {
        console.log(`\x1b[2m    - ${skill.name}: ${skill.description || "N/A"}\x1b[0m`);
      }
    }
    return 0;
  } catch (err) {
    console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
    return 1;
  }
}

export async function runA2aCardCommand(opts = {}) {
  const serverUp = await isServerUp();
  if (!serverUp) {
    console.error(t("common.serverOffline"));
    return 1;
  }

  try {
    const res = await apiFetch("/.well-known/agent.json", {
      retry: false,
      timeout: 5000,
      acceptNotOk: true,
    });
    if (res.ok) {
      const card = await res.json();
      console.log(JSON.stringify(card, null, 2));
      return 0;
    }
    console.log("Agent card not available.");
    return 0;
  } catch (err) {
    console.error(t("common.error", { message: err instanceof Error ? err.message : String(err) }));
    return 1;
  }
}