@kumion/cli 0.3.0 → 0.5.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 CHANGED
@@ -1,10 +1,11 @@
1
- import { readFile } from "node:fs/promises";
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
2
3
  import { parseArgs } from "node:util";
3
- import { ApiError, KumionClient, } from "./client.js";
4
+ import { ApiError, KumionClient, isTextFile, specText, } from "./client.js";
4
5
  import { DEFAULT_BASE_URL, keyPrefix, looksLikeApiKey, normalizeBaseUrl, resolveCredentials, } from "./credentials.js";
5
6
  import { DEFAULT_DEVICE_SCOPES, deviceLogin } from "./device-login.js";
6
7
  import { describeError, ReportedFailure, UsageError } from "./errors.js";
7
- export const VERSION = "0.3.0";
8
+ export const VERSION = "0.5.0";
8
9
  const HELP = `kumion — manage your Kumion voice agents over the Partner API
9
10
 
10
11
  Usage: kumion <command> [options]
@@ -24,6 +25,13 @@ Auth
24
25
  Agents
25
26
  agents list List the tenant's agents
26
27
  agents get <agentId> Show an agent's draft and published version
28
+ agents spec <agentId> [--version published|draft|<n>] [--format pdf|docx|markdown] [--out <path>]
29
+ Download the 応対仕様書 (the agent's settings as a document) for
30
+ a version: 公開中 by default, or the draft / a version number.
31
+ PDF by default; Word (docx) and Markdown too. Writes to --out;
32
+ Markdown without --out goes to stdout, and PDF/Word without --out
33
+ to the file the server names, in the current directory. The
34
+ 出力日時 on the cover is the moment of the export
27
35
  agents patch <agentId> --revision <rev> [--prompt <text> | --prompt-file <path>] [--graph-file <path>]
28
36
  Edit the draft (never goes live by itself)
29
37
  agents publish <agentId> [--revision <rev>]
@@ -81,6 +89,52 @@ Staff (the people a 用件 can transfer a call to)
81
89
  publish (needs a key with agents:live). --enabled false takes
82
90
  them out of the 転送 candidates
83
91
 
92
+ Hours (when the shop is open — one calendar for the whole tenant)
93
+ hours get [--from <date>] [--to <date>]
94
+ Show 営業時間, 定休日, 祝日休み and the 例外日 in a window,
95
+ with the revision the two writes below need
96
+ hours update --revision <rev> [--business-hours-file <path>] [--closed-rules-file <path>]
97
+ [--observe-jp-holidays true|false] [--dry-run]
98
+ Change the clock. businessHours and closedRules are whole
99
+ replacements; an omitted field is left alone. LIVE: the next
100
+ call answers from it, no publish (needs agents:live)
101
+ hours exception set <date> --revision <rev> --kind closed|open|inherit [--hours-file <path>]
102
+ [--note <text>] [--dry-run]
103
+ One 例外日: closed = 臨時休業, open = 振替出勤 (with its own
104
+ hours, or the weekday's), inherit = back to the weekly rule.
105
+ LIVE (needs agents:live)
106
+
107
+ Booking (予約設定 — one calendar for the tenant, read per agent)
108
+ booking get <agentId> Show the slot length, the lead time and the horizon, the
109
+ 内容 and 担当, and whether this agent takes bookings, with
110
+ the revision every booking write below needs
111
+ booking calendar update --revision <rev> --patch-file <path> [--dry-run]
112
+ Change 枠の長さ (defaultSlotMinutes), 直前予約の締め切り
113
+ (minLeadMinutes) and/or 何日先まで (maxAdvanceDays); an
114
+ omitted field is left alone. LIVE (needs agents:live)
115
+ booking services create --revision <rev> --data-file <path> [--dry-run]
116
+ Add one 内容: name, and durationMinutes (1–1440, or null to
117
+ use the slot length). LIVE (needs agents:live)
118
+ booking services update <serviceId> --revision <rev> --patch-file <path> [--dry-run]
119
+ Change one 内容's name and/or durationMinutes; null goes
120
+ back to the slot length. LIVE (needs agents:live)
121
+ booking resources create --revision <rev> --data-file <path> [--dry-run]
122
+ Add one 担当: name, enabled, weeklyHours (予約枠) and the
123
+ serviceIds it takes ([] = every 内容). One 内容 that is not
124
+ this tenant's refuses the whole write. LIVE (needs agents:live)
125
+ booking resources update <resourceId> --revision <rev> --patch-file <path> [--dry-run]
126
+ Change a 担当; an omitted field is left alone, enabled=false
127
+ takes it out of service without deleting it. LIVE
128
+ booking mount <agentId> --mounted true|false --revision <rev> [--dry-run]
129
+ Start or stop taking bookings. Mounting also retires the
130
+ 「仮受付」 promise from the 受付サマリー, in the same write.
131
+ LIVE (needs agents:live)
132
+ booking slots <agentId> --resource <resourceId> --date <YYYY-MM-DD>
133
+ [--service <serviceId>] [--limit <n>]
134
+ One 担当's openings on one day, computed the way a call
135
+ computes them (6 by default, at most 20). Reads only —
136
+ nothing is reserved (needs agents:read)
137
+
84
138
  Facts (the agent's 資料)
85
139
  facts list <agentId> List the facts with their state and revision
86
140
  facts edit <agentId> <factId> --revision <rev> --value <text>
@@ -89,6 +143,46 @@ Facts (the agent's 資料)
89
143
  Confirm pending facts as extracted (all of them without
90
144
  --fact; a fact whose candidates disagree is skipped). LIVE
91
145
 
146
+ Capture specs (記録項目 — what the agent records after a call)
147
+ capture-specs list List the 記録項目 with their revision and the agents each is
148
+ mounted on
149
+ capture-specs create --data-file <path>
150
+ Add one 記録項目 (name, fields, optional 場面). Without an
151
+ instruction the API writes one from those — no model is
152
+ called. It is mounted on no agent yet, so no call changes
153
+ (needs agents:write)
154
+ capture-specs update <specId> --revision <rev> --patch-file <path>
155
+ Change one 記録項目; an omitted field is left alone and key is
156
+ frozen. LIVE: every agent mounted with it records differently
157
+ from its next call (needs agents:live)
158
+ agents capture get <agentId> Show which 記録項目 this agent records, its revision, and
159
+ whether THIS agent would record after a call
160
+ agents capture set <agentId> --revision <rev> (--spec <specId> ... | --clear)
161
+ Replace the whole set this agent records (--spec repeats;
162
+ --clear is []; the two cannot be combined). LIVE: the next
163
+ call's summary is written from the new set, no publish
164
+ (needs agents:live)
165
+
166
+ Documents (資料 — the source an agent's facts are extracted from)
167
+ documents upload (--text-file <path> | --file <path> [--file <path> ...])
168
+ --title <title> --idempotency-key <key> [--template <templateId>] [--dry-run]
169
+ Upload a 資料 — its text, or files (.txt / .md / .pdf / .docx /
170
+ .xlsx, up to 10 files and 20MiB) — and get a job back at once
171
+ (the extraction runs after). Several files become ONE manual,
172
+ in the order given. Same key + same content answers the same
173
+ job; different content under the same key is refused
174
+ (needs agents:write). --dry-run shows the size, the model and
175
+ the remaining allowance, and calls no model
176
+ documents jobs get <jobId> Show an upload job: status, the document it produced, the error.
177
+ Exits non-zero when the job failed or timed out
178
+ documents get <documentId> Show a 資料: its fields, review state and revision (not the text)
179
+ documents replace <documentId> --source <sourceDocumentId> --source-revision <rev> --revision <rev>
180
+ [--dry-run]
181
+ Give a 資料 another document's content and facts, keeping its id, so the
182
+ agents already reading it switch with no re-creation. Every fact comes back
183
+ pending, and a fact the new source does not mention stays as an empty row.
184
+ LIVE: the next call reads the new facts. Needs agents:live
185
+
92
186
  Test runs
93
187
  test-runs start <agentId> [--no-wait] [--interval <sec>] [--timeout <sec>]
94
188
  Run the agent's regression tests against its draft
@@ -102,6 +196,10 @@ Calls
102
196
  calls list [--agent <id>] [--channel webcall|sip_did|trigger] [--from <iso>] [--to <iso>]
103
197
  [--search <text>] [--limit <n>] [--offset <n>]
104
198
  List the tenant's call history, newest first (20 per page)
199
+ scheduled-calls create <agentId> --to <phone> --at <iso8601-with-offset>
200
+ Schedule one dial at that time (e.g. 2026-10-31T13:00:00+09:00)
201
+ scheduled-calls list List the dials scheduled through the API, newest first
202
+ scheduled-calls cancel <id> Cancel a scheduled dial that has not started
105
203
  calls get <callId> Show one call: source, numbers, times, how it ended
106
204
  calls transcript <callId> Print what the caller and the agent said
107
205
  (list/get/transcript need a key with calls:read)
@@ -198,11 +296,13 @@ async function dispatch(argv, deps) {
198
296
  }
199
297
  if (group === "mcp")
200
298
  return mcpServe(argv.slice(1), deps);
201
- const handler = COMMANDS[`${group} ${command ?? ""}`.trim()];
202
- if (!handler) {
299
+ const two = `${group} ${command ?? ""}`.trim();
300
+ const three = rest.length > 0 ? `${two} ${rest[0]}` : two;
301
+ const name = Object.hasOwn(COMMANDS, three) ? three : Object.hasOwn(COMMANDS, two) ? two : null;
302
+ if (!name) {
203
303
  throw new UsageError(`Unknown command: kumion ${[group, command].filter(Boolean).join(" ")}\nRun \`kumion --help\` for usage.`);
