@kumion/cli 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js ADDED
@@ -0,0 +1,681 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { parseArgs } from "node:util";
3
+ import { ApiError, KumionClient } from "./client.js";
4
+ import { DEFAULT_BASE_URL, keyPrefix, looksLikeApiKey, normalizeBaseUrl, resolveCredentials, } from "./credentials.js";
5
+ import { DEFAULT_DEVICE_SCOPES, deviceLogin } from "./device-login.js";
6
+ import { describeError, ReportedFailure, UsageError } from "./errors.js";
7
+ export const VERSION = "0.2.0";
8
+ const HELP = `kumion — manage your Kumion voice agents over the Partner API
9
+
10
+ Usage: kumion <command> [options]
11
+
12
+ Auth
13
+ auth login [--profile <name>] [--base-url <url>] [--scopes <a,b,…>]
14
+ Log in through the browser: approve the code in the
15
+ Portal and get a personal key (12 hours at most;
16
+ tenant administrators only) in the OS keychain
17
+ auth login --with-api-key [--profile <name>] [--tenant <id>] [--base-url <url>]
18
+ Save an API key issued on 設定 → 開発者 instead
19
+ auth status Show which tenant and key commands will use
20
+ auth list List saved profiles
21
+ auth use <profile> Make a profile the default
22
+ auth logout [--profile <name>] Remove a profile and its key
23
+
24
+ Agents
25
+ agents list List the tenant's agents
26
+ agents get <agentId> Show an agent's draft and published version
27
+ agents patch <agentId> --revision <rev> [--prompt <text> | --prompt-file <path>] [--graph-file <path>]
28
+ Edit the draft (never goes live by itself)
29
+ agents publish <agentId> [--revision <rev>]
30
+ Publish the draft through the pre-publish check
31
+
32
+ Test runs
33
+ test-runs start <agentId> [--no-wait] [--interval <sec>] [--timeout <sec>]
34
+ Run the agent's regression tests against its draft
35
+ test-runs get <agentId> <runId> Show one run and its results
36
+ test-runs list <agentId> [--limit <n>]
37
+
38
+ Calls
39
+ calls create <agentId> [--campaign-contact <id>]
40
+ Start a web call with the agent
41
+ calls list [--agent <id>] [--channel webcall|sip_did|trigger] [--from <iso>] [--to <iso>]
42
+ [--search <text>] [--limit <n>] [--offset <n>]
43
+ List the tenant's call history, newest first (20 per page)
44
+ calls get <callId> Show one call: source, numbers, times, how it ended
45
+ calls transcript <callId> Print what the caller and the agent said
46
+ (list/get/transcript need a key with calls:read)
47
+
48
+ MCP
49
+ mcp [--profile <name>] Serve the commands above as MCP tools over stdio,
50
+ for an AI coding assistant. The key comes from the
51
+ keychain or KUMION_API_KEY — never from the host's config
52
+
53
+ Global options
54
+ --profile <name> Use this saved profile (default: the default profile)
55
+ --base-url <url> Kumion Portal origin (default: ${DEFAULT_BASE_URL}).
56
+ Select another environment with this option or KUMION_API_BASE
57
+ --json Print the API's JSON instead of a summary
58
+ --debug Print stack traces on errors
59
+ -h, --help Show help
60
+ -v, --version Show the version
61
+
62
+ Environment
63
+ KUMION_API_KEY, KUMION_TENANT_ID Use this key instead of a saved profile (CI)
64
+ KUMION_API_BASE Same as --base-url
65
+ KUMION_PROFILE Same as --profile
66
+ `;
67
+ const GLOBAL_OPTIONS = {
68
+ profile: { type: "string" },
69
+ "base-url": { type: "string" },
70
+ json: { type: "boolean" },
71
+ debug: { type: "boolean" },
72
+ help: { type: "boolean", short: "h" },
73
+ version: { type: "boolean", short: "v" },
74
+ };
75
+ function parse(args, options) {
76
+ try {
77
+ return parseArgs({ args, options: { ...GLOBAL_OPTIONS, ...options }, allowPositionals: true, strict: true });
78
+ }
79
+ catch (err) {
80
+ throw new UsageError(`${err.message}\nRun \`kumion --help\` for usage.`);
81
+ }
82
+ }
83
+ function need(positionals, index, what) {
84
+ const value = positionals[index];
85
+ if (!value)
86
+ throw new UsageError(`Missing <${what}>. Run \`kumion --help\` for usage.`);
87
+ return value;
88
+ }
89
+ function positiveNumber(raw, flag, fallback) {
90
+ if (raw === undefined)
91
+ return fallback;
92
+ const n = Number(raw);
93
+ if (!Number.isFinite(n) || n <= 0)
94
+ throw new UsageError(`--${flag} must be a positive number.`);
95
+ return n;
96
+ }
97
+ async function readJsonFile(path) {
98
+ let text;
99
+ try {
100
+ text = await readFile(path, "utf8");
101
+ }
102
+ catch (err) {
103
+ throw new UsageError(`Cannot read ${path}: ${err.message}`);
104
+ }
105
+ try {
106
+ return JSON.parse(text);
107
+ }
108
+ catch (err) {
109
+ throw new UsageError(`${path} is not valid JSON: ${err.message}`);
110
+ }
111
+ }
112
+ export async function run(argv, deps) {
113
+ const debug = argv.includes("--debug");
114
+ try {
115
+ return await dispatch(argv, deps);
116
+ }
117
+ catch (err) {
118
+ deps.io.err(`Error: ${describeError(err)}`);
119
+ if (debug && err instanceof Error && err.stack)
120
+ deps.io.err(err.stack);
121
+ return err instanceof UsageError ? 2 : 1;
122
+ }
123
+ }
124
+ async function dispatch(argv, deps) {
125
+ const [group, command, ...rest] = argv;
126
+ if (!group || group === "help" || group === "--help" || group === "-h") {
127
+ deps.io.out(HELP);
128
+ return 0;
129
+ }
130
+ if (group === "--version" || group === "-v") {
131
+ deps.io.out(VERSION);
132
+ return 0;
133
+ }
134
+ if (command === "--help" || command === "-h" || rest.includes("--help") || rest.includes("-h")) {
135
+ deps.io.out(HELP);
136
+ return 0;
137
+ }
138
+ if (group === "mcp")
139
+ return mcpServe(argv.slice(1), deps);
140
+ const handler = COMMANDS[`${group} ${command ?? ""}`.trim()];
141
+ if (!handler) {
142
+ throw new UsageError(`Unknown command: kumion ${[group, command].filter(Boolean).join(" ")}\nRun \`kumion --help\` for usage.`);
143
+ }
144
+ return handler(rest, deps);
145
+ }
146
+ async function clientFor(values, deps) {
147
+ const creds = await resolveCredentials({
148
+ env: deps.env,
149
+ config: await deps.config.read(),
150
+ secrets: deps.secrets,
151
+ profileFlag: values.profile,
152
+ baseUrlFlag: values["base-url"],
153
+ });
154
+ return new KumionClient(creds, deps.fetch);
155
+ }
156
+ function printJson(deps, value) {
157
+ deps.io.out(JSON.stringify(value, null, 2));
158
+ }
159
+ const COMMANDS = {
160
+ "auth login": authLogin,
161
+ "auth status": authStatus,
162
+ "auth list": authList,
163
+ "auth use": authUse,
164
+ "auth logout": authLogout,
165
+ "agents list": agentsList,
166
+ "agents get": agentsGet,
167
+ "agents patch": agentsPatch,
168
+ "agents publish": agentsPublish,
169
+ "test-runs start": testRunsStart,
170
+ "test-runs get": testRunsGet,
171
+ "test-runs list": testRunsList,
172
+ "calls create": callsCreate,
173
+ "calls list": callsList,
174
+ "calls get": callsGet,
175
+ "calls transcript": callsTranscript,
176
+ };
177
+ async function authLogin(args, deps) {
178
+ const { values } = parse(args, {
179
+ tenant: { type: "string" },
180
+ "with-api-key": { type: "boolean" },
181
+ scopes: { type: "string" },
182
+ });
183
+ if (values["with-api-key"]) {
184
+ if (values.scopes !== undefined)
185
+ throw new UsageError("--scopes applies to the browser login, not to --with-api-key.");
186
+ return authLoginWithApiKey(values, deps);
187
+ }
188
+ if (values.tenant !== undefined) {
189
+ throw new UsageError("--tenant applies to --with-api-key. The browser login asks which tenant in the Portal.");
190
+ }
191
+ return authLoginDevice(values, deps);
192
+ }
193
+ async function authLoginDevice(values, deps) {
194
+ const name = values.profile ?? "default";
195
+ const rawBase = values["base-url"] ?? deps.env.KUMION_API_BASE;
196
+ const baseUrl = rawBase ? normalizeBaseUrl(rawBase) : undefined;
197
+ let scopes = DEFAULT_DEVICE_SCOPES;
198
+ if (values.scopes !== undefined) {
199
+ const asked = values.scopes.split(",").map((s) => s.trim()).filter(Boolean);
200
+ const unknown = asked.filter((s) => !DEFAULT_DEVICE_SCOPES.includes(s));
201
+ if (asked.length === 0 || unknown.length > 0) {
202
+ throw new UsageError(`--scopes takes a comma-separated list of: ${DEFAULT_DEVICE_SCOPES.join(", ")}.`);
203
+ }
204
+ scopes = DEFAULT_DEVICE_SCOPES.filter((s) => asked.includes(s));
205
+ }
206
+ const got = await deviceLogin({ baseUrl: baseUrl ?? DEFAULT_BASE_URL, fetch: deps.fetch, sleep: deps.sleep, io: deps.io, scopes });
207
+ await deps.secrets().set(name, got.key);
208
+ const config = await deps.config.read();
209
+ config.profiles[name] = {
210
+ tenantId: got.tenantId,
211
+ ...(baseUrl ? { baseUrl } : {}),
212
+ kind: "personal",
213
+ ...(got.expiresAt ? { expiresAt: got.expiresAt } : {}),
214
+ };
215
+ if (!config.defaultProfile || Object.keys(config.profiles).length === 1)
216
+ config.defaultProfile = name;
217
+ await deps.config.write(config);
218
+ deps.io.out(`Approved. Saved profile "${name}" (tenant ${got.tenantId}, personal key ${keyPrefix(got.key)}` +
219
+ (got.expiresAt ? `, expires ${got.expiresAt}` : "") +
220
+ ") — the key is in the OS keychain." +
221
+ (config.defaultProfile === name ? " It is the default profile." : ` Use it with --profile ${name}, or \`kumion auth use ${name}\`.`));
222
+ if (got.scopes.length > 0)
223
+ deps.io.out(`Permissions: ${got.scopes.join(", ")}`);
224
+ return 0;
225
+ }
226
+ async function authLoginWithApiKey(values, deps) {
227
+ const name = values.profile ?? "default";
228
+ const tenantId = (values.tenant ?? (await deps.io.prompt("Tenant ID: "))).trim();
229
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(tenantId)) {
230
+ throw new UsageError("The tenant ID must be a UUID — the one in the Portal URL (/tenants/<id>/) and in the curl examples on 設定 → 開発者.");
231
+ }
232
+ const apiKey = (await deps.io.prompt("API key (input hidden): ", { hidden: true })).trim();
233
+ if (!looksLikeApiKey(apiKey))
234
+ throw new UsageError("That does not look like a Kumion API key (kum_live_…).");
235
+ const rawBase = values["base-url"] ?? deps.env.KUMION_API_BASE;
236
+ const baseUrl = rawBase ? normalizeBaseUrl(rawBase) : undefined;
237
+ const client = new KumionClient({ apiKey, tenantId, baseUrl: baseUrl ?? DEFAULT_BASE_URL }, deps.fetch);
238
+ let verified = true;
239
+ try {
240
+ await client.listAgents();
241
+ }
242
+ catch (err) {
243
+ if (err instanceof ApiError && err.status === 403)
244
+ verified = false;
245
+ else
246
+ throw err;
247
+ }
248
+ await deps.secrets().set(name, apiKey);
249
+ const config = await deps.config.read();
250
+ config.profiles[name] = baseUrl ? { tenantId, baseUrl } : { tenantId };
251
+ if (!config.defaultProfile || Object.keys(config.profiles).length === 1)
252
+ config.defaultProfile = name;
253
+ await deps.config.write(config);
254
+ deps.io.out(`Saved profile "${name}" (tenant ${tenantId}, key ${keyPrefix(apiKey)}) — the key is in the OS keychain.` +
255
+ (config.defaultProfile === name ? " It is the default profile." : ` Use it with --profile ${name}, or \`kumion auth use ${name}\`.`));
256
+ if (!verified)
257
+ deps.io.out("Note: this key cannot list agents (no agents:read scope), so it was not checked beyond that.");
258
+ return 0;
259
+ }
260
+ async function authStatus(args, deps) {
261
+ const { values } = parse(args, {});
262
+ const creds = await resolveCredentials({
263
+ env: deps.env,
264
+ config: await deps.config.read(),
265
+ secrets: deps.secrets,
266
+ profileFlag: values.profile,
267
+ baseUrlFlag: values["base-url"],
268
+ });
269
+ const profile = creds.profile ? (await deps.config.read()).profiles[creds.profile] : undefined;
270
+ const expired = profile?.expiresAt ? Date.parse(profile.expiresAt) <= Date.now() : false;
271
+ const status = {
272
+ profile: creds.profile,
273
+ source: creds.source,
274
+ tenantId: creds.tenantId,
275
+ baseUrl: creds.baseUrl,
276
+ key: keyPrefix(creds.apiKey),
277
+ ...(profile?.kind ? { kind: profile.kind } : {}),
278
+ ...(profile?.expiresAt ? { expiresAt: profile.expiresAt, expired } : {}),
279
+ };
280
+ if (values.json)
281
+ printJson(deps, status);
282
+ else
283
+ deps.io.out([
284
+ `Profile: ${creds.profile ?? "(none — KUMION_API_KEY from the environment)"}`,
285
+ `Tenant: ${creds.tenantId}`,
286
+ `Base URL: ${creds.baseUrl}`,
287
+ `Key: ${status.key} (${creds.source === "env" ? "environment" : "OS keychain"})`,
288
+ ...(profile?.kind === "personal" ? ["Kind: personal (from the browser login)"] : []),
289
+ ...(profile?.expiresAt
290
+ ? [
291
+ `Expires: ${profile.expiresAt}` +
292
+ (expired ? " — expired; run `kumion auth login` again" : ""),
293
+ ]
294
+ : []),
295
+ ].join("\n"));
296
+ return 0;
297
+ }
298
+ async function authList(args, deps) {
299
+ const { values } = parse(args, {});
300
+ const config = await deps.config.read();
301
+ if (values.json) {
302
+ printJson(deps, config);
303
+ return 0;
304
+ }
305
+ const names = Object.keys(config.profiles);
306
+ if (names.length === 0) {
307
+ deps.io.out("No saved profiles. Run `kumion auth login`.");
308
+ return 0;
309
+ }
310
+ for (const name of names) {
311
+ const p = config.profiles[name];
312
+ deps.io.out(`${name === config.defaultProfile ? "*" : " "} ${name} tenant ${p.tenantId} ${p.baseUrl ?? DEFAULT_BASE_URL}`);
313
+ }
314
+ return 0;
315
+ }
316
+ async function authUse(args, deps) {
317
+ const { positionals } = parse(args, {});
318
+ const name = need(positionals, 0, "profile");
319
+ const config = await deps.config.read();
320
+ if (!config.profiles[name])
321
+ throw new UsageError(`No profile named "${name}".`);
322
+ config.defaultProfile = name;
323
+ await deps.config.write(config);
324
+ deps.io.out(`Default profile is now "${name}".`);
325
+ return 0;
326
+ }
327
+ async function authLogout(args, deps) {
328
+ const { values } = parse(args, {});
329
+ const config = await deps.config.read();
330
+ const name = values.profile ?? config.defaultProfile;
331
+ if (!name || !config.profiles[name])
332
+ throw new UsageError(name ? `No profile named "${name}".` : "Not logged in.");
333
+ await deps.secrets().delete(name);
334
+ delete config.profiles[name];
335
+ if (config.defaultProfile === name)
336
+ config.defaultProfile = Object.keys(config.profiles)[0];
337
+ await deps.config.write(config);
338
+ deps.io.out(`Removed profile "${name}" and its key from the keychain.`);
339
+ return 0;
340
+ }
341
+ async function agentsList(args, deps) {
342
+ const { values } = parse(args, {});
343
+ const agents = await (await clientFor(values, deps)).listAgents();
344
+ if (values.json)
345
+ printJson(deps, { agents });
346
+ else if (agents.length === 0)
347
+ deps.io.out("No agents.");
348
+ else
349
+ for (const a of agents)
350
+ deps.io.out(`${a.id} ${a.publishedAt ? "published" : "draft "} ${a.name}`);
351
+ return 0;
352
+ }
353
+ async function agentsGet(args, deps) {
354
+ const { values, positionals } = parse(args, {});
355
+ const agentId = need(positionals, 0, "agentId");
356
+ const view = await (await clientFor(values, deps)).getAgent(agentId);
357
+ if (values.json) {
358
+ printJson(deps, view);
359
+ return 0;
360
+ }
361
+ const prompt = view.draft.prompt ?? "";
362
+ deps.io.out([
363
+ `${view.agent.name} (${view.agent.id})`,
364
+ `Revision: ${view.revision} (pass to \`agents patch --revision\`)`,
365
+ `Published: ${view.published ? `${view.published.publishedAt} (version ${view.published.version ?? "?"}, check: ${view.published.regression})` : "never"}`,
366
+ ...(view.agent.archivedAt ? [`Archived: ${view.agent.archivedAt} — not callable`] : []),
367
+ ...(view.publishState?.live && view.publishState.unpublishedChanges
368
+ ? ["Draft: has changes that are not published yet"]
369
+ : []),
370
+ `Flow: ${view.agent.workflowId ? "yes" : "none (prompt-only agent)"}`,
371
+ ...(view.draft.callModel?.error ? [`Model: problem — ${view.draft.callModel.error}`] : []),
372
+ `Prompt: ${prompt ? `${prompt.length} chars — ${JSON.stringify(prompt.slice(0, 80))}${prompt.length > 80 ? "…" : ""}` : "(empty)"}`,
373
+ "Use --json for the full draft and published configuration.",
374
+ ].join("\n"));
375
+ return 0;
376
+ }
377
+ async function agentsPatch(args, deps) {
378
+ const { values, positionals } = parse(args, {
379
+ revision: { type: "string" },
380
+ prompt: { type: "string" },
381
+ "prompt-file": { type: "string" },
382
+ "graph-file": { type: "string" },
383
+ });
384
+ const agentId = need(positionals, 0, "agentId");
385
+ if (values.prompt !== undefined && values["prompt-file"]) {
386
+ throw new UsageError("Pass --prompt or --prompt-file, not both.");
387
+ }
388
+ const patch = {};
389
+ let revision = values.revision;
390
+ if (values.prompt !== undefined)
391
+ patch.prompt = values.prompt;
392
+ if (values["prompt-file"]) {
393
+ try {
394
+ patch.prompt = await readFile(values["prompt-file"], "utf8");
395
+ }
396
+ catch (err) {
397
+ throw new UsageError(`Cannot read ${values["prompt-file"]}: ${err.message}`);
398
+ }
399
+ }
400
+ if (values["graph-file"]) {
401
+ const file = (await readJsonFile(values["graph-file"]));
402
+ const draft = file && typeof file.draft === "object" ? file.draft : null;
403
+ if (draft) {
404
+ if (!draft.graph)
405
+ throw new UsageError(`${values["graph-file"]} has no draft.graph — this agent has no flow to edit.`);
406
+ patch.graph = draft.graph;
407
+ if (!revision && typeof file?.revision === "string")
408
+ revision = file.revision;
409
+ }
410
+ else {
411
+ patch.graph = file;
412
+ }
413
+ }
414
+ if (patch.prompt === undefined && patch.graph === undefined) {
415
+ throw new UsageError("Nothing to change. Pass --prompt, --prompt-file or --graph-file.");
416
+ }
417
+ if (!revision) {
418
+ throw new UsageError("Pass --revision <rev> — the revision `kumion agents get` showed when you read the draft you are changing.");
419
+ }
420
+ const view = await (await clientFor(values, deps)).patchAgent(agentId, patch, revision);
421
+ if (values.json)
422
+ printJson(deps, view);
423
+ else
424
+ deps.io.out(`Draft saved. New revision: ${view.revision}\nNothing is live until you run \`kumion agents publish ${agentId}\`.`);
425
+ return 0;
426
+ }
427
+ function formatFindings(findings, indent) {
428
+ return (findings ?? []).map((f) => `${indent}- ${f.kind}${f.nodeKey ? ` @${f.nodeKey}` : ""}: ${f.detail}`);
429
+ }
430
+ async function agentsPublish(args, deps) {
431
+ const { values, positionals } = parse(args, { revision: { type: "string" } });
432
+ const agentId = need(positionals, 0, "agentId");
433
+ const client = await clientFor(values, deps);
434
+ deps.io.err("Publishing — the pre-publish check runs first and can take a few minutes…");
435
+ try {
436
+ const result = await client.publishAgent(agentId, values.revision);
437
+ if (values.json)
438
+ printJson(deps, result);
439
+ else {
440
+ const agent = result.agent;
441
+ deps.io.out(`Published ${agent?.name ?? agentId} at ${agent?.publishedAt ?? "?"} (publish run ${String(result.publishRunId ?? "?")}).`);
442
+ }
443
+ return 0;
444
+ }
445
+ catch (err) {
446
+ if (!(err instanceof ApiError && err.status === 422))
447
+ throw err;
448
+ const body = err.body;
449
+ if (values.json)
450
+ printJson(deps, body);
451
+ const lines = [`Not published — the pre-publish check did not pass.`, `Server said: ${String(body.error ?? "")}`];
452
+ const verdict = body.regression;
453
+ if (verdict?.detail)
454
+ lines.push(verdict.detail);
455
+ if (verdict?.structural?.length) {
456
+ lines.push("Structural problems:");
457
+ lines.push(...formatFindings(verdict.structural, " "));
458
+ }
459
+ if (Array.isArray(verdict?.cases)) {
460
+ for (const c of verdict.cases) {
461
+ if (!c.failures?.length)
462
+ continue;
463
+ lines.push(` case ${c.caseId ?? "?"}${c.expectedLeafKey ? ` (→ ${c.expectedLeafKey})` : ""}:`);
464
+ lines.push(...formatFindings(c.failures, " "));
465
+ }
466
+ }
467
+ if (body.publishRunId)
468
+ lines.push(`Publish run: ${String(body.publishRunId)} (details in the Portal).`);
469
+ lines.push("There is no override from the CLI: fix the draft, run `kumion test-runs start`, and publish again.");
470
+ throw new ReportedFailure(lines.join("\n"));
471
+ }
472
+ }
473
+ const TERMINAL = new Set(["passed", "failed", "could_not_run", "timeout", "cancelled"]);
474
+ export function summarizeTestRun(run) {
475
+ const lines = [
476
+ `Test run ${run.id}: ${run.status.toUpperCase()} (${run.casesDone}/${run.casesTotal} cases)`,
477
+ ];
478
+ if (run.status !== "passed") {
479
+ if (run.structural?.length) {
480
+ lines.push("Structural problems:");
481
+ lines.push(...formatFindings(run.structural, " "));
482
+ }
483
+ for (const r of run.results ?? []) {
484
+ if (!r.failures?.length)
485
+ continue;
486
+ lines.push(`Case ${r.caseId}${r.expectedLeafKey ? ` (→ ${r.expectedLeafKey})` : ""}:`);
487
+ lines.push(...formatFindings(r.failures, " "));
488
+ }
489
+ }
490
+ return lines.join("\n");
491
+ }
492
+ async function testRunsStart(args, deps) {
493
+ const { values, positionals } = parse(args, {
494
+ "no-wait": { type: "boolean" },
495
+ interval: { type: "string" },
496
+ timeout: { type: "string" },
497
+ });
498
+ const agentId = need(positionals, 0, "agentId");
499
+ const intervalMs = positiveNumber(values.interval, "interval", 3) * 1000;
500
+ const timeoutMs = positiveNumber(values.timeout, "timeout", 900) * 1000;
501
+ const client = await clientFor(values, deps);
502
+ let run = await client.startTestRun(agentId);
503
+ if (values["no-wait"]) {
504
+ if (values.json)
505
+ printJson(deps, { testRun: run });
506
+ else
507
+ deps.io.out(`Started test run ${run.id}. Follow it with \`kumion test-runs get ${agentId} ${run.id}\`.`);
508
+ return 0;
509
+ }
510
+ deps.io.err(`Test run ${run.id} started.`);
511
+ let waited = 0;
512
+ let lastProgress = "";
513
+ while (!TERMINAL.has(run.status)) {
514
+ if (waited >= timeoutMs) {
515
+ throw new ReportedFailure(`Stopped waiting after ${timeoutMs / 1000}s; the run is still going on the server. ` +
516
+ `Check it later with \`kumion test-runs get ${agentId} ${run.id}\`.`);
517
+ }
518
+ await deps.sleep(intervalMs);
519
+ waited += intervalMs;
520
+ run = await client.getTestRun(agentId, run.id);
521
+ const progress = `${run.casesDone}/${run.casesTotal}`;
522
+ if (progress !== lastProgress && run.status === "running")
523
+ deps.io.err(` ${progress} cases done…`);
524
+ lastProgress = progress;
525
+ }
526
+ if (values.json)
527
+ printJson(deps, { testRun: run });
528
+ else
529
+ deps.io.out(summarizeTestRun(run));
530
+ return run.status === "passed" ? 0 : 1;
531
+ }
532
+ async function testRunsGet(args, deps) {
533
+ const { values, positionals } = parse(args, {});
534
+ const agentId = need(positionals, 0, "agentId");
535
+ const runId = need(positionals, 1, "runId");
536
+ const run = await (await clientFor(values, deps)).getTestRun(agentId, runId);
537
+ if (values.json)
538
+ printJson(deps, { testRun: run });
539
+ else
540
+ deps.io.out(summarizeTestRun(run));
541
+ return 0;
542
+ }
543
+ async function testRunsList(args, deps) {
544
+ const { values, positionals } = parse(args, { limit: { type: "string" } });
545
+ const agentId = need(positionals, 0, "agentId");
546
+ const limit = values.limit ? positiveNumber(values.limit, "limit", 10) : undefined;
547
+ const runs = await (await clientFor(values, deps)).listTestRuns(agentId, limit);
548
+ if (values.json)
549
+ printJson(deps, { testRuns: runs });
550
+ else if (runs.length === 0)
551
+ deps.io.out("No test runs yet.");
552
+ else
553
+ for (const r of runs)
554
+ deps.io.out(`${r.id} ${r.status.padEnd(13)} ${r.casesDone}/${r.casesTotal} ${r.startedAt}`);
555
+ return 0;
556
+ }
557
+ async function callsCreate(args, deps) {
558
+ const { values, positionals } = parse(args, { "campaign-contact": { type: "string" } });
559
+ const agentId = need(positionals, 0, "agentId");
560
+ const result = await (await clientFor(values, deps)).createCall(agentId, values["campaign-contact"]);
561
+ if (values.json)
562
+ printJson(deps, result);
563
+ else
564
+ deps.io.out([
565
+ `Call started with ${String(result.agentName ?? agentId)}.`,
566
+ `Call log: ${String(result.callLogId)}`,
567
+ `Room: ${String(result.roomName)}`,
568
+ `LiveKit: ${String(result.livekitUrl)}`,
569
+ "Join with the participant token from --json output.",
570
+ ].join("\n"));
571
+ return 0;
572
+ }
573
+ function wholeNumber(raw, flag) {
574
+ if (raw === undefined)
575
+ return undefined;
576
+ const n = Number(raw);
577
+ if (!Number.isInteger(n) || n < 0)
578
+ throw new UsageError(`--${flag} must be a whole number (0 or more).`);
579
+ return n;
580
+ }
581
+ async function callsList(args, deps) {
582
+ const { values } = parse(args, {
583
+ agent: { type: "string" },
584
+ channel: { type: "string" },
585
+ from: { type: "string" },
586
+ to: { type: "string" },
587
+ search: { type: "string" },
588
+ limit: { type: "string" },
589
+ offset: { type: "string" },
590
+ });
591
+ const filter = {
592
+ agentId: values.agent,
593
+ channel: values.channel,
594
+ from: values.from,
595
+ to: values.to,
596
+ q: values.search,
597
+ limit: values.limit === undefined ? undefined : positiveNumber(values.limit, "limit", 20),
598
+ offset: wholeNumber(values.offset, "offset"),
599
+ };
600
+ const page = await (await clientFor(values, deps)).listCalls(filter);
601
+ if (values.json) {
602
+ printJson(deps, page);
603
+ return 0;
604
+ }
605
+ if (page.calls.length === 0) {
606
+ deps.io.out(page.total > 0 ? `No calls on this page (${page.total} in total).` : "No calls.");
607
+ return 0;
608
+ }
609
+ for (const c of page.calls) {
610
+ deps.io.out([
611
+ c.id,
612
+ c.startedAt,
613
+ (c.channel ?? c.source).padEnd(10),
614
+ (c.remoteE164 ?? "-").padEnd(14),
615
+ c.hasTranscript ? "transcript" : "- ",
616
+ c.agentName ?? c.agentId ?? "-",
617
+ ].join(" "));
618
+ }
619
+ const last = page.offset + page.calls.length;
620
+ deps.io.out(`${page.offset + 1}–${last} of ${page.total}.` +
621
+ (last < page.total ? ` Next page: --offset ${last}${page.limit !== 20 ? ` --limit ${page.limit}` : ""}` : ""));
622
+ return 0;
623
+ }
624
+ async function callsGet(args, deps) {
625
+ const { values, positionals } = parse(args, {});
626
+ const callId = need(positionals, 0, "callId");
627
+ const call = await (await clientFor(values, deps)).getCall(callId);
628
+ if (values.json) {
629
+ printJson(deps, { call });
630
+ return 0;
631
+ }
632
+ deps.io.out([
633
+ `Call ${call.id}`,
634
+ `Agent: ${call.agentName ?? "-"}${call.agentId ? ` (${call.agentId})` : ""}`,
635
+ `Source: ${call.source}${call.direction ? ` (${call.direction})` : ""}`,
636
+ `Caller: ${call.remoteE164 ?? "-"}${call.localE164 ? ` → ${call.localE164}` : ""}`,
637
+ `Started: ${call.startedAt}`,
638
+ `Answered: ${call.answeredAt ?? "-"}`,
639
+ `Ended: ${call.endedAt ?? "(still up)"}${call.endedReason ? ` — ${call.endedReason}` : ""}`,
640
+ `Disposition: ${call.disposition ?? "-"}${call.isVoicemail ? " (voicemail)" : ""}`,
641
+ ...(call.ticketNo ? [`Ticket: ${call.ticketNo}`] : []),
642
+ `Transcript: ${call.hasTranscript ? `yes — \`kumion calls transcript ${call.id}\`` : "none yet"}`,
643
+ ].join("\n"));
644
+ return 0;
645
+ }
646
+ export function formatTranscript(transcript) {
647
+ if (!transcript.available) {
648
+ return "No transcript yet — it is written when the call ends, and a call that never connected has none.";
649
+ }
650
+ if (transcript.turns.length === 0)
651
+ return "The transcript is empty: nobody said anything.";
652
+ return transcript.turns
653
+ .map((t) => `${t.at ? `[${t.at}] ` : ""}${t.role === "user" ? "Caller" : "Agent "}: ${t.text}`)
654
+ .join("\n");
655
+ }
656
+ async function callsTranscript(args, deps) {
657
+ const { values, positionals } = parse(args, {});
658
+ const callId = need(positionals, 0, "callId");
659
+ const transcript = await (await clientFor(values, deps)).getTranscript(callId);
660
+ if (values.json)
661
+ printJson(deps, { transcript });
662
+ else
663
+ deps.io.out(formatTranscript(transcript));
664
+ return 0;
665
+ }
666
+ async function mcpServe(args, deps) {
667
+ const { values } = parse(args, {});
668
+ const client = await clientFor(values, deps);
669
+ const { createKumionMcpServer } = await import("./mcp.js");
670
+ const server = createKumionMcpServer(client, { version: VERSION, sleep: deps.sleep });
671
+ if (!deps.mcpTransport)
672
+ throw new Error("No MCP transport configured.");
673
+ const transport = await deps.mcpTransport();
674
+ const closed = new Promise((resolve) => {
675
+ server.server.onclose = resolve;
676
+ });
677
+ await server.connect(transport);
678
+ deps.io.err(`kumion MCP server ready (tenant ${client.tenantId}).`);
679
+ await closed;
680
+ return 0;
681
+ }