@plurnk/plurnk-contracts 9.0.0 → 10.0.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.
Files changed (81) hide show
  1. package/.env.defaults +1 -19
  2. package/README.md +5 -6
  3. package/SPEC.md +93 -44
  4. package/dist/schema/DaemonNotificationEnvelope.json +77 -30
  5. package/dist/schema/FunctionalityCandidate.json +4 -0
  6. package/dist/schema/FunctionalityDiscoverQuery.json +12 -0
  7. package/dist/schema/FunctionalityDiscoverResult.json +10 -0
  8. package/dist/schema/FunctionalityListQuery.json +33 -0
  9. package/dist/schema/FunctionalityListResult.json +16 -1
  10. package/dist/schema/ModelCatalogPage.json +9 -0
  11. package/dist/schema/PlurnkStatement.json +18 -2
  12. package/dist/schema/ProviderAccounting.json +3 -3
  13. package/dist/schema/ProviderCost.json +1 -1
  14. package/dist/schema/ProviderRequestAccounting.json +3 -3
  15. package/dist/schema/ProviderUsage.json +1 -1
  16. package/dist/src/ActorIdentity.d.ts +26 -0
  17. package/dist/src/ActorIdentity.d.ts.map +1 -0
  18. package/dist/src/ActorIdentity.js +179 -0
  19. package/dist/src/ActorIdentity.js.map +1 -0
  20. package/dist/src/Application.d.ts +38 -126
  21. package/dist/src/Application.d.ts.map +1 -1
  22. package/dist/src/Application.js +47 -220
  23. package/dist/src/Application.js.map +1 -1
  24. package/dist/src/ApplicationNotifications.d.ts +19 -6
  25. package/dist/src/ApplicationNotifications.d.ts.map +1 -1
  26. package/dist/src/ApplicationNotifications.js +6 -3
  27. package/dist/src/ApplicationNotifications.js.map +1 -1
  28. package/dist/src/ApplicationPort.d.ts +27 -6
  29. package/dist/src/ApplicationPort.d.ts.map +1 -1
  30. package/dist/src/ApplicationPort.js +1 -1
  31. package/dist/src/ApplicationPort.js.map +1 -1
  32. package/dist/src/ApplicationStream.d.ts +2 -2
  33. package/dist/src/ApplicationStream.d.ts.map +1 -1
  34. package/dist/src/ApplicationStream.js.map +1 -1
  35. package/dist/src/CollectionCommand.d.ts +33 -0
  36. package/dist/src/CollectionCommand.d.ts.map +1 -0
  37. package/dist/src/CollectionCommand.js +277 -0
  38. package/dist/src/CollectionCommand.js.map +1 -0
  39. package/dist/src/Functionality.d.ts +7 -2
  40. package/dist/src/Functionality.d.ts.map +1 -1
  41. package/dist/src/Functionality.js.map +1 -1
  42. package/dist/src/HttpOrigin.d.ts +79 -10
  43. package/dist/src/HttpOrigin.d.ts.map +1 -1
  44. package/dist/src/HttpOrigin.js +286 -44
  45. package/dist/src/HttpOrigin.js.map +1 -1
  46. package/dist/src/HttpPort.d.ts +35 -0
  47. package/dist/src/HttpPort.d.ts.map +1 -0
  48. package/dist/src/HttpPort.js +106 -0
  49. package/dist/src/HttpPort.js.map +1 -0
  50. package/dist/src/InteractiveCommands.d.ts +96 -0
  51. package/dist/src/InteractiveCommands.d.ts.map +1 -0
  52. package/dist/src/InteractiveCommands.js +409 -0
  53. package/dist/src/InteractiveCommands.js.map +1 -0
  54. package/dist/src/McpWireTool.d.ts +27 -0
  55. package/dist/src/McpWireTool.d.ts.map +1 -0
  56. package/dist/src/McpWireTool.js +30 -0
  57. package/dist/src/McpWireTool.js.map +1 -0
  58. package/dist/src/OAuthClient.d.ts +64 -0
  59. package/dist/src/OAuthClient.d.ts.map +1 -0
  60. package/dist/src/OAuthClient.js +226 -0
  61. package/dist/src/OAuthClient.js.map +1 -0
  62. package/dist/src/ScheduleCommand.d.ts +60 -0
  63. package/dist/src/ScheduleCommand.d.ts.map +1 -0
  64. package/dist/src/ScheduleCommand.js +677 -0
  65. package/dist/src/ScheduleCommand.js.map +1 -0
  66. package/dist/src/SessionProjection.d.ts +91 -0
  67. package/dist/src/SessionProjection.d.ts.map +1 -0
  68. package/dist/src/SessionProjection.js +223 -0
  69. package/dist/src/SessionProjection.js.map +1 -0
  70. package/dist/src/Validator.d.ts +2 -1
  71. package/dist/src/Validator.d.ts.map +1 -1
  72. package/dist/src/Validator.js +19 -1
  73. package/dist/src/Validator.js.map +1 -1
  74. package/dist/src/index.d.ts +10 -3
  75. package/dist/src/index.d.ts.map +1 -1
  76. package/dist/src/index.js +7 -1
  77. package/dist/src/index.js.map +1 -1
  78. package/dist/src/types.generated.d.ts +85 -21
  79. package/dist/src/types.generated.d.ts.map +1 -1
  80. package/dist/src/types.generated.js.map +1 -1
  81. package/package.json +3 -2
