@kumion/cli 0.3.0 → 0.4.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
1
  import { readFile } from "node:fs/promises";
2
+ import { basename } from "node:path";
2
3
  import { parseArgs } from "node:util";
3
4
  import { ApiError, KumionClient, } 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.4.0";
8
9
  const HELP = `kumion — manage your Kumion voice agents over the Partner API
9
10
 
10
11
  Usage: kumion <command> [options]
@@ -81,14 +82,99 @@ Staff (the people a 用件 can transfer a call to)
81
82
  publish (needs a key with agents:live). --enabled false takes
82
83
  them out of the 転送 candidates
83
84
 
84
- Facts (the agent's 資料)
85
- facts list <agentId> List the facts with their state and revision
85
+ Hours (when the shop is open — one calendar for the whole tenant)
86
+ hours get [--from <date>] [--to <date>]
87
+ Show 営業時間, 定休日, 祝日休み and the 例外日 in a window,
88
+ with the revision the two writes below need
89
+ hours update --revision <rev> [--business-hours-file <path>] [--closed-rules-file <path>]
90
+ [--observe-jp-holidays true|false] [--dry-run]
91
+ Change the clock. businessHours and closedRules are whole
92
+ replacements; an omitted field is left alone. LIVE: the next
93
+ call answers from it, no publish (needs agents:live)
94
+ hours exception set <date> --revision <rev> --kind closed|open|inherit [--hours-file <path>]
95
+ [--note <text>] [--dry-run]
96
+ One 例外日: closed = 臨時休業, open = 振替出勤 (with its own
97
+ hours, or the weekday's), inherit = back to the weekly rule.
98
+ LIVE (needs agents:live)
99
+
100
+ Booking (予約設定 — one calendar for the tenant, read per agent)
101
+ booking get <agentId> Show the slot length, the lead time and the horizon, the
102
+ 内容 and 担当, and whether this agent takes bookings, with
103
+ the revision every booking write below needs
104
+ booking calendar update --revision <rev> --patch-file <path> [--dry-run]
105
+ Change 枠の長さ (defaultSlotMinutes), 直前予約の締め切り
106
+ (minLeadMinutes) and/or 何日先まで (maxAdvanceDays); an
107
+ omitted field is left alone. LIVE (needs agents:live)
108
+ booking services create --revision <rev> --data-file <path> [--dry-run]
109
+ Add one 内容: name, and durationMinutes (1–1440, or null to
110
+ use the slot length). LIVE (needs agents:live)
111
+ booking services update <serviceId> --revision <rev> --patch-file <path> [--dry-run]
112
+ Change one 内容's name and/or durationMinutes; null goes
113
+ back to the slot length. LIVE (needs agents:live)
114
+ booking resources create --revision <rev> --data-file <path> [--dry-run]
115
+ Add one 担当: name, enabled, weeklyHours (予約枠) and the
116
+ serviceIds it takes ([] = every 内容). One 内容 that is not
117
+ this tenant's refuses the whole write. LIVE (needs agents:live)
118
+ booking resources update <resourceId> --revision <rev> --patch-file <path> [--dry-run]
119
+ Change a 担当; an omitted field is left alone, enabled=false
120
+ takes it out of service without deleting it. LIVE
121
+ booking mount <agentId> --mounted true|false --revision <rev> [--dry-run]
122
+ Start or stop taking bookings. Mounting also retires the
123
+ 「仮受付」 promise from the 受付サマリー, in the same write.
124
+ LIVE (needs agents:live)
125
+ booking slots <agentId> --resource <resourceId> --date <YYYY-MM-DD>
126
+ [--service <serviceId>] [--limit <n>]
127
+ One 担当's openings on one day, computed the way a call
128
+ computes them (6 by default, at most 20). Reads only —
129
+ nothing is reserved (needs agents:read)
130
+
131
+ Facts (the agent's 資料) facts list <agentId> List the facts with their state and revision
86
132
  facts edit <agentId> <factId> --revision <rev> --value <text>
87
133
  Confirm one fact with a new value. LIVE (needs agents:live)
88
134
  facts confirm <agentId> [--fact <factId> ...]
89
135
  Confirm pending facts as extracted (all of them without
90
136
  --fact; a fact whose candidates disagree is skipped). LIVE
91
137
 
138
+ Capture specs (記録項目 — what the agent records after a call)
139
+ capture-specs list List the 記録項目 with their revision and the agents each is
140
+ mounted on
141
+ capture-specs create --data-file <path>
142
+ Add one 記録項目 (name, fields, optional 場面). Without an
143
+ instruction the API writes one from those — no model is
144
+ called. It is mounted on no agent yet, so no call changes
145
+ (needs agents:write)
146
+ capture-specs update <specId> --revision <rev> --patch-file <path>
147
+ Change one 記録項目; an omitted field is left alone and key is
148
+ frozen. LIVE: every agent mounted with it records differently
149
+ from its next call (needs agents:live)
150
+ agents capture get <agentId> Show which 記録項目 this agent records, its revision, and
151
+ whether THIS agent would record after a call
152
+ agents capture set <agentId> --revision <rev> (--spec <specId> ... | --clear)
153
+ Replace the whole set this agent records (--spec repeats;
154
+ --clear is []; the two cannot be combined). LIVE: the next
155
+ call's summary is written from the new set, no publish
156
+ (needs agents:live)
157
+
158
+ Documents (資料 — the source an agent's facts are extracted from)
159
+ documents upload (--text-file <path> | --file <path> [--file <path> ...])
160
+ --title <title> --idempotency-key <key> [--template <templateId>] [--dry-run]
161
+ Upload a 資料 — its text, or files (.txt / .md / .pdf / .docx /
162
+ .xlsx, up to 10 files and 20MiB) — and get a job back at once
163
+ (the extraction runs after). Several files become ONE manual,
164
+ in the order given. Same key + same content answers the same
165
+ job; different content under the same key is refused
166
+ (needs agents:write). --dry-run shows the size, the model and
167
+ the remaining allowance, and calls no model
168
+ documents jobs get <jobId> Show an upload job: status, the document it produced, the error.
169
+ Exits non-zero when the job failed or timed out
170
+ documents get <documentId> Show a 資料: its fields, review state and revision (not the text)
171
+ documents replace <documentId> --source <sourceDocumentId> --source-revision <rev> --revision <rev>
172
+ [--dry-run]
173
+ Give a 資料 another document's content and facts, keeping its id, so the
174
+ agents already reading it switch with no re-creation. Every fact comes back
175
+ pending, and a fact the new source does not mention stays as an empty row.
176
+ LIVE: the next call reads the new facts. Needs agents:live
177
+
92
178
  Test runs
93
179
  test-runs start <agentId> [--no-wait] [--interval <sec>] [--timeout <sec>]
94
180
  Run the agent's regression tests against its draft
@@ -198,11 +284,13 @@ async function dispatch(argv, deps) {
198
284
  }
199
285
  if (group === "mcp")
200
286
  return mcpServe(argv.slice(1), deps);
201
- const handler = COMMANDS[`${group} ${command ?? ""}`.trim()];
202
- if (!handler) {
287
+ const two = `${group} ${command ?? ""}`.trim();
288
+ const three = rest.length > 0 ? `${two} ${rest[0]}` : two;
289
+ const name = Object.hasOwn(COMMANDS, three) ? three : Object.hasOwn(COMMANDS, two) ? two : null;
290
+ if (!name) {
203
291
  throw new UsageError(`Unknown command: kumion ${[group, command].filter(Boolean).join(" ")}\nRun \`kumion --help\` for usage.`);