204
304
  }
205
- return handler(rest, deps);
305
+ return COMMANDS[name](name === three ? rest.slice(1) : rest, deps);
206
306
  }
207
307
  async function clientFor(values, deps) {
208
308
  const creds = await resolveCredentials({
@@ -225,6 +325,7 @@ export const COMMANDS = {
225
325
  "auth logout": authLogout,
226
326
  "agents list": agentsList,
227
327
  "agents get": agentsGet,
328
+ "agents spec": agentsSpec,
228
329
  "agents patch": agentsPatch,
229
330
  "agents publish": agentsPublish,
230
331
  "agents opening-name": agentsOpeningName,
@@ -237,12 +338,35 @@ export const COMMANDS = {
237
338
  "staff list": staffList,
238
339
  "staff create": staffCreate,
239
340
  "staff update": staffUpdate,
341
+ "hours get": hoursGet,
342
+ "hours update": hoursUpdate,
343
+ "hours exception set": hoursExceptionSet,
344
+ "booking get": bookingGet,
345
+ "booking calendar update": bookingCalendarUpdate,
346
+ "booking services create": bookingServicesCreate,
347
+ "booking services update": bookingServicesUpdate,
348
+ "booking resources create": bookingResourcesCreate,
349
+ "booking resources update": bookingResourcesUpdate,
350
+ "booking mount": bookingMount,
351
+ "booking slots": bookingSlots,
240
352
  "facts list": factsList,
241
353
  "facts edit": factsEdit,
242
354
  "facts confirm": factsConfirm,
355
+ "capture-specs list": captureSpecsList,
356
+ "capture-specs create": captureSpecsCreate,
357
+ "capture-specs update": captureSpecsUpdate,
358
+ "agents capture get": agentsCaptureGet,
359
+ "agents capture set": agentsCaptureSet,
360
+ "documents upload": documentsUpload,
361
+ "documents jobs get": documentsJobsGet,
362
+ "documents get": documentsGet,
363
+ "documents replace": documentsReplace,
243
364
  "test-runs start": testRunsStart,
244
365
  "test-runs get": testRunsGet,
245
366
  "test-runs list": testRunsList,
367
+ "scheduled-calls create": scheduledCallsCreate,
368
+ "scheduled-calls list": scheduledCallsList,
369
+ "scheduled-calls cancel": scheduledCallsCancel,
246
370
  "calls create": callsCreate,
247
371
  "calls list": callsList,
248
372
  "calls get": callsGet,
@@ -448,6 +572,50 @@ async function agentsGet(args, deps) {
448
572
  ].join("\n"));
449
573
  return 0;
450
574
  }
575
+ async function agentsSpec(args, deps) {
576
+ const { values, positionals } = parse(args, {
577
+ version: { type: "string" },
578
+ format: { type: "string" },
579
+ out: { type: "string" },
580
+ });
581
+ const agentId = need(positionals, 0, "agentId");
582
+ const version = values.version;
583
+ if (version !== undefined && version !== "published" && version !== "draft" && !/^[1-9]\d*$/.test(version)) {
584
+ throw new UsageError("--version takes published (公開中), draft (下書き), or a version number (1, 2, …).");
585
+ }
586
+ const file = await (await clientFor(values, deps)).getAgentSpec(agentId, {
587
+ ...(version === undefined ? {} : { version }),
588
+ ...(values.format === undefined ? {} : { format: values.format }),
589
+ });
590
+ const text = isTextFile(file);
591
+ const bytes = file.body.byteLength;
592
+ const target = values.out ?? (text ? null : file.filename ?? defaultSpecName(agentId, file.contentType));
593
+ if (target === null) {
594
+ if (values.json) {
595
+ printJson(deps, { filename: file.filename, contentType: file.contentType, markdown: specText(file) });
596
+ return 0;
597
+ }
598
+ deps.io.out(specText(file).replace(/\n$/, ""));
599
+ return 0;
600
+ }
601
+ const path = values.out ? values.out : join((deps.cwd ?? process.cwd)(), target);
602
+ try {
603
+ await writeFile(path, file.body);
604
+ }
605
+ catch (err) {
606
+ throw new UsageError(`Cannot write ${path}: ${err.message}`);
607
+ }
608
+ if (values.json) {
609
+ printJson(deps, { path, filename: file.filename, contentType: file.contentType, bytes });
610
+ return 0;
611
+ }
612
+ deps.io.out(`Wrote ${path} (${file.filename ?? "仕様書"}, ${bytes} bytes)`);
613
+ return 0;
614
+ }
615
+ function defaultSpecName(agentId, contentType) {
616
+ const extension = contentType === "application/pdf" ? "pdf" : contentType?.includes("wordprocessingml") ? "docx" : "bin";
617
+ return `仕様書_${agentId}.${extension}`;
618
+ }
451
619
  async function agentsPatch(args, deps) {
452
620
  const { values, positionals } = parse(args, {
453
621
  revision: { type: "string" },
@@ -617,7 +785,7 @@ async function agentsCreateFromTemplate(args, deps) {
617
785
  deps.io.out("");
618
786
  deps.io.out(`${result.missing.length} 件は資料から読み取れませんでした。アシスタントで足すか、このまま公開できます。`);
619
787
  }
620
- deps.io.out("Next: `kumion agents get <id>`, `kumion test-runs start <id>`, `kumion agents publish <id>`.");
788
+ deps.io.out("Next: `kumion facts list <id>`, `kumion facts confirm <id>`, `kumion agents get <id>`, `kumion test-runs start <id>`, `kumion agents publish <id>`.");
621
789
  return 0;
622
790
  }
623
791
  function staffLine(staff) {
@@ -714,6 +882,659 @@ async function staffUpdate(args, deps) {
714
882
  deps.io.out("This スタッフ is not a 転送 candidate now (disabled, or missing a 転送先).");
715
883
  return 0;
716
884
  }
885
+ const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
886
+ function hoursText(hours) {
887
+ const lines = [];
888
+ lines.push(`Revision ${hours.revision} (pass to \`hours update --revision\`)`);
889
+ lines.push(`Timezone ${hours.timezone} 祝日休み: ${hours.observeJpHolidays ? "yes" : "no"}`);
890
+ const open = WEEKDAYS.filter((day) => (hours.businessHours[day] ?? []).length > 0);
891
+ if (open.length === 0)
892
+ lines.push("営業時間: not set (every day is answered as 未設定)");
893
+ else {
894
+ lines.push("営業時間:");
895
+ for (const day of WEEKDAYS) {
896
+ const ranges = hours.businessHours[day] ?? [];
897
+ lines.push(` ${day} ${ranges.length === 0 ? "closed" : ranges.map((r) => `${r.start}-${r.end}`).join(", ")}`);
898
+ }
899
+ }
900
+ lines.push(`定休日: ${hours.closedRules.length} rule(s)`);
901
+ if (hours.exceptions.length === 0)
902
+ lines.push("例外日: none in this window");
903
+ else {
904
+ lines.push("例外日:");
905
+ for (const exception of hours.exceptions) {
906
+ const what = exception.kind === "closed" ? "臨時休業" : "振替出勤";
907
+ const when = exception.hours && exception.hours.length > 0
908
+ ? ` ${exception.hours.map((r) => `${r.start}-${r.end}`).join(", ")}`
909
+ : "";
910
+ lines.push(` ${exception.closedOn} ${what}${when}${exception.note ? ` (${exception.note})` : ""}`);
911
+ }
912
+ }
913
+ if (hours.affectedAgentIds.length > 0) {
914
+ lines.push(`This calendar is read by ${hours.affectedAgentIds.length} agent(s): ${hours.affectedAgentIds.join(", ")}`);
915
+ }
916
+ return lines;
917
+ }
918
+ async function hoursGet(args, deps) {
919
+ const { values } = parse(args, { from: { type: "string" }, to: { type: "string" } });
920
+ const hours = await (await clientFor(values, deps)).getStoreHours({ from: values.from, to: values.to });
921
+ if (values.json)
922
+ printJson(deps, hours);
923
+ else
924
+ for (const line of hoursText(hours))
925
+ deps.io.out(line);
926
+ return 0;
927
+ }
928
+ function parseYesNo(raw, flag) {
929
+ if (raw === undefined)
930
+ return undefined;
931
+ if (raw === "true")
932
+ return true;
933
+ if (raw === "false")
934
+ return false;
935
+ throw new UsageError(`--${flag} takes true or false.`);
936
+ }
937
+ const HOURS_REVISION_HELP = "the revision `kumion hours get` showed for the clock you are changing.";
938
+ async function hoursUpdate(args, deps) {
939
+ const { values } = parse(args, {
940
+ revision: { type: "string" },
941
+ "business-hours-file": { type: "string" },
942
+ "closed-rules-file": { type: "string" },
943
+ "observe-jp-holidays": { type: "string" },
944
+ "dry-run": { type: "boolean" },
945
+ });
946
+ const patch = {};
947
+ if (values["business-hours-file"] !== undefined) {
948
+ patch.businessHours = (await readJsonFile(values["business-hours-file"]));
949
+ }
950
+ if (values["closed-rules-file"] !== undefined) {
951
+ patch.closedRules = (await readJsonFile(values["closed-rules-file"]));
952
+ }
953
+ const observe = parseYesNo(values["observe-jp-holidays"], "observe-jp-holidays");
954
+ if (observe !== undefined)
955
+ patch.observeJpHolidays = observe;
956
+ if (Object.keys(patch).length === 0) {
957
+ throw new UsageError("Nothing to change. Pass --business-hours-file, --closed-rules-file or --observe-jp-holidays.");
958
+ }
959
+ const revision = requireRevision(values.revision, HOURS_REVISION_HELP);
960
+ const hours = await (await clientFor(values, deps)).updateStoreHours(patch, revision, { dryRun: values["dry-run"] });
961
+ if (values.json) {
962
+ printJson(deps, hours);
963
+ return 0;
964
+ }
965
+ if (values["dry-run"]) {
966
+ deps.io.out(`Dry run: nothing was saved. The calendar is at revision ${hours.revision}.`);
967
+ for (const line of hoursText(hours).slice(1))
968
+ deps.io.out(line);
969
+ return 0;
970
+ }
971
+ deps.io.out(`Saved and live now — no publish needed. New revision: ${hours.revision}`);
972
+ if (hours.affectedAgentIds.length > 0) {
973
+ deps.io.out(`The next call on ${hours.affectedAgentIds.length} agent(s) answers from this clock.`);
974
+ }
975
+ return 0;
976
+ }
977
+ const EXCEPTION_KINDS = ["closed", "open", "inherit"];
978
+ async function hoursExceptionSet(args, deps) {
979
+ const { values, positionals } = parse(args, {
980
+ revision: { type: "string" },
981
+ kind: { type: "string" },
982
+ "hours-file": { type: "string" },
983
+ note: { type: "string" },
984
+ "dry-run": { type: "boolean" },
985
+ });
986
+ const date = need(positionals, 0, "date");
987
+ const kind = values.kind;
988
+ if (!kind || !EXCEPTION_KINDS.includes(kind)) {
989
+ throw new UsageError("Pass --kind closed|open|inherit.");
990
+ }
991
+ const input = { kind: kind };
992
+ if (values["hours-file"] !== undefined) {
993
+ input.hours = (await readJsonFile(values["hours-file"]));
994
+ }
995
+ if (values.note !== undefined)
996
+ input.note = values.note;
997
+ const revision = requireRevision(values.revision, HOURS_REVISION_HELP);
998
+ const result = await (await clientFor(values, deps)).setStoreHoursException(date, input, revision, {
999
+ dryRun: values["dry-run"],
1000
+ });
1001
+ if (values.json) {
1002
+ printJson(deps, result);
1003
+ return 0;
1004
+ }
1005
+ const what = kind === "inherit"
1006
+ ? `${date} の例外を消して、曜日どおりに戻しました`
1007
+ : kind === "open"
1008
+ ? `${date} を振替出勤にしました`
1009
+ : `${date} を臨時休業にしました`;
1010
+ if (values["dry-run"]) {
1011
+ deps.io.out(`Dry run: nothing was saved. ${what} (would be).`);
1012
+ }
1013
+ else {
1014
+ deps.io.out(`${what}。Saved and live now — no publish needed. New revision: ${result.revision}`);
1015
+ if (kind === "inherit" && result.exception === null) {
1016
+ if (result.revision === revision)
1017
+ deps.io.out("There was no exception on that day — nothing changed.");
1018
+ }
1019
+ }
1020
+ return 0;
1021
+ }
1022
+ function minutesLabel(value) {
1023
+ return value === null ? "枠の長さを使う" : `${value}分`;
1024
+ }
1025
+ function bookingText(settings) {
1026
+ const lines = [];
1027
+ lines.push(`Revision ${settings.revision} (pass to \`booking … --revision\`)`);
1028
+ lines.push(`枠 ${settings.calendar.defaultSlotMinutes}分 直前予約の締め切り ${settings.calendar.minLeadMinutes}分前 何日先まで ${settings.calendar.maxAdvanceDays}日`);
1029
+ lines.push(settings.mounted
1030
+ ? "This agent takes bookings now (mounted)."
1031
+ : "This agent is not mounted on the calendar, so it takes no bookings.");
1032
+ lines.push(`担当 ${settings.resources.length} (予約できる担当 ${settings.bookableResourceCount})`);
1033
+ for (const resource of settings.resources) {
1034
+ const services = settings.resourceServices.filter((link) => link.resourceId === resource.id);
1035
+ lines.push(` ${resource.name} ${resource.enabled ? "enabled" : "disabled"}` +
1036
+ (services.length === 0 ? " (no 内容 named: takes every 内容)" : ` ${services.length} 内容`));
1037
+ }
1038
+ if (settings.services.length === 0)
1039
+ lines.push("内容: none (one 枠 of the slot length is booked)");
1040
+ else {
1041
+ lines.push("内容:");
1042
+ for (const service of settings.services) {
1043
+ lines.push(` ${service.id} ${service.name} ${minutesLabel(service.durationMinutes)}`);
1044
+ }
1045
+ }
1046
+ if (settings.affectedAgentIds.length > 0) {
1047
+ lines.push(`This calendar is read by ${settings.affectedAgentIds.length} agent(s): ${settings.affectedAgentIds.join(", ")}`);
1048
+ }
1049
+ return lines;
1050
+ }
1051
+ async function readTextFile(path) {
1052
+ try {
1053
+ return await readFile(path, "utf8");
1054
+ }
1055
+ catch (err) {
1056
+ throw new UsageError(`Cannot read ${path}: ${err.message}`);
1057
+ }
1058
+ }
1059
+ async function readBinaryFile(path) {
1060
+ try {
1061
+ return new Uint8Array(await readFile(path));
1062
+ }
1063
+ catch (err) {
1064
+ throw new UsageError(`Cannot read ${path}: ${err.message}`);
1065
+ }
1066
+ }
1067
+ async function readJsonObjectFile(path) {
1068
+ const value = await readJsonFile(path);
1069
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1070
+ throw new UsageError(`${path} must hold a JSON object.`);
1071
+ }
1072
+ return value;
1073
+ }
1074
+ async function bookingGet(args, deps) {
1075
+ const { values, positionals } = parse(args, {});
1076
+ const agentId = need(positionals, 0, "agentId");
1077
+ const settings = await (await clientFor(values, deps)).getBookingSettings(agentId);
1078
+ if (values.json)
1079
+ printJson(deps, settings);
1080
+ else
1081
+ for (const line of bookingText(settings))
1082
+ deps.io.out(line);
1083
+ return 0;
1084
+ }
1085
+ const BOOKING_REVISION_HELP = "the revision `kumion booking get` showed for the 予約設定 you are changing.";
1086
+ async function bookingCalendarUpdate(args, deps) {
1087
+ const { values } = parse(args, { revision: { type: "string" }, "patch-file": { type: "string" }, "dry-run": { type: "boolean" } });
1088
+ if (values["patch-file"] === undefined) {
1089
+ throw new UsageError("Pass --patch-file <path> holding defaultSlotMinutes, minLeadMinutes and/or maxAdvanceDays.");
1090
+ }
1091
+ const patch = (await readJsonObjectFile(values["patch-file"]));
1092
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1093
+ const result = await (await clientFor(values, deps)).updateBookingCalendar(patch, revision, { dryRun: values["dry-run"] });
1094
+ if (values.json) {
1095
+ printJson(deps, result);
1096
+ return 0;
1097
+ }
1098
+ const calendar = result.calendar;
1099
+ const summary = `枠 ${calendar.defaultSlotMinutes}分 直前予約の締め切り ${calendar.minLeadMinutes}分前 何日先まで ${calendar.maxAdvanceDays}日`;
1100
+ if (values["dry-run"]) {
1101
+ deps.io.out(`Dry run: nothing was saved. The calendar is at revision ${result.revision}.`);
1102
+ deps.io.out(summary);
1103
+ return 0;
1104
+ }
1105
+ deps.io.out(`Saved and live now — no publish needed. New revision: ${result.revision}`);
1106
+ deps.io.out(summary);
1107
+ if (result.affectedAgentIds.length > 0) {
1108
+ deps.io.out(`The next slot on ${result.affectedAgentIds.length} agent(s) uses these settings.`);
1109
+ }
1110
+ return 0;
1111
+ }
1112
+ function bookingServiceText(service) {
1113
+ return `${service.name} ${minutesLabel(service.durationMinutes)}`;
1114
+ }
1115
+ async function bookingServicesCreate(args, deps) {
1116
+ const { values } = parse(args, { revision: { type: "string" }, "data-file": { type: "string" }, "dry-run": { type: "boolean" } });
1117
+ if (values["data-file"] === undefined) {
1118
+ throw new UsageError("Pass --data-file <path> holding name, and durationMinutes (or null for the slot length).");
1119
+ }
1120
+ const service = (await readJsonObjectFile(values["data-file"]));
1121
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1122
+ const result = await (await clientFor(values, deps)).createBookingService(service, revision, { dryRun: values["dry-run"] });
1123
+ if (values.json) {
1124
+ printJson(deps, result);
1125
+ return 0;
1126
+ }
1127
+ if (values["dry-run"]) {
1128
+ deps.io.out(`Dry run: nothing was saved. Would add: ${bookingServiceText(result.service)}`);
1129
+ return 0;
1130
+ }
1131
+ deps.io.out(`Added 内容 ${result.service.id} ${bookingServiceText(result.service)}`);
1132
+ deps.io.out(`Saved and live now — no publish needed. New revision: ${result.revision}`);
1133
+ return 0;
1134
+ }
1135
+ async function bookingServicesUpdate(args, deps) {
1136
+ const { values, positionals } = parse(args, {
1137
+ revision: { type: "string" },
1138
+ "patch-file": { type: "string" },
1139
+ "dry-run": { type: "boolean" },
1140
+ });
1141
+ const serviceId = need(positionals, 0, "serviceId");
1142
+ if (values["patch-file"] === undefined) {
1143
+ throw new UsageError("Pass --patch-file <path> holding name and/or durationMinutes (null = the slot length).");
1144
+ }
1145
+ const patch = (await readJsonObjectFile(values["patch-file"]));
1146
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1147
+ const result = await (await clientFor(values, deps)).updateBookingService(serviceId, patch, revision, {
1148
+ dryRun: values["dry-run"],
1149
+ });
1150
+ if (values.json) {
1151
+ printJson(deps, result);
1152
+ return 0;
1153
+ }
1154
+ if (values["dry-run"]) {
1155
+ deps.io.out(`Dry run: nothing was saved. Would be: ${bookingServiceText(result.service)}`);
1156
+ return 0;
1157
+ }
1158
+ deps.io.out(`Saved and live now — no publish needed. 内容 ${serviceId}: ${bookingServiceText(result.service)}`);
1159
+ deps.io.out(`New revision: ${result.revision}`);
1160
+ return 0;
1161
+ }
1162
+ function weeklyHoursLabel(hours) {
1163
+ const days = Object.keys(hours).filter((day) => (hours[day] ?? []).length > 0);
1164
+ return days.length === 0 ? "枠なし(この担当には予約が入りません)" : `${days.join("・")} の ${days.length}日`;
1165
+ }
1166
+ function bookingResourceText(resource) {
1167
+ const service = resource.serviceRestriction === "all" ? "すべての内容" : `内容 ${resource.serviceIds.length} 件`;
1168
+ return `${resource.name} ${resource.enabled ? "enabled" : "disabled"} 枠 ${weeklyHoursLabel(resource.weeklyHours)} ${service}`;
1169
+ }
1170
+ async function bookingResourcesCreate(args, deps) {
1171
+ const { values } = parse(args, { revision: { type: "string" }, "data-file": { type: "string" }, "dry-run": { type: "boolean" } });
1172
+ if (values["data-file"] === undefined) {
1173
+ throw new UsageError("Pass --data-file <path> holding name, and enabled / weeklyHours / serviceIds.");
1174
+ }
1175
+ const input = (await readJsonObjectFile(values["data-file"]));
1176
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1177
+ const result = await (await clientFor(values, deps)).createBookingResource(input, revision, {
1178
+ dryRun: values["dry-run"],
1179
+ });
1180
+ if (values.json) {
1181
+ printJson(deps, result);
1182
+ return 0;
1183
+ }
1184
+ if (values["dry-run"]) {
1185
+ deps.io.out(`Dry run: nothing was saved. Would add: ${bookingResourceText(result.resource)}`);
1186
+ return 0;
1187
+ }
1188
+ deps.io.out(`Added 担当 ${result.resource.id} ${bookingResourceText(result.resource)}`);
1189
+ deps.io.out(`Saved and live now — no publish needed. New revision: ${result.revision}`);
1190
+ return 0;
1191
+ }
1192
+ async function bookingResourcesUpdate(args, deps) {
1193
+ const { values, positionals } = parse(args, {
1194
+ revision: { type: "string" },
1195
+ "patch-file": { type: "string" },
1196
+ "dry-run": { type: "boolean" },
1197
+ });
1198
+ const resourceId = need(positionals, 0, "resourceId");
1199
+ if (values["patch-file"] === undefined) {
1200
+ throw new UsageError("Pass --patch-file <path> holding name, enabled, weeklyHours and/or serviceIds ([] = every 内容).");
1201
+ }
1202
+ const patch = (await readJsonObjectFile(values["patch-file"]));
1203
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1204
+ const result = await (await clientFor(values, deps)).updateBookingResource(resourceId, patch, revision, {
1205
+ dryRun: values["dry-run"],
1206
+ });
1207
+ if (values.json) {
1208
+ printJson(deps, result);
1209
+ return 0;
1210
+ }
1211
+ if (values["dry-run"]) {
1212
+ deps.io.out(`Dry run: nothing was saved. Would be: ${bookingResourceText(result.resource)}`);
1213
+ return 0;
1214
+ }
1215
+ deps.io.out(`Saved and live now — no publish needed. 担当 ${resourceId}: ${bookingResourceText(result.resource)}`);
1216
+ deps.io.out(`New revision: ${result.revision}`);
1217
+ return 0;
1218
+ }
1219
+ async function bookingMount(args, deps) {
1220
+ const { values, positionals } = parse(args, {
1221
+ revision: { type: "string" },
1222
+ mounted: { type: "string" },
1223
+ "dry-run": { type: "boolean" },
1224
+ });
1225
+ const agentId = need(positionals, 0, "agentId");
1226
+ const mounted = parseYesNo(values.mounted, "mounted");
1227
+ if (mounted === undefined)
1228
+ throw new UsageError("Pass --mounted true or --mounted false.");
1229
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1230
+ const result = await (await clientFor(values, deps)).setAgentBooking(agentId, mounted, revision, {
1231
+ dryRun: values["dry-run"],
1232
+ });
1233
+ if (values.json) {
1234
+ printJson(deps, result);
1235
+ return 0;
1236
+ }
1237
+ const state = result.mounted ? "takes bookings" : "does not take bookings";
1238
+ if (values["dry-run"]) {
1239
+ deps.io.out(`Dry run: nothing was saved. This agent would ${result.mounted ? "start" : "stop"} taking bookings.`);
1240
+ return 0;
1241
+ }
1242
+ deps.io.out(`Saved and live now — no publish needed. This agent ${state}. New revision: ${result.revision}`);
1243
+ if (result.receptionSummaryRetired > 0) {
1244
+ deps.io.out(`Retired 仮受付 from ${result.receptionSummaryRetired} 受付サマリー spec(s): the calendar confirms for real now.`);
1245
+ }
1246
+ return 0;
1247
+ }
1248
+ function bookingSlotText(slot) {
1249
+ const minutes = Math.round((new Date(slot.endAt).getTime() - new Date(slot.startAt).getTime()) / 60_000);
1250
+ return `${slot.startAt.slice(0, 16).replace("T", " ")}(${minutes}分)`;
1251
+ }
1252
+ async function bookingSlots(args, deps) {
1253
+ const { values, positionals } = parse(args, {
1254
+ resource: { type: "string" },
1255
+ date: { type: "string" },
1256
+ service: { type: "string" },
1257
+ limit: { type: "string" },
1258
+ });
1259
+ const agentId = need(positionals, 0, "agentId");
1260
+ if (values.resource === undefined)
1261
+ throw new UsageError("Pass --resource <resourceId> (the 担当's id, from `booking get`).");
1262
+ if (values.date === undefined)
1263
+ throw new UsageError("Pass --date <YYYY-MM-DD>.");
1264
+ const limit = values.limit === undefined ? undefined : Number(values.limit);
1265
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {
1266
+ throw new UsageError("--limit takes a whole number of slots.");
1267
+ }
1268
+ const view = await (await clientFor(values, deps)).listBookingSlots(agentId, {
1269
+ resourceId: values.resource,
1270
+ date: values.date,
1271
+ ...(values.service === undefined ? {} : { serviceId: values.service }),
1272
+ ...(limit === undefined ? {} : { limit }),
1273
+ });
1274
+ if (values.json) {
1275
+ printJson(deps, view);
1276
+ return 0;
1277
+ }
1278
+ deps.io.out(`${view.resource.name} ${view.date} (${view.resource.enabled ? "enabled" : "disabled"})`);
1279
+ if (!view.mounted) {
1280
+ deps.io.out("This agent is not mounted on the calendar, so it will not offer these slots (see `booking mount`).");
1281
+ }
1282
+ if (!view.serviceAllowed) {
1283
+ deps.io.out("This 担当 does not take that 内容, so no slot of that length is offered.");
1284
+ return 0;
1285
+ }
1286
+ if (view.slots.length === 0) {
1287
+ deps.io.out("No openings on that day.");
1288
+ return 0;
1289
+ }
1290
+ for (const slot of view.slots)
1291
+ deps.io.out(` ${bookingSlotText(slot)}`);
1292
+ return 0;
1293
+ }
1294
+ const CAPTURE_SPEC_REVISION_HELP = "the revision `kumion capture-specs list` showed for the 記録項目 you are changing.";
1295
+ function captureSpecScope(spec) {
1296
+ return spec.affectedAgentIds.length === 0 ? "no agent yet" : `${spec.affectedAgentIds.length} agent(s)`;
1297
+ }
1298
+ function captureSpecLine(spec) {
1299
+ return `${spec.id} ${spec.enabled ? "enabled " : "disabled"} ${spec.label} [key ${spec.key} revision ${spec.revision}] ${captureSpecScope(spec)}`;
1300
+ }
1301
+ async function captureSpecsList(args, deps) {
1302
+ const { values } = parse(args, {});
1303
+ const specs = await (await clientFor(values, deps)).listCaptureSpecs();
1304
+ if (values.json) {
1305
+ printJson(deps, { captureSpecs: specs });
1306
+ return 0;
1307
+ }
1308
+ if (specs.length === 0)
1309
+ deps.io.out("No 記録項目.");
1310
+ else
1311
+ for (const spec of specs)
1312
+ deps.io.out(captureSpecLine(spec));
1313
+ return 0;
1314
+ }
1315
+ async function captureSpecsCreate(args, deps) {
1316
+ const { values } = parse(args, { "data-file": { type: "string" } });
1317
+ if (values["data-file"] === undefined) {
1318
+ throw new UsageError("Pass --data-file <path> holding label, fields, and optionally key / scenario / instruction.");
1319
+ }
1320
+ const input = (await readJsonObjectFile(values["data-file"]));
1321
+ if (input.fields === undefined)
1322
+ throw new UsageError(`${values["data-file"]} must hold fields.`);
1323
+ const spec = await (await clientFor(values, deps)).createCaptureSpec({ ...input, fields: input.fields });
1324
+ if (values.json) {
1325
+ printJson(deps, { captureSpec: spec });
1326
+ return 0;
1327
+ }
1328
+ deps.io.out(`Created 記録項目 ${spec.id} ${spec.label} [key ${spec.key} revision ${spec.revision}]`);
1329
+ deps.io.out("No agent records it yet — mount it on an agent before it can record anything.");
1330
+ return 0;
1331
+ }
1332
+ async function captureSpecsUpdate(args, deps) {
1333
+ const { values, positionals } = parse(args, { revision: { type: "string" }, "patch-file": { type: "string" } });
1334
+ const specId = need(positionals, 0, "specId");
1335
+ if (values["patch-file"] === undefined) {
1336
+ throw new UsageError("Pass --patch-file <path> holding the fields to change (see `kumion --help`).");
1337
+ }
1338
+ const patch = (await readJsonObjectFile(values["patch-file"]));
1339
+ const revision = requireRevision(values.revision, CAPTURE_SPEC_REVISION_HELP);
1340
+ const spec = await (await clientFor(values, deps)).updateCaptureSpec(specId, patch, revision);
1341
+ if (values.json) {
1342
+ printJson(deps, { captureSpec: spec });
1343
+ return 0;
1344
+ }
1345
+ deps.io.out(`Saved and live now — no publish needed. 記録項目 ${specId}: ${spec.label}`);
1346
+ deps.io.out(`New revision: ${spec.revision}`);
1347
+ if (spec.affectedAgentIds.length === 0)
1348
+ deps.io.out("No agent is mounted with this 記録項目, so no call records it yet.");
1349
+ else
1350
+ deps.io.out(`Every agent mounted with it records differently from its next call: ${spec.affectedAgentIds.join(", ")}`);
1351
+ return 0;
1352
+ }
1353
+ const AGENT_CAPTURE_REVISION_HELP = "the revision `kumion agents capture get` showed for this agent.";
1354
+ function printAgentCaptureReadiness(capture, deps) {
1355
+ if (capture.readiness.ready) {
1356
+ deps.io.out(`Ready: ${capture.enabledMountedCount} 記録項目 will be extracted after a call.`);
1357
+ return;
1358
+ }
1359
+ deps.io.out("NOT ready — a call on this agent records nothing:");
1360
+ for (const issue of capture.readiness.issues)
1361
+ deps.io.out(` ${issue.message}`);
1362
+ }
1363
+ function printAgentCapture(capture, deps) {
1364
+ if (capture.captureSpecIds.length === 0)
1365
+ deps.io.out("No 記録項目 mounted on this agent.");
1366
+ for (const spec of capture.captureSpecs) {
1367
+ deps.io.out(`${spec.id} ${spec.enabled ? "enabled " : "disabled"} ${spec.label} [key ${spec.key} revision ${spec.revision}]`);
1368
+ }
1369
+ printAgentCaptureReadiness(capture, deps);
1370
+ deps.io.out(`Revision: ${capture.revision}`);
1371
+ }
1372
+ async function agentsCaptureGet(args, deps) {
1373
+ const { values, positionals } = parse(args, {});
1374
+ const agentId = need(positionals, 0, "agentId");
1375
+ const capture = await (await clientFor(values, deps)).getAgentCapture(agentId);
1376
+ if (values.json) {
1377
+ printJson(deps, capture);
1378
+ return 0;
1379
+ }
1380
+ printAgentCapture(capture, deps);
1381
+ return 0;
1382
+ }
1383
+ async function agentsCaptureSet(args, deps) {
1384
+ const { values, positionals } = parse(args, {
1385
+ revision: { type: "string" },
1386
+ spec: { type: "string", multiple: true },
1387
+ clear: { type: "boolean" },
1388
+ });
1389
+ const agentId = need(positionals, 0, "agentId");
1390
+ const specs = values.spec ?? [];
1391
+ if (values.clear && specs.length > 0) {
1392
+ throw new UsageError("Pass either --spec <specId> (repeatable) or --clear, not both.");
1393
+ }
1394
+ if (!values.clear && specs.length === 0) {
1395
+ throw new UsageError("Pass --spec <specId> (repeatable) to mount, or --clear to record nothing.");
1396
+ }
1397
+ const revision = requireRevision(values.revision, AGENT_CAPTURE_REVISION_HELP);
1398
+ const capture = await (await clientFor(values, deps)).setAgentCapture(agentId, specs, revision);
1399
+ if (values.json) {
1400
+ printJson(deps, capture);
1401
+ return 0;
1402
+ }
1403
+ deps.io.out(capture.captureSpecIds.length === 0
1404
+ ? "Saved and live now — no publish needed. This agent records nothing after a call."
1405
+ : `Saved and live now — no publish needed. This agent records: ${capture.captureSpecs.map((spec) => spec.label).join(", ")}`);
1406
+ printAgentCaptureReadiness(capture, deps);
1407
+ deps.io.out(`New revision: ${capture.revision}`);
1408
+ return 0;
1409
+ }
1410
+ function documentJobText(job) {
1411
+ const head = `${job.jobId} ${job.status}`;
1412
+ if (job.status === "succeeded")
1413
+ return `${head} document ${job.documentId}`;
1414
+ if (job.error)
1415
+ return `${head} ${job.error.code}: ${job.error.message}`;
1416
+ return `${head} (deadline ${job.deadlineAt})`;
1417
+ }
1418
+ async function documentsUpload(args, deps) {
1419
+ const { values } = parse(args, {
1420
+ "text-file": { type: "string" },
1421
+ file: { type: "string", multiple: true },
1422
+ title: { type: "string" },
1423
+ template: { type: "string" },
1424
+ "idempotency-key": { type: "string" },
1425
+ "dry-run": { type: "boolean" },
1426
+ });
1427
+ const textFile = values["text-file"];
1428
+ const files = values.file ?? [];
1429
+ if (textFile !== undefined && files.length > 0) {
1430
+ throw new UsageError("Pass either --text-file or --file, not both: the API takes the text OR the files.");
1431
+ }
1432
+ if (textFile === undefined && files.length === 0) {
1433
+ throw new UsageError("Pass --text-file <path> for the text of the 資料, or --file <path> (repeatable) for files.");
1434
+ }
1435
+ if (!values.title)
1436
+ throw new UsageError("Pass --title <title>.");
1437
+ const idempotencyKey = values["idempotency-key"];
1438
+ if (!idempotencyKey) {
1439
+ throw new UsageError("Pass --idempotency-key <key>: a retry with the same key answers the job it already made.");
1440
+ }
1441
+ const payload = textFile === undefined
1442
+ ? {
1443
+ files: await Promise.all(files.map(async (path) => ({ filename: basename(path), bytes: await readBinaryFile(path) }))),
1444
+ }
1445
+ : { rawText: await readTextFile(textFile) };
1446
+ const result = await (await clientFor(values, deps)).uploadDocument({
1447
+ title: values.title,
1448
+ idempotencyKey,
1449
+ ...payload,
1450
+ ...(values.template === undefined ? {} : { templateId: values.template }),
1451
+ }, { dryRun: values["dry-run"] });
1452
+ if (values.json) {
1453
+ printJson(deps, result);
1454
+ return 0;
1455
+ }
1456
+ if ("dryRun" in result) {
1457
+ deps.io.out(`Would upload ${result.filesCount} file(s), ${result.chars.toLocaleString("en-US")} characters (${result.bytes.toLocaleString("en-US")} bytes); nothing is written and no model is called.`);
1458
+ deps.io.out(`Model: ${result.provider}${result.model ? ` / ${result.model}` : ""}`);
1459
+ deps.io.out(`Allowance left: ${result.budget.keyRemaining} for this key, ${result.budget.tenantRemaining} for the tenant (per hour).`);
1460
+ deps.io.out("Price: not available (amount is null) — extractions are counted, not billed per run.");
1461
+ return 0;
1462
+ }
1463
+ deps.io.out(`Accepted. ${documentJobText(result)}`);
1464
+ deps.io.out(`Check it with: kumion documents jobs get ${result.jobId}`);
1465
+ return 0;
1466
+ }
1467
+ async function documentsJobsGet(args, deps) {
1468
+ const { values, positionals } = parse(args, {});
1469
+ const jobId = need(positionals, 0, "jobId");
1470
+ const job = await (await clientFor(values, deps)).getDocumentUploadJob(jobId);
1471
+ if (values.json)
1472
+ printJson(deps, job);
1473
+ else
1474
+ deps.io.out(documentJobText(job));
1475
+ return job.status === "failed" || job.status === "timed_out" ? 1 : 0;
1476
+ }
1477
+ async function documentsGet(args, deps) {
1478
+ const { values, positionals } = parse(args, {});
1479
+ const documentId = need(positionals, 0, "documentId");
1480
+ const document = await (await clientFor(values, deps)).getDocument(documentId);
1481
+ if (values.json) {
1482
+ printJson(deps, document);
1483
+ return 0;
1484
+ }
1485
+ const summary = document.document;
1486
+ deps.io.out(`${summary.id} ${summary.title} [${summary.status}, ${summary.mode}, revision ${document.revision}]`);
1487
+ deps.io.out(`${summary.charCount.toLocaleString("en-US")} characters, ${document.fields.length} field(s)`);
1488
+ for (const field of document.fields) {
1489
+ deps.io.out(` ${field.fieldKey} ${field.label} (${field.category}, ${field.reviewState})`);
1490
+ }
1491
+ for (const reference of document.references) {
1492
+ deps.io.out(reference.kind === "agent"
1493
+ ? ` used by agent ${reference.agentName} (${reference.agentId})`
1494
+ : ` used by node ${reference.nodeName ?? reference.nodeKey} of ${reference.workflowName} (${reference.workflowId})`);
1495
+ }
1496
+ return 0;
1497
+ }
1498
+ async function documentsReplace(args, deps) {
1499
+ const { values, positionals } = parse(args, {
1500
+ source: { type: "string" },
1501
+ "source-revision": { type: "string" },
1502
+ revision: { type: "string" },
1503
+ "dry-run": { type: "boolean" },
1504
+ });
1505
+ const documentId = need(positionals, 0, "documentId");
1506
+ if (!values.source)
1507
+ throw new UsageError("Pass --source <documentId>: the 資料 the new content comes from.");
1508
+ if (!values["source-revision"]) {
1509
+ throw new UsageError("Pass --source-revision <revision> — the source's revision, from `kumion documents get`.");
1510
+ }
1511
+ const revision = requireRevision(values.revision, "the 資料's revision from `kumion documents get`. It changes when anyone confirms or edits a fact.");
1512
+ const result = await (await clientFor(values, deps)).replaceDocument(documentId, { sourceDocumentId: values.source, sourceRevision: values["source-revision"] }, revision, { dryRun: values["dry-run"] });
1513
+ if (values.json) {
1514
+ printJson(deps, result);
1515
+ return 0;
1516
+ }
1517
+ const { changes } = result;
1518
+ const lines = [];
1519
+ lines.push(result.dryRun
1520
+ ? `Would replace ${result.document.id} with the content of ${result.source.documentId} — nothing is written.`
1521
+ : `Replaced ${result.document.id} with the content of ${result.source.documentId}.`);
1522
+ lines.push(`Characters: ${changes.characters.before.toLocaleString("en-US")} → ${changes.characters.after.toLocaleString("en-US")}`);
1523
+ if (changes.fields.added.length > 0)
1524
+ lines.push(`New facts: ${changes.fields.added.join(", ")}`);
1525
+ if (changes.fields.placeholders.length > 0) {
1526
+ lines.push(`Kept as empty (the new 資料 does not mention them): ${changes.fields.placeholders.join(", ")}`);
1527
+ }
1528
+ if (changes.fields.removed.length > 0)
1529
+ lines.push(`Gone: ${changes.fields.removed.join(", ")}`);
1530
+ lines.push(`Confirmations reset: ${result.resetConfirmedCount}. Every fact is pending again — review them before publishing.`);
1531
+ if (result.affectedAgentIds.length > 0) {
1532
+ lines.push(`Read by: ${result.affectedAgentIds.join(", ")} (live from their next call)`);
1533
+ }
1534
+ lines.push(result.dryRun ? `Revision stays: ${result.revision}` : `New revision: ${result.revision}`);
1535
+ deps.io.out(lines.join("\n"));
1536
+ return 0;
1537
+ }
717
1538
  async function factsEdit(args, deps) {
718
1539
  const { values, positionals } = parse(args, { revision: { type: "string" }, value: { type: "string" } });
719
1540
  const agentId = need(positionals, 0, "agentId");
@@ -756,6 +1577,11 @@ async function agentsPublish(args, deps) {
756
1577
  else {
757
1578
  const agent = result.agent;
758
1579
  deps.io.out(`Published ${agent?.name ?? agentId} at ${agent?.publishedAt ?? "?"} (publish run ${String(result.publishRunId ?? "?")}).`);
1580
+ const unconfirmed = typeof result.unconfirmedFacts === "number" ? result.unconfirmedFacts : 0;
1581
+ if (unconfirmed > 0) {
1582
+ deps.io.out(`${unconfirmed} fact(s) in this agent's 資料 are still unconfirmed, so it will say it will check and call back for them.`);
1583
+ deps.io.out(`Next: \`kumion facts confirm ${agentId}\``);
1584
+ }
759
1585
  }
760
1586
  return 0;
761
1587
  }
@@ -1015,6 +1841,42 @@ async function testRunsList(args, deps) {
1015
1841
  deps.io.out(`${r.id} ${r.status.padEnd(13)} ${r.casesDone}/${r.casesTotal} ${r.startedAt}`);
1016
1842
  return 0;
1017
1843
  }
1844
+ async function scheduledCallsCreate(args, deps) {
1845
+ const { values, positionals } = parse(args, { to: { type: "string" }, at: { type: "string" } });
1846
+ const agentId = need(positionals, 0, "agentId");
1847
+ if (!values.to)
1848
+ throw new UsageError("--to <phone> is required.");
1849
+ if (!values.at)
1850
+ throw new UsageError("--at <iso8601 with offset> is required.");
1851
+ const result = await (await clientFor(values, deps)).createScheduledCall(agentId, values.to, values.at);
1852
+ if (values.json)
1853
+ printJson(deps, result);
1854
+ else
1855
+ deps.io.out(`Scheduled ${String(result.phoneNumber)} for ${String(result.scheduledAt)}.\nId: ${String(result.id)}`);
1856
+ return 0;
1857
+ }
1858
+ async function scheduledCallsList(args, deps) {
1859
+ const { values } = parse(args, {});
1860
+ const rows = await (await clientFor(values, deps)).listScheduledCalls();
1861
+ if (values.json)
1862
+ printJson(deps, { scheduledCalls: rows });
1863
+ else if (rows.length === 0)
1864
+ deps.io.out("No scheduled calls.");
1865
+ else
1866
+ for (const r of rows)
1867
+ deps.io.out(`${String(r.id)} ${String(r.state).padEnd(9)} ${String(r.scheduledAt)} ${String(r.phoneNumber)}${r.reason ? ` (${String(r.reason)})` : ""}`);
1868
+ return 0;
1869
+ }
1870
+ async function scheduledCallsCancel(args, deps) {
1871
+ const { values, positionals } = parse(args, {});
1872
+ const id = need(positionals, 0, "id");
1873
+ const result = await (await clientFor(values, deps)).cancelScheduledCall(id);
1874
+ if (values.json)
1875
+ printJson(deps, result);
1876
+ else
1877
+ deps.io.out(`Canceled ${String(result.id)}.`);
1878
+ return 0;
1879
+ }
1018
1880
  async function callsCreate(args, deps) {
1019
1881
  const { values, positionals } = parse(args, {
1020
1882
  "campaign-contact": { type: "string" },