@@ -0,0 +1,677 @@
1
+ // {§contract-representations} {§acp-action-binding} {§client-family-commands} {§client-schedule-command}
2
+ // Runtime-neutral schedule wire types, quote-preserving slash-argument tokenizer,
3
+ // schedule command parser, Problem extractor, and row/inspect/receipt formatters.
4
+ import { isRecord } from "./guards.js";
5
+ import { formatListPageFooter, parseFamilyDiscoverArgs, parseFamilyListArgs } from "./CollectionCommand.js";
6
+ import Problems from "./Problems.js";
7
+ export const SCHEDULE_USAGE = `usage: /schedule [list|show|inspect|discover|add|replace|run|done|reopen|enable|disable|remove] [options]
8
+
9
+ subcommands:
10
+ list [query] [--state <s>] [--origin <o>] [--offset <n>] [--limit <n>]
11
+ List or filter workspace schedules and macros (default).
12
+ show <alias> | inspect <alias> Inspect one schedule or macro definition in full.
13
+ discover [<rule>] [--cursor <c>] [--limit <n>]
14
+ Show workspace clock or preview occurrences of <rule>.
15
+ add <alias> <session> <rule> <prompt...> Add a prompt schedule (cron, RRULE, +duration, ISO, manual, or once).
16
+ add <alias> [--manual|--once|--rule <r>] --target <session> [--persona <p>] [--catchup|--no-catchup] --prompt <text>
17
+ add <alias> [--manual|--once|--rule <r>] --step <server>.<tool> ['<json>'] [--aside <label>] [--step ...]
18
+ add <alias> [--manual|--once|--rule <r>] --run '<json-steps>'
19
+ replace ... Replace an existing schedule or macro using any add form.
20
+ run <alias> Execute a schedule or macro now and display step receipts.
21
+ done <alias> | reopen <alias> Mark an obligation done or reopen it.
22
+ enable <alias> | disable <alias> Enable or disable a schedule.
23
+ remove <alias> Remove a workspace schedule.
24
+ `;
25
+ export const SCHEDULE_ADD_FLAGS = Object.freeze([
26
+ { value: "--manual", description: "Reusable on-demand trigger (default)" },
27
+ { value: "--once", description: "Single-shot unscheduled obligation" },
28
+ { value: "--rule", description: "Cron, RRULE, +duration, or ISO timestamp" },
29
+ { value: "--step", description: "Add macro step: <server>.<tool> ['<json>']" },
30
+ { value: "--run", description: "JSON array of macro tool-call steps" },
31
+ { value: "--aside", description: "Short label for the preceding --step" },
32
+ { value: "--target", description: "Target session://<name>" },
33
+ { value: "--prompt", description: "Prompt text delivered to target session" },
34
+ { value: "--persona", description: "Optional persona for auto-created session" },
35
+ { value: "--catchup", description: "Fire missed window once on daemon wake" },
36
+ { value: "--no-catchup", description: "Skip missed occurrences after downtime" },
37
+ ]);
38
+ class FamilyCommandUsageError extends Error {
39
+ problem;
40
+ constructor(title, detail, recovery) {
41
+ super(detail);
42
+ this.name = "FamilyCommandUsageError";
43
+ this.problem = Problems.create("client", "usage", 400, detail, recovery !== undefined ? { recovery } : {}, { title });
44
+ }
45
+ }
46
+ const usageError = (title, detail, recovery) => new FamilyCommandUsageError(title, detail, recovery);
47
+ /**
48
+ * {§acp-action-binding} Shell-style tokenizer for interactive slash-command arguments so quoted rules
49
+ * (`"0 9 * * 1-5"`) and JSON step payloads (`'{"text":"echo hi"}'`) stay intact.
50
+ */
51
+ export const tokenizeSlashArgs = (raw) => {
52
+ const tokens = [];
53
+ let current = "";
54
+ let inToken = false;
55
+ let quote = null;
56
+ for (let i = 0; i < raw.length; i += 1) {
57
+ const ch = raw[i];
58
+ if (quote !== null) {
59
+ if (quote === '"' && ch === "\\" && i + 1 < raw.length) {
60
+ const next = raw[i + 1];
61
+ if (next === '"' || next === "\\" || next === "$" || next === "`") {
62
+ current += next;
63
+ i += 1;
64
+ continue;
65
+ }
66
+ }
67
+ if (ch === quote) {
68
+ quote = null;
69
+ continue;
70
+ }
71
+ current += ch;
72
+ continue;
73
+ }
74
+ if (ch === "'" || ch === '"') {
75
+ quote = ch;
76
+ inToken = true;
77
+ continue;
78
+ }
79
+ if (ch === "\\" && i + 1 < raw.length && /\s/u.test(raw[i + 1])) {
80
+ current += raw[i + 1];
81
+ inToken = true;
82
+ i += 1;
83
+ continue;
84
+ }
85
+ if (/\s/u.test(ch)) {
86
+ if (inToken) {
87
+ tokens.push(current);
88
+ current = "";
89
+ inToken = false;
90
+ }
91
+ continue;
92
+ }
93
+ current += ch;
94
+ inToken = true;
95
+ }
96
+ if (quote !== null) {
97
+ throw usageError("Unterminated quote", `Unclosed ${quote === "'" ? "single" : "double"} quote in command arguments.`);
98
+ }
99
+ if (inToken) {
100
+ tokens.push(current);
101
+ }
102
+ return tokens;
103
+ };
104
+ const normalizeTarget = (raw) => raw.startsWith("session://") ? raw : `session://${raw}`;
105
+ const validateToolCall = (raw, index) => {
106
+ if (!isRecord(raw)) {
107
+ throw usageError("Invalid macro step", `Step #${String(index)} must be a JSON object with 'server' and 'tool'.`, `--run '[{"server":"plurnk","tool":"sh","arguments":{"text":"echo hi"}}]'`);
108
+ }
109
+ const server = typeof raw.server === "string" ? raw.server.trim() : "";
110
+ const tool = typeof raw.tool === "string" ? raw.tool.trim() : "";
111
+ if (server.length === 0 || tool.length === 0) {
112
+ throw usageError("Invalid macro step", `Step #${String(index)} requires non-empty 'server' and 'tool' strings.`, `--run '[{"server":"plurnk","tool":"sh","arguments":{"text":"echo hi"}}]'`);
113
+ }
114
+ let stepArgs;
115
+ if (raw.arguments !== undefined) {
116
+ if (!isRecord(raw.arguments)) {
117
+ throw usageError("Invalid step arguments", `Step #${String(index)} (${server}.${tool}) 'arguments' must be a JSON object.`);
118
+ }
119
+ stepArgs = raw.arguments;
120
+ }
121
+ let aside;
122
+ if (raw.aside !== undefined) {
123
+ if (typeof raw.aside !== "string" || raw.aside.trim().length === 0) {
124
+ throw usageError("Invalid step aside", `Step #${String(index)} (${server}.${tool}) 'aside' must be a non-empty string.`);
125
+ }
126
+ aside = raw.aside.trim();
127
+ }
128
+ return {
129
+ server,
130
+ tool,
131
+ ...(stepArgs !== undefined && Object.keys(stepArgs).length > 0 ? { arguments: stepArgs } : {}),
132
+ ...(aside !== undefined ? { aside } : {}),
133
+ };
134
+ };
135
+ const parseRunJson = (raw) => {
136
+ let parsed;
137
+ try {
138
+ parsed = JSON.parse(raw);
139
+ }
140
+ catch (err) {
141
+ throw usageError("Invalid --run JSON", `--run requires a JSON array of { server, tool, arguments?, aside? } steps: ${err instanceof Error ? err.message : String(err)}`, `--run '[{"server":"plurnk","tool":"sh","arguments":{"text":"echo hi"}}]'`);
142
+ }
143
+ const list = Array.isArray(parsed) ? parsed : isRecord(parsed) ? [parsed] : null;
144
+ if (list === null || list.length === 0) {
145
+ throw usageError("Invalid --run steps", "--run must be a non-empty JSON array of { server, tool, arguments?, aside? } objects.", `--run '[{"server":"plurnk","tool":"sh","arguments":{"text":"echo hi"}}]'`);
146
+ }
147
+ return list.map((item, idx) => validateToolCall(item, idx));
148
+ };
149
+ const parseStepSpec = (spec) => {
150
+ const dot = spec.indexOf(".");
151
+ if (dot <= 0 || dot === spec.length - 1) {
152
+ throw usageError("Invalid --step target", `--step expects <server>.<tool> (got ${JSON.stringify(spec)}).`, `--step plurnk.sh '{"text":"echo hi"}'`);
153
+ }
154
+ const server = spec.slice(0, dot).trim();
155
+ const tool = spec.slice(dot + 1).trim();
156
+ if (server.length === 0 || tool.length === 0) {
157
+ throw usageError("Invalid --step target", `--step expects non-empty <server>.<tool> (got ${JSON.stringify(spec)}).`, `--step plurnk.sh '{"text":"echo hi"}'`);
158
+ }
159
+ return { server, tool };
160
+ };
161
+ const requireFlagValue = (flag, value) => {
162
+ if (value === undefined) {
163
+ throw usageError("Missing option value", `${flag} requires a value.`);
164
+ }
165
+ return value;
166
+ };
167
+ /**
168
+ * {§acp-action-binding} Canonical `schedule` subcommand parser shared by `parseFamilyCommand`, ACP, CLI, and Web.
169
+ */
170
+ export const parseScheduleFamilyArgs = (rawSub, rest) => {
171
+ const sub = rawSub.toLowerCase();
172
+ if (sub === "list") {
173
+ return {
174
+ scopePrefix: "workspace",
175
+ sub: "list",
176
+ rest,
177
+ actionName: "workspace.schedule.list",
178
+ params: parseFamilyListArgs(rest),
179
+ };
180
+ }
181
+ if (sub === "show" || sub === "inspect") {
182
+ const alias = (rest[0] ?? "").trim();
183
+ if (alias.length === 0) {
184
+ throw usageError("Missing schedule alias", `usage: /schedule ${sub} <alias>`);
185
+ }
186
+ return {
187
+ scopePrefix: "workspace",
188
+ sub: "inspect",
189
+ rest: [alias, ...rest.slice(1)],
190
+ actionName: "workspace.schedule.list",
191
+ params: {},
192
+ };
193
+ }
194
+ if (sub === "discover") {
195
+ return {
196
+ scopePrefix: "workspace",
197
+ sub: "discover",
198
+ rest,
199
+ actionName: "workspace.schedule.discover",
200
+ params: parseFamilyDiscoverArgs("schedule", rest),
201
+ };
202
+ }
203
+ if (sub === "enable" || sub === "disable" || sub === "remove") {
204
+ const alias = (rest[0] ?? "").trim();
205
+ if (alias.length === 0) {
206
+ throw usageError("Missing schedule alias", `usage: /schedule ${sub} <alias>`);
207
+ }
208
+ return {
209
+ scopePrefix: "workspace",
210
+ sub,
211
+ rest,
212
+ actionName: `workspace.schedule.${sub}`,
213
+ params: { alias },
214
+ };
215
+ }
216
+ if (sub === "run") {
217
+ const alias = (rest[0] ?? "").trim();
218
+ if (alias.length === 0) {
219
+ throw usageError("Missing schedule alias", "usage: /schedule run <alias>");
220
+ }
221
+ return {
222
+ scopePrefix: "workspace",
223
+ sub: "run",
224
+ rest,
225
+ actionName: "workspace.schedule.run",
226
+ params: { alias },
227
+ };
228
+ }
229
+ if (sub === "done" || sub === "reopen" || sub === "open") {
230
+ const alias = (rest[0] ?? "").trim();
231
+ if (alias.length === 0) {
232
+ throw usageError("Missing schedule alias", `usage: /schedule ${sub} <alias>`);
233
+ }
234
+ return {
235
+ scopePrefix: "workspace",
236
+ sub: "status",
237
+ rest,
238
+ actionName: "workspace.schedule.status",
239
+ params: { alias, status: sub === "done" ? "done" : "open" },
240
+ };
241
+ }
242
+ if (sub === "add" || sub === "replace") {
243
+ let timingKind;
244
+ let ruleFlag;
245
+ let runFlag;
246
+ let targetFlag;
247
+ let promptFlag;
248
+ let personaFlag;
249
+ let catchupFlag;
250
+ const steps = [];
251
+ const posArgs = [];
252
+ const setTiming = (kind, value) => {
253
+ if (timingKind !== undefined) {
254
+ throw usageError("Conflicting timing flags", "Specify at most one of --manual, --once, or --rule.");
255
+ }
256
+ timingKind = kind;
257
+ ruleFlag = value;
258
+ };
259
+ for (let i = 0; i < rest.length; i += 1) {
260
+ const tok = rest[i];
261
+ if (tok === "--manual") {
262
+ setTiming("manual", "manual");
263
+ }
264
+ else if (tok === "--once") {
265
+ setTiming("once", "once");
266
+ }
267
+ else if (tok === "--rule") {
268
+ setTiming("rule", requireFlagValue("--rule", rest[i + 1]));
269
+ i += 1;
270
+ }
271
+ else if (tok.startsWith("--rule=")) {
272
+ setTiming("rule", tok.slice("--rule=".length));
273
+ }
274
+ else if (tok === "--run") {
275
+ runFlag = requireFlagValue("--run", rest[i + 1]);
276
+ i += 1;
277
+ }
278
+ else if (tok.startsWith("--run=")) {
279
+ runFlag = tok.slice("--run=".length);
280
+ }
281
+ else if (tok === "--step" || tok.startsWith("--step=")) {
282
+ const rawSpec = tok === "--step"
283
+ ? requireFlagValue("--step", rest[i + 1])
284
+ : tok.slice("--step=".length);
285
+ if (tok === "--step")
286
+ i += 1;
287
+ const { server, tool } = parseStepSpec(rawSpec);
288
+ const next = rest[i + 1];
289
+ let stepArgs;
290
+ if (next !== undefined && !next.startsWith("--") && next.trim().startsWith("{")) {
291
+ let parsedArgs;
292
+ try {
293
+ parsedArgs = JSON.parse(next);
294
+ }
295
+ catch (err) {
296
+ throw usageError("Invalid --step arguments JSON", `Step ${server}.${tool} arguments must be valid JSON: ${err instanceof Error ? err.message : String(err)}`);
297
+ }
298
+ if (!isRecord(parsedArgs)) {
299
+ throw usageError("Invalid --step arguments JSON", `Step ${server}.${tool} arguments must be a JSON object.`);
300
+ }
301
+ stepArgs = parsedArgs;
302
+ i += 1;
303
+ }
304
+ steps.push({
305
+ server,
306
+ tool,
307
+ ...(stepArgs !== undefined && Object.keys(stepArgs).length > 0 ? { arguments: stepArgs } : {}),
308
+ });
309
+ }
310
+ else if (tok === "--aside" || tok.startsWith("--aside=")) {
311
+ const asideVal = tok === "--aside"
312
+ ? requireFlagValue("--aside", rest[i + 1])
313
+ : tok.slice("--aside=".length);
314
+ if (tok === "--aside")
315
+ i += 1;
316
+ const lastStep = steps.at(-1);
317
+ if (lastStep === undefined) {
318
+ throw usageError("Unexpected --aside", "--aside must follow a --step <server>.<tool> flag.");
319
+ }
320
+ lastStep.aside = asideVal;
321
+ }
322
+ else if (tok === "--target") {
323
+ targetFlag = requireFlagValue("--target", rest[i + 1]);
324
+ i += 1;
325
+ }
326
+ else if (tok.startsWith("--target=")) {
327
+ targetFlag = tok.slice("--target=".length);
328
+ }
329
+ else if (tok === "--prompt") {
330
+ promptFlag = requireFlagValue("--prompt", rest[i + 1]);
331
+ i += 1;
332
+ }
333
+ else if (tok.startsWith("--prompt=")) {
334
+ promptFlag = tok.slice("--prompt=".length);
335
+ }
336
+ else if (tok === "--persona") {
337
+ personaFlag = requireFlagValue("--persona", rest[i + 1]);
338
+ i += 1;
339
+ }
340
+ else if (tok.startsWith("--persona=")) {
341
+ personaFlag = tok.slice("--persona=".length);
342
+ }
343
+ else if (tok === "--catchup") {
344
+ catchupFlag = true;
345
+ }
346
+ else if (tok === "--no-catchup") {
347
+ catchupFlag = false;
348
+ }
349
+ else {
350
+ posArgs.push(tok);
351
+ }
352
+ }
353
+ const alias = (posArgs[0] ?? "").trim();
354
+ if (alias.length === 0) {
355
+ throw usageError("Missing schedule alias", `usage: /schedule ${sub} <alias> [--manual|--once|--rule <rule>] (--target <session> --prompt <text> | --step <server>.<tool> ['<json>'])`);
356
+ }
357
+ if (runFlag !== undefined && steps.length > 0) {
358
+ throw usageError("Conflicting macro flags", "Use either --run '<json-steps>' or repeatable --step flags, not both.");
359
+ }
360
+ const isMacro = runFlag !== undefined || steps.length > 0;
361
+ if (isMacro) {
362
+ if (promptFlag !== undefined || personaFlag !== undefined) {
363
+ throw usageError("Conflicting schedule kind", "Scripted macros (--run / --step) cannot be combined with --prompt or --persona.");
364
+ }
365
+ const runSteps = runFlag !== undefined ? parseRunJson(runFlag) : steps;
366
+ const rawRule = ruleFlag ?? posArgs[1];
367
+ return {
368
+ scopePrefix: "workspace",
369
+ sub,
370
+ rest,
371
+ actionName: `workspace.schedule.${sub}`,
372
+ params: {
373
+ alias,
374
+ ...(rawRule !== undefined && rawRule.length > 0 ? { rule: rawRule } : {}),
375
+ run: runSteps,
376
+ ...(targetFlag !== undefined && targetFlag.length > 0
377
+ ? { target: normalizeTarget(targetFlag) }
378
+ : {}),
379
+ ...(catchupFlag !== undefined ? { catchup: catchupFlag } : {}),
380
+ },
381
+ };
382
+ }
383
+ let sessionArg = targetFlag;
384
+ let rawRule = ruleFlag;
385
+ let promptText = promptFlag;
386
+ let cursor = 1;
387
+ if (sessionArg === undefined && cursor < posArgs.length) {
388
+ sessionArg = posArgs[cursor];
389
+ cursor += 1;
390
+ }
391
+ if (rawRule === undefined && cursor < posArgs.length) {
392
+ rawRule = posArgs[cursor];
393
+ cursor += 1;
394
+ }
395
+ if (promptText === undefined && cursor < posArgs.length) {
396
+ promptText = posArgs.slice(cursor).join(" ");
397
+ }
398
+ if (!sessionArg || sessionArg.trim().length === 0 || !promptText || promptText.trim().length === 0) {
399
+ throw usageError("Incomplete schedule definition", `usage: /schedule ${sub} <alias> <session> <rule> <prompt...> (or --target <session> --prompt <text> or --step <server>.<tool>)`);
400
+ }
401
+ return {
402
+ scopePrefix: "workspace",
403
+ sub,
404
+ rest,
405
+ actionName: `workspace.schedule.${sub}`,
406
+ params: {
407
+ alias,
408
+ ...(rawRule !== undefined && rawRule.trim().length > 0 ? { rule: rawRule.trim() } : {}),
409
+ target: normalizeTarget(sessionArg.trim()),
410
+ prompt: promptText.trim(),
411
+ ...(personaFlag !== undefined && personaFlag.length > 0 ? { persona: personaFlag } : {}),
412
+ ...(catchupFlag !== undefined ? { catchup: catchupFlag } : {}),
413
+ },
414
+ };
415
+ }
416
+ throw usageError("Unknown schedule subcommand", `Unknown schedule subcommand '${sub}'. Use list, show, inspect, discover, add, replace, run, done, reopen, enable, disable, or remove.`);
417
+ };
418
+ const summarizeStepChain = (steps) => {
419
+ const names = steps.filter(isRecord).map((step) => {
420
+ const srv = typeof step.server === "string" ? step.server : "?";
421
+ const tool = typeof step.tool === "string" ? step.tool : "?";
422
+ return `${srv}.${tool}`;
423
+ });
424
+ if (names.length === 0)
425
+ return "0 steps";
426
+ const chain = names.length <= 3 ? names.join(" → ") : `${names.slice(0, 3).join(" → ")} +${String(names.length - 3)}`;
427
+ return `${String(names.length)} ${names.length === 1 ? "step" : "steps"}: ${chain}`;
428
+ };
429
+ const summarizeScheduleAction = (def) => {
430
+ if (Array.isArray(def.run)) {
431
+ return summarizeStepChain(def.run);
432
+ }
433
+ const target = typeof def.target === "string" ? def.target : "";
434
+ const persona = typeof def.persona === "string" && def.persona.length > 0 ? ` (${def.persona})` : "";
435
+ const prompt = typeof def.prompt === "string" ? def.prompt.trim().replace(/\s+/gu, " ") : "";
436
+ const clipped = prompt.length > 60 ? `${prompt.slice(0, 59)}…` : prompt;
437
+ return [target.length > 0 ? `${target}${persona}` : "", clipped].filter((p) => p.length > 0).join(" · ");
438
+ };
439
+ const compactRuleLabel = (def, detail) => {
440
+ const rule = typeof detail.rule === "string"
441
+ ? detail.rule
442
+ : typeof def.rule === "string"
443
+ ? def.rule
444
+ : "manual";
445
+ const compactRule = rule.includes("\n")
446
+ ? (typeof detail.text === "string" && detail.text.length > 0 ? detail.text : rule.split(/\r?\n/u).join("; "))
447
+ : rule;
448
+ const next = typeof detail.next === "string" && detail.next.length > 0 ? ` (next ${detail.next})` : "";
449
+ return `${compactRule}${next}`;
450
+ };
451
+ /** {§acp-action-binding} Formats schedule definition rows for `list`, `add`, `replace`, `enable`, and `disable`. */
452
+ export const formatScheduleRows = (result) => {
453
+ const definitions = Array.isArray(result.definitions) ? result.definitions : [];
454
+ const footer = formatListPageFooter(result);
455
+ if (definitions.length === 0) {
456
+ return footer !== null ? `schedule: none\n${footer}\n` : "schedule: none\n";
457
+ }
458
+ const lines = [];
459
+ for (const rawItem of definitions) {
460
+ if (!isRecord(rawItem)) {
461
+ lines.push(String(rawItem));
462
+ continue;
463
+ }
464
+ const alias = typeof rawItem.alias === "string" ? rawItem.alias : "";
465
+ const state = typeof rawItem.state === "string" ? rawItem.state : "active";
466
+ const def = isRecord(rawItem.definition) ? rawItem.definition : {};
467
+ const detail = isRecord(rawItem.detail) ? rawItem.detail : {};
468
+ const isMacro = Array.isArray(def.run) || detail.kind === "run";
469
+ const kindLabel = isMacro ? "macro" : "prompt";
470
+ const statusLabel = typeof detail.status === "string"
471
+ ? `status=${detail.status}`
472
+ : state === "unavailable"
473
+ ? "status=fail"
474
+ : "";
475
+ const ruleSummary = compactRuleLabel(def, detail);
476
+ const actionSummary = summarizeScheduleAction(def);
477
+ const problemNote = state === "unavailable" && isRecord(rawItem.problem) && typeof rawItem.problem.detail === "string"
478
+ ? `— ${rawItem.problem.detail}`
479
+ : "";
480
+ const prov = isRecord(rawItem.provenance) ? rawItem.provenance : {};
481
+ const source = typeof prov.source === "string" && prov.source.length > 0 ? `source=${prov.source}` : "";
482
+ const parts = [alias, state, kindLabel, statusLabel, ruleSummary, actionSummary, problemNote, source]
483
+ .filter((p) => p.length > 0);
484
+ lines.push(parts.join(" "));
485
+ }
486
+ if (footer !== null) {
487
+ lines.push(footer);
488
+ }
489
+ return `${lines.join("\n")}\n`;
490
+ };
491
+ /** {§acp-action-binding} Formats a full single-alias schedule inspection view (`/schedule show|inspect <alias>`). */
492
+ export const formatScheduleInspect = (entry) => {
493
+ const alias = typeof entry.alias === "string" ? entry.alias : "";
494
+ const state = typeof entry.state === "string" ? entry.state : "active";
495
+ const origin = typeof entry.origin === "string" ? entry.origin : "workspace";
496
+ const def = isRecord(entry.definition) ? entry.definition : {};
497
+ const detail = isRecord(entry.detail) ? entry.detail : {};
498
+ const prov = isRecord(entry.provenance) ? entry.provenance : {};
499
+ const isMacro = Array.isArray(def.run) || detail.kind === "run";
500
+ const status = typeof detail.status === "string" ? detail.status : state === "unavailable" ? "fail" : "open";
501
+ const rule = typeof detail.rule === "string" ? detail.rule : typeof def.rule === "string" ? def.rule : "manual";
502
+ const ruleText = typeof detail.text === "string" && detail.text.length > 0 ? ` (${detail.text})` : "";
503
+ const lines = [
504
+ `alias: ${alias}`,
505
+ `kind: ${isMacro ? "macro (run)" : "prompt"}`,
506
+ `state: ${state} (status=${status}, origin=${origin})`,
507
+ `rule: ${rule.replace(/\r?\n/gu, " / ")}${ruleText}`,
508
+ ];
509
+ if (typeof detail.next === "string" && detail.next.length > 0) {
510
+ lines.push(`next: ${detail.next}`);
511
+ }
512
+ if (typeof detail.zone === "string" && detail.zone.length > 0) {
513
+ lines.push(`zone: ${detail.zone}`);
514
+ }
515
+ if (typeof detail.catchup === "boolean" && rule !== "manual" && rule !== "once") {
516
+ lines.push(`catchup: ${String(detail.catchup)}`);
517
+ }
518
+ if (typeof detail.lastFiredAt === "string" && detail.lastFiredAt.length > 0) {
519
+ lines.push(`lastFired: ${detail.lastFiredAt}`);
520
+ }
521
+ if (typeof detail.doneAt === "string" && detail.doneAt.length > 0) {
522
+ lines.push(`doneAt: ${detail.doneAt}`);
523
+ }
524
+ if (typeof detail.loopId === "number") {
525
+ lines.push(`loopId: ${String(detail.loopId)}`);
526
+ }
527
+ if (typeof prov.source === "string" && prov.source.length > 0) {
528
+ lines.push(`source: ${prov.source}`);
529
+ }
530
+ if (isRecord(entry.problem) && typeof entry.problem.detail === "string" && entry.problem.detail.length > 0) {
531
+ lines.push(`problem: ${entry.problem.detail}`);
532
+ }
533
+ if (isMacro && Array.isArray(def.run)) {
534
+ if (typeof def.target === "string" && def.target.length > 0) {
535
+ lines.push(`target: ${def.target}`);
536
+ }
537
+ lines.push(`steps (${String(def.run.length)}):`);
538
+ for (let i = 0; i < def.run.length; i += 1) {
539
+ const rawStep = def.run[i];
540
+ if (!isRecord(rawStep))
541
+ continue;
542
+ const srv = typeof rawStep.server === "string" ? rawStep.server : "?";
543
+ const tool = typeof rawStep.tool === "string" ? rawStep.tool : "?";
544
+ const argsStr = isRecord(rawStep.arguments) && Object.keys(rawStep.arguments).length > 0
545
+ ? ` ${JSON.stringify(rawStep.arguments)}`
546
+ : "";
547
+ const asideStr = typeof rawStep.aside === "string" && rawStep.aside.length > 0
548
+ ? ` (${rawStep.aside})`
549
+ : "";
550
+ lines.push(` #${String(i)} ${srv}.${tool}${argsStr}${asideStr}`);
551
+ }
552
+ }
553
+ else {
554
+ if (typeof def.target === "string" && def.target.length > 0) {
555
+ lines.push(`target: ${def.target}`);
556
+ }
557
+ if (typeof def.persona === "string" && def.persona.length > 0) {
558
+ lines.push(`persona: ${def.persona}`);
559
+ }
560
+ if (typeof def.prompt === "string" && def.prompt.length > 0) {
561
+ lines.push(`prompt: ${def.prompt}`);
562
+ }
563
+ }
564
+ return `${lines.join("\n")}\n`;
565
+ };
566
+ const parseStepReceipts = (raw) => {
567
+ if (!Array.isArray(raw))
568
+ return [];
569
+ const out = [];
570
+ for (const item of raw) {
571
+ if (!isRecord(item))
572
+ continue;
573
+ if (typeof item.server !== "string" || typeof item.tool !== "string" || typeof item.status !== "number")
574
+ continue;
575
+ out.push({
576
+ index: typeof item.index === "number" ? item.index : out.length,
577
+ server: item.server,
578
+ tool: item.tool,
579
+ status: item.status,
580
+ ...(typeof item.uri === "string" ? { uri: item.uri } : {}),
581
+ ...(typeof item.preview === "string" ? { preview: item.preview } : {}),
582
+ ...(isRecord(item.problem) ? { problem: item.problem } : {}),
583
+ });
584
+ }
585
+ return out;
586
+ };
587
+ /** {§acp-action-binding} Formats compact per-step macro receipts (`results[]`) for CLI, ACP, and Web. */
588
+ export const formatScheduleStepReceipts = (rawResults) => {
589
+ const receipts = parseStepReceipts(rawResults);
590
+ const lines = [];
591
+ for (const step of receipts) {
592
+ const uriPart = step.uri !== undefined && step.uri.length > 0 ? ` ${step.uri}` : "";
593
+ const rawPreview = step.preview?.trim() ?? "";
594
+ const previewLines = rawPreview.length > 0 ? rawPreview.split(/\r?\n/u) : [];
595
+ const inlinePreview = previewLines.length === 1 ? ` — ${previewLines[0]}` : "";
596
+ lines.push(` #${String(step.index)} ${step.server}.${step.tool} ${String(step.status)}${uriPart}${inlinePreview}`);
597
+ if (previewLines.length > 1) {
598
+ for (const pLine of previewLines) {
599
+ lines.push(` ${pLine}`);
600
+ }
601
+ }
602
+ if (step.problem !== undefined) {
603
+ const detail = typeof step.problem.detail === "string"
604
+ ? step.problem.detail
605
+ : typeof step.problem.title === "string"
606
+ ? step.problem.title
607
+ : "";
608
+ if (detail.length > 0) {
609
+ lines.push(` ! ${detail}`);
610
+ }
611
+ }
612
+ }
613
+ return lines;
614
+ };
615
+ export const formatScheduleRunResult = (fallbackAlias, result) => {
616
+ const alias = typeof result.alias === "string" && result.alias.length > 0 ? result.alias : fallbackAlias;
617
+ const status = typeof result.status === "string" ? result.status : "open";
618
+ const receipts = parseStepReceipts(result.results);
619
+ const meta = [];
620
+ if (receipts.length > 0) {
621
+ meta.push(`${String(receipts.length)} ${receipts.length === 1 ? "step" : "steps"}`);
622
+ }
623
+ if (typeof result.loopId === "number") {
624
+ meta.push(`loop ${String(result.loopId)}`);
625
+ }
626
+ if (typeof result.doneAt === "string" && result.doneAt.length > 0) {
627
+ meta.push(`done ${result.doneAt}`);
628
+ }
629
+ else if (typeof result.lastFiredAt === "string" && result.lastFiredAt.length > 0) {
630
+ meta.push(`fired ${result.lastFiredAt}`);
631
+ }
632
+ const header = meta.length > 0 ? `${alias} ${status} (${meta.join(" · ")})` : `${alias} ${status}`;
633
+ const stepLines = formatScheduleStepReceipts(receipts);
634
+ return stepLines.length > 0 ? `${header}\n${stepLines.join("\n")}` : header;
635
+ };
636
+ export const formatScheduleStatusResult = (fallbackAlias, result) => {
637
+ const alias = typeof result.alias === "string" && result.alias.length > 0 ? result.alias : fallbackAlias;
638
+ const status = typeof result.status === "string" ? result.status : "open";
639
+ const doneNote = typeof result.doneAt === "string" && result.doneAt.length > 0 ? ` (done ${result.doneAt})` : "";
640
+ return `${alias} ${status}${doneNote}`;
641
+ };
642
+ /**
643
+ * {§client-schedule-command} Extracts a structured `ProblemDetails` from a schedule usage or RPC failure,
644
+ * attaching `recovery: "/schedule reopen <alias>"` on `409 already-done` conflicts when absent.
645
+ */
646
+ export const extractScheduleProblem = (error, fallbackAlias) => {
647
+ let problem = Problems.fromError(error);
648
+ if (problem === null && isRecord(error) && isRecord(error.data)) {
649
+ const candidate = isRecord(error.data.problem) ? error.data.problem : error.data;
650
+ if (typeof candidate.type === "string"
651
+ && typeof candidate.title === "string"
652
+ && typeof candidate.status === "number"
653
+ && typeof candidate.detail === "string") {
654
+ problem = {
655
+ ...candidate,
656
+ type: candidate.type,
657
+ title: candidate.title,
658
+ status: candidate.status,
659
+ detail: candidate.detail,
660
+ };
661
+ }
662
+ }
663
+ if (problem === null)
664
+ return null;
665
+ if (problem.status === 409
666
+ && (problem.type.endsWith("/already-done") || /\balready[- ]done\b/iu.test(problem.detail))
667
+ && (typeof problem.recovery !== "string" || problem.recovery.length === 0)
668
+ && typeof fallbackAlias === "string"
669
+ && fallbackAlias.trim().length > 0) {
670
+ return {
671
+ ...problem,
672
+ recovery: `/schedule reopen ${fallbackAlias.trim()}`,
673
+ };
674
+ }
675
+ return problem;
676
+ };
677
+ //# sourceMappingURL=ScheduleCommand.js.map