204
292
  }
205
- return handler(rest, deps);
293
+ return COMMANDS[name](name === three ? rest.slice(1) : rest, deps);
206
294
  }
207
295
  async function clientFor(values, deps) {
208
296
  const creds = await resolveCredentials({
@@ -237,9 +325,29 @@ export const COMMANDS = {
237
325
  "staff list": staffList,
238
326
  "staff create": staffCreate,
239
327
  "staff update": staffUpdate,
328
+ "hours get": hoursGet,
329
+ "hours update": hoursUpdate,
330
+ "hours exception set": hoursExceptionSet,
331
+ "booking get": bookingGet,
332
+ "booking calendar update": bookingCalendarUpdate,
333
+ "booking services create": bookingServicesCreate,
334
+ "booking services update": bookingServicesUpdate,
335
+ "booking resources create": bookingResourcesCreate,
336
+ "booking resources update": bookingResourcesUpdate,
337
+ "booking mount": bookingMount,
338
+ "booking slots": bookingSlots,
240
339
  "facts list": factsList,
241
340
  "facts edit": factsEdit,
242
341
  "facts confirm": factsConfirm,
342
+ "capture-specs list": captureSpecsList,
343
+ "capture-specs create": captureSpecsCreate,
344
+ "capture-specs update": captureSpecsUpdate,
345
+ "agents capture get": agentsCaptureGet,
346
+ "agents capture set": agentsCaptureSet,
347
+ "documents upload": documentsUpload,
348
+ "documents jobs get": documentsJobsGet,
349
+ "documents get": documentsGet,
350
+ "documents replace": documentsReplace,
243
351
  "test-runs start": testRunsStart,
244
352
  "test-runs get": testRunsGet,
245
353
  "test-runs list": testRunsList,
@@ -617,7 +725,7 @@ async function agentsCreateFromTemplate(args, deps) {
617
725
  deps.io.out("");
618
726
  deps.io.out(`${result.missing.length} 件は資料から読み取れませんでした。アシスタントで足すか、このまま公開できます。`);
619
727
  }
620
- deps.io.out("Next: `kumion agents get <id>`, `kumion test-runs start <id>`, `kumion agents publish <id>`.");
728
+ 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
729
  return 0;
622
730
  }
623
731
  function staffLine(staff) {
@@ -714,6 +822,659 @@ async function staffUpdate(args, deps) {
714
822
  deps.io.out("This スタッフ is not a 転送 candidate now (disabled, or missing a 転送先).");
715
823
  return 0;
716
824
  }
825
+ const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
826
+ function hoursText(hours) {
827
+ const lines = [];
828
+ lines.push(`Revision ${hours.revision} (pass to \`hours update --revision\`)`);
829
+ lines.push(`Timezone ${hours.timezone} 祝日休み: ${hours.observeJpHolidays ? "yes" : "no"}`);
830
+ const open = WEEKDAYS.filter((day) => (hours.businessHours[day] ?? []).length > 0);
831
+ if (open.length === 0)
832
+ lines.push("営業時間: not set (every day is answered as 未設定)");
833
+ else {
834
+ lines.push("営業時間:");
835
+ for (const day of WEEKDAYS) {
836
+ const ranges = hours.businessHours[day] ?? [];
837
+ lines.push(` ${day} ${ranges.length === 0 ? "closed" : ranges.map((r) => `${r.start}-${r.end}`).join(", ")}`);
838
+ }
839
+ }
840
+ lines.push(`定休日: ${hours.closedRules.length} rule(s)`);
841
+ if (hours.exceptions.length === 0)
842
+ lines.push("例外日: none in this window");
843
+ else {
844
+ lines.push("例外日:");
845
+ for (const exception of hours.exceptions) {
846
+ const what = exception.kind === "closed" ? "臨時休業" : "振替出勤";
847
+ const when = exception.hours && exception.hours.length > 0
848
+ ? ` ${exception.hours.map((r) => `${r.start}-${r.end}`).join(", ")}`
849
+ : "";
850
+ lines.push(` ${exception.closedOn} ${what}${when}${exception.note ? ` (${exception.note})` : ""}`);
851
+ }
852
+ }
853
+ if (hours.affectedAgentIds.length > 0) {
854
+ lines.push(`This calendar is read by ${hours.affectedAgentIds.length} agent(s): ${hours.affectedAgentIds.join(", ")}`);
855
+ }
856
+ return lines;
857
+ }
858
+ async function hoursGet(args, deps) {
859
+ const { values } = parse(args, { from: { type: "string" }, to: { type: "string" } });
860
+ const hours = await (await clientFor(values, deps)).getStoreHours({ from: values.from, to: values.to });
861
+ if (values.json)
862
+ printJson(deps, hours);
863
+ else
864
+ for (const line of hoursText(hours))
865
+ deps.io.out(line);
866
+ return 0;
867
+ }
868
+ function parseYesNo(raw, flag) {
869
+ if (raw === undefined)
870
+ return undefined;
871
+ if (raw === "true")
872
+ return true;
873
+ if (raw === "false")
874
+ return false;
875
+ throw new UsageError(`--${flag} takes true or false.`);
876
+ }
877
+ const HOURS_REVISION_HELP = "the revision `kumion hours get` showed for the clock you are changing.";
878
+ async function hoursUpdate(args, deps) {
879
+ const { values } = parse(args, {
880
+ revision: { type: "string" },
881
+ "business-hours-file": { type: "string" },
882
+ "closed-rules-file": { type: "string" },
883
+ "observe-jp-holidays": { type: "string" },
884
+ "dry-run": { type: "boolean" },
885
+ });
886
+ const patch = {};
887
+ if (values["business-hours-file"] !== undefined) {
888
+ patch.businessHours = (await readJsonFile(values["business-hours-file"]));
889
+ }
890
+ if (values["closed-rules-file"] !== undefined) {
891
+ patch.closedRules = (await readJsonFile(values["closed-rules-file"]));
892
+ }
893
+ const observe = parseYesNo(values["observe-jp-holidays"], "observe-jp-holidays");
894
+ if (observe !== undefined)
895
+ patch.observeJpHolidays = observe;
896
+ if (Object.keys(patch).length === 0) {
897
+ throw new UsageError("Nothing to change. Pass --business-hours-file, --closed-rules-file or --observe-jp-holidays.");
898
+ }
899
+ const revision = requireRevision(values.revision, HOURS_REVISION_HELP);
900
+ const hours = await (await clientFor(values, deps)).updateStoreHours(patch, revision, { dryRun: values["dry-run"] });
901
+ if (values.json) {
902
+ printJson(deps, hours);
903
+ return 0;
904
+ }
905
+ if (values["dry-run"]) {
906
+ deps.io.out(`Dry run: nothing was saved. The calendar is at revision ${hours.revision}.`);
907
+ for (const line of hoursText(hours).slice(1))
908
+ deps.io.out(line);
909
+ return 0;
910
+ }
911
+ deps.io.out(`Saved and live now — no publish needed. New revision: ${hours.revision}`);
912
+ if (hours.affectedAgentIds.length > 0) {
913
+ deps.io.out(`The next call on ${hours.affectedAgentIds.length} agent(s) answers from this clock.`);
914
+ }
915
+ return 0;
916
+ }
917
+ const EXCEPTION_KINDS = ["closed", "open", "inherit"];
918
+ async function hoursExceptionSet(args, deps) {
919
+ const { values, positionals } = parse(args, {
920
+ revision: { type: "string" },
921
+ kind: { type: "string" },
922
+ "hours-file": { type: "string" },
923
+ note: { type: "string" },
924
+ "dry-run": { type: "boolean" },
925
+ });
926
+ const date = need(positionals, 0, "date");
927
+ const kind = values.kind;
928
+ if (!kind || !EXCEPTION_KINDS.includes(kind)) {
929
+ throw new UsageError("Pass --kind closed|open|inherit.");
930
+ }
931
+ const input = { kind: kind };
932
+ if (values["hours-file"] !== undefined) {
933
+ input.hours = (await readJsonFile(values["hours-file"]));
934
+ }
935
+ if (values.note !== undefined)
936
+ input.note = values.note;
937
+ const revision = requireRevision(values.revision, HOURS_REVISION_HELP);
938
+ const result = await (await clientFor(values, deps)).setStoreHoursException(date, input, revision, {
939
+ dryRun: values["dry-run"],
940
+ });
941
+ if (values.json) {
942
+ printJson(deps, result);
943
+ return 0;
944
+ }
945
+ const what = kind === "inherit"
946
+ ? `${date} の例外を消して、曜日どおりに戻しました`
947
+ : kind === "open"
948
+ ? `${date} を振替出勤にしました`
949
+ : `${date} を臨時休業にしました`;
950
+ if (values["dry-run"]) {
951
+ deps.io.out(`Dry run: nothing was saved. ${what} (would be).`);
952
+ }
953
+ else {
954
+ deps.io.out(`${what}。Saved and live now — no publish needed. New revision: ${result.revision}`);
955
+ if (kind === "inherit" && result.exception === null) {
956
+ if (result.revision === revision)
957
+ deps.io.out("There was no exception on that day — nothing changed.");
958
+ }
959
+ }
960
+ return 0;
961
+ }
962
+ function minutesLabel(value) {
963
+ return value === null ? "枠の長さを使う" : `${value}分`;
964
+ }
965
+ function bookingText(settings) {
966
+ const lines = [];
967
+ lines.push(`Revision ${settings.revision} (pass to \`booking … --revision\`)`);
968
+ lines.push(`枠 ${settings.calendar.defaultSlotMinutes}分 直前予約の締め切り ${settings.calendar.minLeadMinutes}分前 何日先まで ${settings.calendar.maxAdvanceDays}日`);
969
+ lines.push(settings.mounted
970
+ ? "This agent takes bookings now (mounted)."
971
+ : "This agent is not mounted on the calendar, so it takes no bookings.");
972
+ lines.push(`担当 ${settings.resources.length} (予約できる担当 ${settings.bookableResourceCount})`);
973
+ for (const resource of settings.resources) {
974
+ const services = settings.resourceServices.filter((link) => link.resourceId === resource.id);
975
+ lines.push(` ${resource.name} ${resource.enabled ? "enabled" : "disabled"}` +
976
+ (services.length === 0 ? " (no 内容 named: takes every 内容)" : ` ${services.length} 内容`));
977
+ }
978
+ if (settings.services.length === 0)
979
+ lines.push("内容: none (one 枠 of the slot length is booked)");
980
+ else {
981
+ lines.push("内容:");
982
+ for (const service of settings.services) {
983
+ lines.push(` ${service.id} ${service.name} ${minutesLabel(service.durationMinutes)}`);
984
+ }
985
+ }
986
+ if (settings.affectedAgentIds.length > 0) {
987
+ lines.push(`This calendar is read by ${settings.affectedAgentIds.length} agent(s): ${settings.affectedAgentIds.join(", ")}`);
988
+ }
989
+ return lines;
990
+ }
991
+ async function readTextFile(path) {
992
+ try {
993
+ return await readFile(path, "utf8");
994
+ }
995
+ catch (err) {
996
+ throw new UsageError(`Cannot read ${path}: ${err.message}`);
997
+ }
998
+ }
999
+ async function readBinaryFile(path) {
1000
+ try {
1001
+ return new Uint8Array(await readFile(path));
1002
+ }
1003
+ catch (err) {
1004
+ throw new UsageError(`Cannot read ${path}: ${err.message}`);
1005
+ }
1006
+ }
1007
+ async function readJsonObjectFile(path) {
1008
+ const value = await readJsonFile(path);
1009
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1010
+ throw new UsageError(`${path} must hold a JSON object.`);
1011
+ }
1012
+ return value;
1013
+ }
1014
+ async function bookingGet(args, deps) {
1015
+ const { values, positionals } = parse(args, {});
1016
+ const agentId = need(positionals, 0, "agentId");
1017
+ const settings = await (await clientFor(values, deps)).getBookingSettings(agentId);
1018
+ if (values.json)
1019
+ printJson(deps, settings);
1020
+ else
1021
+ for (const line of bookingText(settings))
1022
+ deps.io.out(line);
1023
+ return 0;
1024
+ }
1025
+ const BOOKING_REVISION_HELP = "the revision `kumion booking get` showed for the 予約設定 you are changing.";
1026
+ async function bookingCalendarUpdate(args, deps) {
1027
+ const { values } = parse(args, { revision: { type: "string" }, "patch-file": { type: "string" }, "dry-run": { type: "boolean" } });
1028
+ if (values["patch-file"] === undefined) {
1029
+ throw new UsageError("Pass --patch-file <path> holding defaultSlotMinutes, minLeadMinutes and/or maxAdvanceDays.");
1030
+ }
1031
+ const patch = (await readJsonObjectFile(values["patch-file"]));
1032
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1033
+ const result = await (await clientFor(values, deps)).updateBookingCalendar(patch, revision, { dryRun: values["dry-run"] });
1034
+ if (values.json) {
1035
+ printJson(deps, result);
1036
+ return 0;
1037
+ }
1038
+ const calendar = result.calendar;
1039
+ const summary = `枠 ${calendar.defaultSlotMinutes}分 直前予約の締め切り ${calendar.minLeadMinutes}分前 何日先まで ${calendar.maxAdvanceDays}日`;
1040
+ if (values["dry-run"]) {
1041
+ deps.io.out(`Dry run: nothing was saved. The calendar is at revision ${result.revision}.`);
1042
+ deps.io.out(summary);
1043
+ return 0;
1044
+ }
1045
+ deps.io.out(`Saved and live now — no publish needed. New revision: ${result.revision}`);
1046
+ deps.io.out(summary);
1047
+ if (result.affectedAgentIds.length > 0) {
1048
+ deps.io.out(`The next slot on ${result.affectedAgentIds.length} agent(s) uses these settings.`);
1049
+ }
1050
+ return 0;
1051
+ }
1052
+ function bookingServiceText(service) {
1053
+ return `${service.name} ${minutesLabel(service.durationMinutes)}`;
1054
+ }
1055
+ async function bookingServicesCreate(args, deps) {
1056
+ const { values } = parse(args, { revision: { type: "string" }, "data-file": { type: "string" }, "dry-run": { type: "boolean" } });
1057
+ if (values["data-file"] === undefined) {
1058
+ throw new UsageError("Pass --data-file <path> holding name, and durationMinutes (or null for the slot length).");
1059
+ }
1060
+ const service = (await readJsonObjectFile(values["data-file"]));
1061
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1062
+ const result = await (await clientFor(values, deps)).createBookingService(service, revision, { dryRun: values["dry-run"] });
1063
+ if (values.json) {
1064
+ printJson(deps, result);
1065
+ return 0;
1066
+ }
1067
+ if (values["dry-run"]) {
1068
+ deps.io.out(`Dry run: nothing was saved. Would add: ${bookingServiceText(result.service)}`);
1069
+ return 0;
1070
+ }
1071
+ deps.io.out(`Added 内容 ${result.service.id} ${bookingServiceText(result.service)}`);
1072
+ deps.io.out(`Saved and live now — no publish needed. New revision: ${result.revision}`);
1073
+ return 0;
1074
+ }
1075
+ async function bookingServicesUpdate(args, deps) {
1076
+ const { values, positionals } = parse(args, {
1077
+ revision: { type: "string" },
1078
+ "patch-file": { type: "string" },
1079
+ "dry-run": { type: "boolean" },
1080
+ });
1081
+ const serviceId = need(positionals, 0, "serviceId");
1082
+ if (values["patch-file"] === undefined) {
1083
+ throw new UsageError("Pass --patch-file <path> holding name and/or durationMinutes (null = the slot length).");
1084
+ }
1085
+ const patch = (await readJsonObjectFile(values["patch-file"]));
1086
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1087
+ const result = await (await clientFor(values, deps)).updateBookingService(serviceId, patch, revision, {
1088
+ dryRun: values["dry-run"],
1089
+ });
1090
+ if (values.json) {
1091
+ printJson(deps, result);
1092
+ return 0;
1093
+ }
1094
+ if (values["dry-run"]) {
1095
+ deps.io.out(`Dry run: nothing was saved. Would be: ${bookingServiceText(result.service)}`);
1096
+ return 0;
1097
+ }
1098
+ deps.io.out(`Saved and live now — no publish needed. 内容 ${serviceId}: ${bookingServiceText(result.service)}`);
1099
+ deps.io.out(`New revision: ${result.revision}`);
1100
+ return 0;
1101
+ }
1102
+ function weeklyHoursLabel(hours) {
1103
+ const days = Object.keys(hours).filter((day) => (hours[day] ?? []).length > 0);
1104
+ return days.length === 0 ? "枠なし(この担当には予約が入りません)" : `${days.join("・")} の ${days.length}日`;
1105
+ }
1106
+ function bookingResourceText(resource) {
1107
+ const service = resource.serviceRestriction === "all" ? "すべての内容" : `内容 ${resource.serviceIds.length} 件`;
1108
+ return `${resource.name} ${resource.enabled ? "enabled" : "disabled"} 枠 ${weeklyHoursLabel(resource.weeklyHours)} ${service}`;
1109
+ }
1110
+ async function bookingResourcesCreate(args, deps) {
1111
+ const { values } = parse(args, { revision: { type: "string" }, "data-file": { type: "string" }, "dry-run": { type: "boolean" } });
1112
+ if (values["data-file"] === undefined) {
1113
+ throw new UsageError("Pass --data-file <path> holding name, and enabled / weeklyHours / serviceIds.");
1114
+ }
1115
+ const input = (await readJsonObjectFile(values["data-file"]));
1116
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1117
+ const result = await (await clientFor(values, deps)).createBookingResource(input, revision, {
1118
+ dryRun: values["dry-run"],
1119
+ });
1120
+ if (values.json) {
1121
+ printJson(deps, result);
1122
+ return 0;
1123
+ }
1124
+ if (values["dry-run"]) {
1125
+ deps.io.out(`Dry run: nothing was saved. Would add: ${bookingResourceText(result.resource)}`);
1126
+ return 0;
1127
+ }
1128
+ deps.io.out(`Added 担当 ${result.resource.id} ${bookingResourceText(result.resource)}`);
1129
+ deps.io.out(`Saved and live now — no publish needed. New revision: ${result.revision}`);
1130
+ return 0;
1131
+ }
1132
+ async function bookingResourcesUpdate(args, deps) {
1133
+ const { values, positionals } = parse(args, {
1134
+ revision: { type: "string" },
1135
+ "patch-file": { type: "string" },
1136
+ "dry-run": { type: "boolean" },
1137
+ });
1138
+ const resourceId = need(positionals, 0, "resourceId");
1139
+ if (values["patch-file"] === undefined) {
1140
+ throw new UsageError("Pass --patch-file <path> holding name, enabled, weeklyHours and/or serviceIds ([] = every 内容).");
1141
+ }
1142
+ const patch = (await readJsonObjectFile(values["patch-file"]));
1143
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1144
+ const result = await (await clientFor(values, deps)).updateBookingResource(resourceId, patch, revision, {
1145
+ dryRun: values["dry-run"],
1146
+ });
1147
+ if (values.json) {
1148
+ printJson(deps, result);
1149
+ return 0;
1150
+ }
1151
+ if (values["dry-run"]) {
1152
+ deps.io.out(`Dry run: nothing was saved. Would be: ${bookingResourceText(result.resource)}`);
1153
+ return 0;
1154
+ }
1155
+ deps.io.out(`Saved and live now — no publish needed. 担当 ${resourceId}: ${bookingResourceText(result.resource)}`);
1156
+ deps.io.out(`New revision: ${result.revision}`);
1157
+ return 0;
1158
+ }
1159
+ async function bookingMount(args, deps) {
1160
+ const { values, positionals } = parse(args, {
1161
+ revision: { type: "string" },
1162
+ mounted: { type: "string" },
1163
+ "dry-run": { type: "boolean" },
1164
+ });
1165
+ const agentId = need(positionals, 0, "agentId");
1166
+ const mounted = parseYesNo(values.mounted, "mounted");
1167
+ if (mounted === undefined)
1168
+ throw new UsageError("Pass --mounted true or --mounted false.");
1169
+ const revision = requireRevision(values.revision, BOOKING_REVISION_HELP);
1170
+ const result = await (await clientFor(values, deps)).setAgentBooking(agentId, mounted, revision, {
1171
+ dryRun: values["dry-run"],
1172
+ });
1173
+ if (values.json) {
1174
+ printJson(deps, result);
1175
+ return 0;
1176
+ }
1177
+ const state = result.mounted ? "takes bookings" : "does not take bookings";
1178
+ if (values["dry-run"]) {
1179
+ deps.io.out(`Dry run: nothing was saved. This agent would ${result.mounted ? "start" : "stop"} taking bookings.`);
1180
+ return 0;
1181
+ }
1182
+ deps.io.out(`Saved and live now — no publish needed. This agent ${state}. New revision: ${result.revision}`);
1183
+ if (result.receptionSummaryRetired > 0) {
1184
+ deps.io.out(`Retired 仮受付 from ${result.receptionSummaryRetired} 受付サマリー spec(s): the calendar confirms for real now.`);
1185
+ }
1186
+ return 0;
1187
+ }
1188
+ function bookingSlotText(slot) {
1189
+ const minutes = Math.round((new Date(slot.endAt).getTime() - new Date(slot.startAt).getTime()) / 60_000);
1190
+ return `${slot.startAt.slice(0, 16).replace("T", " ")}(${minutes}分)`;
1191
+ }
1192
+ async function bookingSlots(args, deps) {
1193
+ const { values, positionals } = parse(args, {
1194
+ resource: { type: "string" },
1195
+ date: { type: "string" },
1196
+ service: { type: "string" },
1197
+ limit: { type: "string" },
1198
+ });
1199
+ const agentId = need(positionals, 0, "agentId");
1200
+ if (values.resource === undefined)
1201
+ throw new UsageError("Pass --resource <resourceId> (the 担当's id, from `booking get`).");
1202
+ if (values.date === undefined)
1203
+ throw new UsageError("Pass --date <YYYY-MM-DD>.");
1204
+ const limit = values.limit === undefined ? undefined : Number(values.limit);
1205
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {
1206
+ throw new UsageError("--limit takes a whole number of slots.");
1207
+ }
1208
+ const view = await (await clientFor(values, deps)).listBookingSlots(agentId, {
1209
+ resourceId: values.resource,
1210
+ date: values.date,
1211
+ ...(values.service === undefined ? {} : { serviceId: values.service }),
1212
+ ...(limit === undefined ? {} : { limit }),
1213
+ });
1214
+ if (values.json) {
1215
+ printJson(deps, view);
1216
+ return 0;
1217
+ }
1218
+ deps.io.out(`${view.resource.name} ${view.date} (${view.resource.enabled ? "enabled" : "disabled"})`);
1219
+ if (!view.mounted) {
1220
+ deps.io.out("This agent is not mounted on the calendar, so it will not offer these slots (see `booking mount`).");
1221
+ }
1222
+ if (!view.serviceAllowed) {
1223
+ deps.io.out("This 担当 does not take that 内容, so no slot of that length is offered.");
1224
+ return 0;
1225
+ }
1226
+ if (view.slots.length === 0) {
1227
+ deps.io.out("No openings on that day.");
1228
+ return 0;
1229
+ }
1230
+ for (const slot of view.slots)
1231
+ deps.io.out(` ${bookingSlotText(slot)}`);
1232
+ return 0;
1233
+ }
1234
+ const CAPTURE_SPEC_REVISION_HELP = "the revision `kumion capture-specs list` showed for the 記録項目 you are changing.";
1235
+ function captureSpecScope(spec) {
1236
+ return spec.affectedAgentIds.length === 0 ? "no agent yet" : `${spec.affectedAgentIds.length} agent(s)`;
1237
+ }
1238
+ function captureSpecLine(spec) {
1239
+ return `${spec.id} ${spec.enabled ? "enabled " : "disabled"} ${spec.label} [key ${spec.key} revision ${spec.revision}] ${captureSpecScope(spec)}`;
1240
+ }
1241
+ async function captureSpecsList(args, deps) {
1242
+ const { values } = parse(args, {});
1243
+ const specs = await (await clientFor(values, deps)).listCaptureSpecs();
1244
+ if (values.json) {
1245
+ printJson(deps, { captureSpecs: specs });
1246
+ return 0;
1247
+ }
1248
+ if (specs.length === 0)
1249
+ deps.io.out("No 記録項目.");
1250
+ else
1251
+ for (const spec of specs)
1252
+ deps.io.out(captureSpecLine(spec));
1253
+ return 0;
1254
+ }
1255
+ async function captureSpecsCreate(args, deps) {
1256
+ const { values } = parse(args, { "data-file": { type: "string" } });
1257
+ if (values["data-file"] === undefined) {
1258
+ throw new UsageError("Pass --data-file <path> holding label, fields, and optionally key / scenario / instruction.");
1259
+ }
1260
+ const input = (await readJsonObjectFile(values["data-file"]));
1261
+ if (input.fields === undefined)
1262
+ throw new UsageError(`${values["data-file"]} must hold fields.`);
1263
+ const spec = await (await clientFor(values, deps)).createCaptureSpec({ ...input, fields: input.fields });
1264
+ if (values.json) {
1265
+ printJson(deps, { captureSpec: spec });
1266
+ return 0;
1267
+ }
1268
+ deps.io.out(`Created 記録項目 ${spec.id} ${spec.label} [key ${spec.key} revision ${spec.revision}]`);
1269
+ deps.io.out("No agent records it yet — mount it on an agent before it can record anything.");
1270
+ return 0;
1271
+ }
1272
+ async function captureSpecsUpdate(args, deps) {
1273
+ const { values, positionals } = parse(args, { revision: { type: "string" }, "patch-file": { type: "string" } });
1274
+ const specId = need(positionals, 0, "specId");
1275
+ if (values["patch-file"] === undefined) {
1276
+ throw new UsageError("Pass --patch-file <path> holding the fields to change (see `kumion --help`).");
1277
+ }
1278
+ const patch = (await readJsonObjectFile(values["patch-file"]));
1279
+ const revision = requireRevision(values.revision, CAPTURE_SPEC_REVISION_HELP);
1280
+ const spec = await (await clientFor(values, deps)).updateCaptureSpec(specId, patch, revision);
1281
+ if (values.json) {
1282
+ printJson(deps, { captureSpec: spec });
1283
+ return 0;
1284
+ }
1285
+ deps.io.out(`Saved and live now — no publish needed. 記録項目 ${specId}: ${spec.label}`);
1286
+ deps.io.out(`New revision: ${spec.revision}`);
1287
+ if (spec.affectedAgentIds.length === 0)
1288
+ deps.io.out("No agent is mounted with this 記録項目, so no call records it yet.");
1289
+ else
1290
+ deps.io.out(`Every agent mounted with it records differently from its next call: ${spec.affectedAgentIds.join(", ")}`);
1291
+ return 0;
1292
+ }
1293
+ const AGENT_CAPTURE_REVISION_HELP = "the revision `kumion agents capture get` showed for this agent.";
1294
+ function printAgentCaptureReadiness(capture, deps) {
1295
+ if (capture.readiness.ready) {
1296
+ deps.io.out(`Ready: ${capture.enabledMountedCount} 記録項目 will be extracted after a call.`);
1297
+ return;
1298
+ }
1299
+ deps.io.out("NOT ready — a call on this agent records nothing:");
1300
+ for (const issue of capture.readiness.issues)
1301
+ deps.io.out(` ${issue.message}`);
1302
+ }
1303
+ function printAgentCapture(capture, deps) {
1304
+ if (capture.captureSpecIds.length === 0)
1305
+ deps.io.out("No 記録項目 mounted on this agent.");
1306
+ for (const spec of capture.captureSpecs) {
1307
+ deps.io.out(`${spec.id} ${spec.enabled ? "enabled " : "disabled"} ${spec.label} [key ${spec.key} revision ${spec.revision}]`);
1308
+ }
1309
+ printAgentCaptureReadiness(capture, deps);
1310
+ deps.io.out(`Revision: ${capture.revision}`);
1311
+ }
1312
+ async function agentsCaptureGet(args, deps) {
1313
+ const { values, positionals } = parse(args, {});
1314
+ const agentId = need(positionals, 0, "agentId");
1315
+ const capture = await (await clientFor(values, deps)).getAgentCapture(agentId);
1316
+ if (values.json) {
1317
+ printJson(deps, capture);
1318
+ return 0;
1319
+ }
1320
+ printAgentCapture(capture, deps);
1321
+ return 0;
1322
+ }
1323
+ async function agentsCaptureSet(args, deps) {
1324
+ const { values, positionals } = parse(args, {
1325
+ revision: { type: "string" },
1326
+ spec: { type: "string", multiple: true },
1327
+ clear: { type: "boolean" },
1328
+ });
1329
+ const agentId = need(positionals, 0, "agentId");
1330
+ const specs = values.spec ?? [];
1331
+ if (values.clear && specs.length > 0) {
1332
+ throw new UsageError("Pass either --spec <specId> (repeatable) or --clear, not both.");
1333
+ }
1334
+ if (!values.clear && specs.length === 0) {
1335
+ throw new UsageError("Pass --spec <specId> (repeatable) to mount, or --clear to record nothing.");
1336
+ }
1337
+ const revision = requireRevision(values.revision, AGENT_CAPTURE_REVISION_HELP);
1338
+ const capture = await (await clientFor(values, deps)).setAgentCapture(agentId, specs, revision);
1339
+ if (values.json) {
1340
+ printJson(deps, capture);
1341
+ return 0;
1342
+ }
1343
+ deps.io.out(capture.captureSpecIds.length === 0
1344
+ ? "Saved and live now — no publish needed. This agent records nothing after a call."
1345
+ : `Saved and live now — no publish needed. This agent records: ${capture.captureSpecs.map((spec) => spec.label).join(", ")}`);
1346
+ printAgentCaptureReadiness(capture, deps);
1347
+ deps.io.out(`New revision: ${capture.revision}`);
1348
+ return 0;
1349
+ }
1350
+ function documentJobText(job) {
1351
+ const head = `${job.jobId} ${job.status}`;
1352
+ if (job.status === "succeeded")
1353
+ return `${head} document ${job.documentId}`;
1354
+ if (job.error)
1355
+ return `${head} ${job.error.code}: ${job.error.message}`;
1356
+ return `${head} (deadline ${job.deadlineAt})`;
1357
+ }
1358
+ async function documentsUpload(args, deps) {
1359
+ const { values } = parse(args, {
1360
+ "text-file": { type: "string" },
1361
+ file: { type: "string", multiple: true },
1362
+ title: { type: "string" },
1363
+ template: { type: "string" },
1364
+ "idempotency-key": { type: "string" },
1365
+ "dry-run": { type: "boolean" },
1366
+ });
1367
+ const textFile = values["text-file"];
1368
+ const files = values.file ?? [];
1369
+ if (textFile !== undefined && files.length > 0) {
1370
+ throw new UsageError("Pass either --text-file or --file, not both: the API takes the text OR the files.");
1371
+ }
1372
+ if (textFile === undefined && files.length === 0) {
1373
+ throw new UsageError("Pass --text-file <path> for the text of the 資料, or --file <path> (repeatable) for files.");
1374
+ }
1375
+ if (!values.title)
1376
+ throw new UsageError("Pass --title <title>.");
1377
+ const idempotencyKey = values["idempotency-key"];
1378
+ if (!idempotencyKey) {
1379
+ throw new UsageError("Pass --idempotency-key <key>: a retry with the same key answers the job it already made.");
1380
+ }
1381
+ const payload = textFile === undefined
1382
+ ? {
1383
+ files: await Promise.all(files.map(async (path) => ({ filename: basename(path), bytes: await readBinaryFile(path) }))),
1384
+ }
1385
+ : { rawText: await readTextFile(textFile) };
1386
+ const result = await (await clientFor(values, deps)).uploadDocument({
1387
+ title: values.title,
1388
+ idempotencyKey,
1389
+ ...payload,
1390
+ ...(values.template === undefined ? {} : { templateId: values.template }),
1391
+ }, { dryRun: values["dry-run"] });
1392
+ if (values.json) {
1393
+ printJson(deps, result);
1394
+ return 0;
1395
+ }
1396
+ if ("dryRun" in result) {
1397
+ 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.`);
1398
+ deps.io.out(`Model: ${result.provider}${result.model ? ` / ${result.model}` : ""}`);
1399
+ deps.io.out(`Allowance left: ${result.budget.keyRemaining} for this key, ${result.budget.tenantRemaining} for the tenant (per hour).`);
1400
+ deps.io.out("Price: not available (amount is null) — extractions are counted, not billed per run.");
1401
+ return 0;
1402
+ }
1403
+ deps.io.out(`Accepted. ${documentJobText(result)}`);
1404
+ deps.io.out(`Check it with: kumion documents jobs get ${result.jobId}`);
1405
+ return 0;
1406
+ }
1407
+ async function documentsJobsGet(args, deps) {
1408
+ const { values, positionals } = parse(args, {});
1409
+ const jobId = need(positionals, 0, "jobId");
1410
+ const job = await (await clientFor(values, deps)).getDocumentUploadJob(jobId);
1411
+ if (values.json)
1412
+ printJson(deps, job);
1413
+ else
1414
+ deps.io.out(documentJobText(job));
1415
+ return job.status === "failed" || job.status === "timed_out" ? 1 : 0;
1416
+ }
1417
+ async function documentsGet(args, deps) {
1418
+ const { values, positionals } = parse(args, {});
1419
+ const documentId = need(positionals, 0, "documentId");
1420
+ const document = await (await clientFor(values, deps)).getDocument(documentId);
1421
+ if (values.json) {
1422
+ printJson(deps, document);
1423
+ return 0;
1424
+ }
1425
+ const summary = document.document;
1426
+ deps.io.out(`${summary.id} ${summary.title} [${summary.status}, ${summary.mode}, revision ${document.revision}]`);
1427
+ deps.io.out(`${summary.charCount.toLocaleString("en-US")} characters, ${document.fields.length} field(s)`);
1428
+ for (const field of document.fields) {
1429
+ deps.io.out(` ${field.fieldKey} ${field.label} (${field.category}, ${field.reviewState})`);
1430
+ }
1431
+ for (const reference of document.references) {
1432
+ deps.io.out(reference.kind === "agent"
1433
+ ? ` used by agent ${reference.agentName} (${reference.agentId})`
1434
+ : ` used by node ${reference.nodeName ?? reference.nodeKey} of ${reference.workflowName} (${reference.workflowId})`);
1435
+ }
1436
+ return 0;
1437
+ }
1438
+ async function documentsReplace(args, deps) {
1439
+ const { values, positionals } = parse(args, {
1440
+ source: { type: "string" },
1441
+ "source-revision": { type: "string" },
1442
+ revision: { type: "string" },
1443
+ "dry-run": { type: "boolean" },
1444
+ });
1445
+ const documentId = need(positionals, 0, "documentId");
1446
+ if (!values.source)
1447
+ throw new UsageError("Pass --source <documentId>: the 資料 the new content comes from.");
1448
+ if (!values["source-revision"]) {
1449
+ throw new UsageError("Pass --source-revision <revision> — the source's revision, from `kumion documents get`.");
1450
+ }
1451
+ const revision = requireRevision(values.revision, "the 資料's revision from `kumion documents get`. It changes when anyone confirms or edits a fact.");
1452
+ const result = await (await clientFor(values, deps)).replaceDocument(documentId, { sourceDocumentId: values.source, sourceRevision: values["source-revision"] }, revision, { dryRun: values["dry-run"] });
1453
+ if (values.json) {
1454
+ printJson(deps, result);
1455
+ return 0;
1456
+ }
1457
+ const { changes } = result;
1458
+ const lines = [];
1459
+ lines.push(result.dryRun
1460
+ ? `Would replace ${result.document.id} with the content of ${result.source.documentId} — nothing is written.`
1461
+ : `Replaced ${result.document.id} with the content of ${result.source.documentId}.`);
1462
+ lines.push(`Characters: ${changes.characters.before.toLocaleString("en-US")} → ${changes.characters.after.toLocaleString("en-US")}`);
1463
+ if (changes.fields.added.length > 0)
1464
+ lines.push(`New facts: ${changes.fields.added.join(", ")}`);
1465
+ if (changes.fields.placeholders.length > 0) {
1466
+ lines.push(`Kept as empty (the new 資料 does not mention them): ${changes.fields.placeholders.join(", ")}`);
1467
+ }
1468
+ if (changes.fields.removed.length > 0)
1469
+ lines.push(`Gone: ${changes.fields.removed.join(", ")}`);
1470
+ lines.push(`Confirmations reset: ${result.resetConfirmedCount}. Every fact is pending again — review them before publishing.`);
1471
+ if (result.affectedAgentIds.length > 0) {
1472
+ lines.push(`Read by: ${result.affectedAgentIds.join(", ")} (live from their next call)`);
1473
+ }
1474
+ lines.push(result.dryRun ? `Revision stays: ${result.revision}` : `New revision: ${result.revision}`);
1475
+ deps.io.out(lines.join("\n"));
1476
+ return 0;
1477
+ }
717
1478
  async function factsEdit(args, deps) {
718
1479
  const { values, positionals } = parse(args, { revision: { type: "string" }, value: { type: "string" } });
719
1480
  const agentId = need(positionals, 0, "agentId");
@@ -756,6 +1517,11 @@ async function agentsPublish(args, deps) {
756
1517
  else {
757
1518
  const agent = result.agent;
758
1519
  deps.io.out(`Published ${agent?.name ?? agentId} at ${agent?.publishedAt ?? "?"} (publish run ${String(result.publishRunId ?? "?")}).`);
1520
+ const unconfirmed = typeof result.unconfirmedFacts === "number" ? result.unconfirmedFacts : 0;
1521
+ if (unconfirmed > 0) {
1522
+ 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.`);
1523
+ deps.io.out(`Next: \`kumion facts confirm ${agentId}\``);
1524
+ }
759
1525
  }
760
1526
  return 0;
761
1527
  }