@aicopycoders/exodus 2026.7.200-beta.9 → 2026.8.1200-beta.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 (40) hide show
  1. package/README.md +51 -0
  2. package/assets/docs/CLAUDE.md +2 -0
  3. package/assets/docs/PIPELINES.md +26 -0
  4. package/assets/skills/exodus/SKILL.md +5 -2
  5. package/assets/skills/exodus-meme/SKILL.md +44 -28
  6. package/assets/skills/exodus-winners/SKILL.md +29 -20
  7. package/assets/skills/exodus-workflow/SKILL.md +464 -63
  8. package/dist/bin/exodus.js +3 -0
  9. package/dist/commands/bank.d.ts +88 -0
  10. package/dist/commands/bank.js +346 -0
  11. package/dist/commands/browse.js +2 -1
  12. package/dist/commands/creative.js +2 -2
  13. package/dist/commands/genesis.js +16 -4
  14. package/dist/commands/keys.js +1 -0
  15. package/dist/commands/meme.js +9 -6
  16. package/dist/commands/primer.js +2 -1
  17. package/dist/commands/session.d.ts +55 -0
  18. package/dist/commands/session.js +202 -0
  19. package/dist/commands/status.js +4 -4
  20. package/dist/commands/swipe.js +4 -4
  21. package/dist/commands/template.js +2 -2
  22. package/dist/commands/update.d.ts +2 -0
  23. package/dist/commands/update.js +20 -0
  24. package/dist/commands/winners.js +13 -3
  25. package/dist/commands/workflow.d.ts +293 -8
  26. package/dist/commands/workflow.js +2442 -118
  27. package/dist/lib/client.d.ts +8 -1
  28. package/dist/lib/client.js +30 -6
  29. package/dist/lib/format.d.ts +7 -0
  30. package/dist/lib/format.js +52 -5
  31. package/dist/lib/intel-format.js +2 -1
  32. package/dist/lib/keys-sync.js +1 -0
  33. package/dist/lib/poll.js +7 -4
  34. package/dist/lib/route-support.d.ts +4 -0
  35. package/dist/lib/route-support.js +22 -0
  36. package/dist/lib/runStatus.d.ts +22 -0
  37. package/dist/lib/runStatus.js +139 -0
  38. package/dist/lib/workflowText.d.ts +3 -0
  39. package/dist/lib/workflowText.js +113 -0
  40. package/package.json +5 -2
@@ -1,7 +1,13 @@
1
1
  import fs from "node:fs";
2
- import { apiGet, apiPost } from "../lib/client.js";
3
- import { formatError } from "../lib/format.js";
2
+ import path from "node:path";
3
+ import nodePath from "node:path";
4
+ import { apiGet, apiGetText, apiPost, apiPostDashboard, getDashboardUrl, } from "../lib/client.js";
5
+ import { formatApiError } from "../lib/format.js";
4
6
  import { pollUntilDone } from "../lib/poll.js";
7
+ import { normalizeRunStatus, runStatusLabel, storedWorkflowStatusForms, workflowRunPresentation, RUN_STATUS_LABELS, TERMINAL_RUN_STATUSES, } from "../lib/runStatus.js";
8
+ import { workflowToYaml, parseWorkflowText } from "../lib/workflowText.js";
9
+ import { missingRouteLine } from "../lib/route-support.js";
10
+ import { getChannel } from "../lib/channel.js";
5
11
  export const helpText = `
6
12
  exodus workflow — List, describe, run, inspect, import, and export saved workflows
7
13
 
@@ -9,10 +15,27 @@ Usage:
9
15
  exodus workflow list [--json]
10
16
  exodus workflow describe <workflowId|name> [--json]
11
17
  exodus workflow bots [--category <cat>] [--slug <slug>] [--json]
12
- exodus workflow run <workflowId|name> [--input key=value ...] [--wait] [--json]
13
- exodus workflow status [--id <runId>] [--json]
14
- exodus workflow export <workflowId|name> [--out <file>]
18
+ exodus workflow templates [list] [--json]
19
+ exodus workflow templates export <key> [--out <file>] [--json]
20
+ exodus workflow schema [--kind <kind>] [--face <face>] [--json]
21
+ exodus workflow run <workflowId|name> [--fill <name>] [--input key=value ...] [--input <fileField>=<path> ...] [--terminal <nodeId> ...] [--rig-overrides <json|@file>] [--auto-approve] [--wait] [--out <dir>] [--json]
22
+ exodus workflow status [--id <runId>] [--out <dir>] [--json]
23
+ exodus workflow versions <workflowId|name> [--json]
24
+ exodus workflow export <workflowId|name> [--version <n>] [--out <file>] [--json]
25
+ exodus workflow validate <file> [--update <workflowId>] [--json]
15
26
  exodus workflow import <file> [--update <workflowId>] [--dry-run] [--json]
27
+ exodus workflow triggers <workflowId|name> [--json]
28
+ exodus workflow triggers <workflowId|name> enable <n> [--json]
29
+ exodus workflow triggers <workflowId|name> disable <n> [--json]
30
+ exodus workflow triggers <workflowId|name> fire [<n>] [--text "..."] [--rig-overrides <json|@file>] [--wait] [--json]
31
+ exodus workflow inbox [--json]
32
+ exodus workflow checkpoint <runId> [show] [--json]
33
+ exodus workflow checkpoint <runId> edit <n> [--text "..." | --file <path> | (stdin)] [--json]
34
+ exodus workflow checkpoint <runId> approve [--reject <n[,n..]>] [--wait] [--json]
35
+ exodus workflow checkpoint <runId> retry [--note "..."] [--wait] [--json]
36
+ exodus workflow checkpoint <runId> cancel [--reason "..."] [--json]
37
+ exodus workflow repair <runId> retry|skip|kill [--wait] [--json]
38
+ exodus workflow answer <runId> --slot key=value [--slot key=value ...] [--json]
16
39
 
17
40
  Flags:
18
41
  --json Machine-readable JSON output
@@ -22,31 +45,211 @@ Flags:
22
45
  --input key=@path loads the value from a file (path is
23
46
  resolved from the current directory); --input key=@@text
24
47
  keeps a leading "@" as a literal character.
25
- --wait Poll until the workflow run reaches a terminal status
48
+ FILE fields (an Asset Input — "workflow describe" shows
49
+ them as source "asset") take a local file path instead:
50
+ --input hero=./photos/hero.png. The CLI uploads the file
51
+ and sends the stored asset in its place; a leading "@"
52
+ is accepted and ignored. An http(s) URL is accepted too
53
+ (--input hero=https://example.com/hero.png) — the server
54
+ fetches and registers it at launch. Pass an asset id
55
+ from an earlier upload to reuse it. Accepted files:
56
+ image PNG, JPEG, WebP, GIF (≤15MB) · video MP4, MOV,
57
+ WebM (≤200MB) · audio MP3, M4A, WAV, OGG (≤50MB) ·
58
+ document PDF, TXT, MD, DOC, DOCX (≤25MB).
59
+ MULTI-CHOICE fields (describe tags them "multi-select")
60
+ take several picks in ONE value, comma-separated:
61
+ --input tone=casual,punchy.
62
+ --fill <name> (run) Launch from a saved fill — a named set of inputs
63
+ saved on THIS brand's copy of the workflow. Its values
64
+ become the run's inputs; any --input you also pass wins
65
+ for that one key, so a fill is a starting point, not a
66
+ lock. Names are exact (case-sensitive); an unknown one
67
+ is rejected before the run starts. Fills are created and
68
+ named in the dashboard's run dialog.
69
+ --terminal <nodeId> (run) Repeatable. Scope the run to the upstream closure
70
+ of these end node(s) — only nodes feeding a picked
71
+ terminal execute; the rest are recorded out-of-scope.
72
+ Omit to run the whole graph.
73
+ --rig-overrides <json> (run, triggers fire) Change what an Image Rig box fires
74
+ for THIS ONE run, without editing the saved workflow —
75
+ a different number of images, a different meme format,
76
+ a different model. Takes a JSON object keyed by the
77
+ box's node id, or @path to a .json file holding one:
78
+ --rig-overrides '{"rig_1":{"lines":{"line_1":{"count":3}}}}'
79
+ Add "confirmLargeRun": true beside "lines" to allow a
80
+ run over the brand's image safety cap — the same
81
+ acknowledgement the tick-box in the app asks for. A box
82
+ or line name the workflow doesn't have is refused
83
+ before anything runs, and the error names it. On
84
+ "triggers fire" it REPLACES the schedule's own
85
+ overrides for that one test fire.
86
+ --auto-approve (run) Deliberately unattended launch: every Checkpoint
87
+ box this run stops at is approved automatically, with
88
+ whatever it was holding left exactly as it is, and the
89
+ run record marks each stop as auto-approved so you can
90
+ see nobody looked. Default is to park and wait for a
91
+ person's verdict. This is a choice you make for ONE
92
+ launch — it is never a setting on the workflow itself.
93
+ --wait Poll until the workflow run reaches a terminal status.
94
+ (checkpoint retry) Re-runs the step feeding the
95
+ Checkpoint box and waits until its fresh output is
96
+ ready and the run parks again — that IS its finish
97
+ line; a redo never runs the workflow to completion.
26
98
  --id <runId> Workflow run id for status detail
27
- --out <file> Write export JSON to a file instead of stdout
28
- --update <workflowId> (import) Update this existing workflow in place instead
29
- of creating a new one. Sends the contract's updatedAt as
30
- an optimistic-concurrency guard — if it 409s, re-export
31
- the workflow, reapply edits, and import again.
32
- --dry-run Preview import (validate + resolve refs) without writing
99
+ --out <file> Write the export to a file instead of stdout
100
+ --out <dir> (run --wait / status --id) Save every delivered output
101
+ of the finished run into this directory (created if
102
+ missing) and print the paths — text as .md, storyboards
103
+ and frame sets as .json, images/video/audio downloaded.
104
+ Unfulfilled slots are reported, never written.
105
+ --version <n> (export) Export a saved historical version instead of the
106
+ current head. <n> is the real 1-based version id from
107
+ "workflow versions" (a positive integer). A version
108
+ export intentionally carries NO triggers/description —
109
+ those aren't versioned, so a rollback leaves them
110
+ unchanged; head exports remain the only place triggers
111
+ appear.
112
+ --json (export) Emit the legacy JSON contract body instead of
113
+ the default canonical YAML (escape hatch for tools that
114
+ still parse the old JSON export byte-for-byte)
115
+ --update <workflowId> (import/validate) Update this existing workflow in place
116
+ instead of creating a new one. Sends the contract's
117
+ updatedAt as an optimistic-concurrency guard — if it
118
+ 409s, re-export the workflow, reapply edits, and retry.
119
+ --dry-run Preview import (validate + resolve refs) without writing.
120
+ Same server-side check as "workflow validate <file>" —
121
+ use validate as the standalone front door.
122
+ --text "..." (triggers fire) The input an EVENT trigger's run carries.
123
+ Required for event triggers; rejected for cron triggers.
124
+ (checkpoint edit) The replacement copy for one output.
125
+ --file <path> (checkpoint edit) Load the replacement copy from a file.
126
+ --reason "..." (checkpoint cancel) Optional reason recorded on the
127
+ cancel.
128
+ --note "..." (checkpoint retry) Optional correction for the redo
129
+ ("make the hook punchier"). Steps that call a model
130
+ follow it on the re-run; deterministic steps only
131
+ record it on the run's review trail.
132
+ --reject <n[,n..]> (checkpoint approve) Only for a Checkpoint box that is
133
+ reviewing a Splitter fan-out item by item. Drops those
134
+ ITEM numbers (the "Item N of M" headings in the show
135
+ listing, 1-based) and approves the rest. Rejecting is
136
+ filtering, not failing — the run carries on with the
137
+ survivors. Rejecting every item is refused: cancel
138
+ instead.
139
+ --slot key=value (answer) Repeatable. One answer per pending slot.
140
+ --kind <kind> (schema) Print just one node kind's ports + config rules
141
+ --face <face> (schema) Print just one transform face's spec
33
142
 
34
143
  Examples:
35
144
  exodus workflow describe "Launch Flow"
36
145
  exodus workflow bots
37
146
  exodus workflow bots --category writing
38
147
  exodus workflow bots --slug new-hook-bot
148
+ exodus workflow templates
149
+ exodus workflow templates export complete-ad-set --out my.yaml
150
+ exodus workflow schema
151
+ exodus workflow schema --kind transform
152
+ exodus workflow schema --kind splitter
153
+ exodus workflow schema --kind collector
154
+ exodus workflow schema --kind checkpoint
155
+ exodus workflow schema --face collector
39
156
  exodus workflow run "Launch Flow" --input brief="new offer" --wait
40
157
  exodus workflow run "Launch Flow" --input brief=@brief.txt
158
+ exodus workflow run "Product Shots" --input hero=./photos/hero.png --wait
159
+ exodus workflow run "Product Shots" --input hero=https://example.com/hero.png
160
+ exodus workflow run "Launch Flow" --fill "Weekly promo" --wait
161
+ exodus workflow run "Launch Flow" --fill "Weekly promo" --input brief="new offer"
162
+ exodus workflow run "Launch Flow" --terminal bot-3 --terminal image-2
163
+ exodus workflow run "Launch Flow" --auto-approve --wait
164
+ exodus workflow run "Product Shots" --rig-overrides '{"rig_1":{"lines":{"line_1":{"count":3}}}}'
165
+ exodus workflow run "Product Shots" --rig-overrides @rig.json --wait
166
+ exodus workflow run "Launch Flow" --wait --out ./deliverables
41
167
  exodus workflow status --id wr_123
42
- exodus workflow export "Launch Flow" --out workflow.json
43
- exodus workflow import workflow.json --dry-run
168
+ exodus workflow status --id wr_123 --out ./deliverables
169
+ exodus workflow versions "Launch Flow"
170
+ exodus workflow export "Launch Flow" --out workflow.yaml
171
+ exodus workflow export "Launch Flow" --version 3 --out v3.yaml
172
+ exodus workflow export "Launch Flow" --json --out workflow.json
173
+ exodus workflow validate my.yaml
174
+ exodus workflow import workflow.yaml --dry-run
44
175
  exodus workflow import workflow.json --update wf_123
176
+ exodus workflow triggers "Winner Flywheel"
177
+ exodus workflow triggers "Winner Flywheel" enable 1
178
+ exodus workflow triggers "Winner Flywheel" fire 1 --text "new offer" --wait
179
+ exodus workflow inbox
180
+ exodus workflow checkpoint wr_123
181
+ exodus workflow checkpoint wr_123 edit 1 --text "tighter opener"
182
+ exodus workflow checkpoint wr_123 approve --wait
183
+ exodus workflow checkpoint wr_123 approve --reject 2,5 --wait
184
+ exodus workflow checkpoint wr_123 retry --note "make the hook punchier" --wait
185
+ exodus workflow checkpoint wr_123 cancel --reason "wrong direction"
186
+ exodus workflow repair wr_123 retry --wait
187
+ exodus workflow answer wr_123 --slot tone=casual --slot length=short
188
+
189
+ # Diff two saved versions:
190
+ exodus workflow export X --version 3 --out v3.yaml && exodus workflow export X --version 5 --out v5.yaml && diff v3.yaml v5.yaml
191
+ # Roll a workflow back to an earlier version:
192
+ exodus workflow export X --version 3 --out v3.yaml && exodus workflow import v3.yaml --update <id>
45
193
 
46
194
  Notes:
195
+ workflow describe prints the ENTRY CONTRACT — every input the workflow asks
196
+ for, whether it's required or optional, the shape it accepts (a dropdown and
197
+ its choices, a number, a true/false toggle; a plain text box shows no tag),
198
+ and the author's help text. Supply those keys with --input; a value the
199
+ contract can't accept is rejected before the run starts, naming the field.
200
+ It also prints the EXIT contract under "Delivers" — the named results a
201
+ finished run hands back, in the author's order: the slot's label, its key (the
202
+ name --out files and a webhook key off), what kind of thing it is (text /
203
+ structured data / file / set of files), and the author's note. A workflow with
204
+ no Output node says so plainly ("Delivers: nothing — no Output node."), and
205
+ "workflow run" repeats that as a warning before it spends the run. Against a
206
+ backend too old to report deliveries the section is omitted entirely.
207
+ "workflow run --fill <name>" launches from a saved fill instead of typing the
208
+ inputs again — the fill's values fill the contract, and any --input you pass
209
+ alongside it overrides just that key.
210
+ Cold-start is a template, not a blank file: "workflow templates" lists the
211
+ starters (incl. Winner Flywheel), "workflow templates export <key> --out f.yaml"
212
+ writes the server-rendered YAML verbatim — edit it, then "workflow import f.yaml".
213
+ "workflow schema" prints the LIVE graph vocabulary (node kinds, ports, config
214
+ rules, transform faces, collector policy, wiring rules) from the backend you're
215
+ deployed against, so what you author matches what will validate; --kind/--face
216
+ narrow it, --json is the machine payload. "workflow validate <file>" checks a
217
+ file against the live backend (it IS import --dry-run under its own door).
218
+ "workflow run --rig-overrides" re-aims an Image Rig box for ONE run without
219
+ touching the saved workflow: how many images a line fires, which meme format,
220
+ which model. Node ids and line keys come from "workflow export" (or the box's
221
+ panel in the app); anything you name that isn't there stops the launch and the
222
+ message says which key was wrong. A trigger can carry the same payload in its
223
+ YAML ("imageRigOverrides:" beside its schedule), so a Monday schedule and a
224
+ Friday one can fire the same workflow at different sizes.
225
+ workflow triggers are addressed by 1-based position — a trigger carries no id,
226
+ so the CLI reads the live list from the export contract and sends a fingerprint
227
+ of the trigger's fields as the guard; a concurrent edit fails loud rather than
228
+ flipping the wrong trigger. Add or remove triggers by editing the YAML export.
229
+ workflow export writes canonical YAML by default (human-diffable, key order
230
+ fixed so equal workflows dump byte-identically); pass --json for the legacy
231
+ JSON contract body. workflow import accepts either a YAML export or a legacy
232
+ JSON file — same downstream, so YAML files work against the deployed API.
233
+ workflow versions lists a workflow's saved history newest-first (up to 50);
234
+ version numbers are real 1-based ids you pass to export --version. A version
235
+ export intentionally carries NO triggers/description (they aren't versioned),
236
+ so rolling back with import --update leaves them unchanged — head exports
237
+ remain the only place triggers appear.
47
238
  workflow bots --json emits the FULL catalog response verbatim (--category /
48
239
  --slug filters are ignored in that mode). workflow bots --slug <slug> --json
49
240
  emits just that one bot's catalog JSON.
241
+ workflow inbox lists every run parked waiting on you, badged by park kind
242
+ (checkpoint/repair/slots/gate/legacy) and how it started (bg / trig:<event>).
243
+ A run parked at a Checkpoint box is resolved with the "checkpoint" verbs: show
244
+ what is waiting there, edit one output in place (edit 1 --text ...), approve
245
+ (resume), retry (re-run the step feeding the box), or cancel. A Checkpoint is
246
+ its own box on the canvas, sitting on a wire between two steps, so the diagram
247
+ shows exactly where a run will stop. A require-all collector that stalled
248
+ on a dead input is a "repair" park — retry it, skip the dead input, or kill the
249
+ run. A nested sub-workflow waiting on inputs is a "slots" park — answer it with
250
+ repeatable --slot key=value flags (run "answer" with no --slot to list the slot
251
+ ids it wants). The "gate" verbs retired in 2.0 along with the Gate node — the
252
+ command now prints a pointer at "checkpoint" and exits 1.
50
253
  `.trim();
51
254
  const LIST_PATH = "/api/v2/workflows";
52
255
  const RUN_PATH = "/api/v2/workflows/run";
@@ -54,21 +257,113 @@ const STATUS_PATH = "/api/v2/workflow";
54
257
  const EXPORT_PATH = "/api/v2/workflows/export";
55
258
  const IMPORT_PATH = "/api/v2/workflows/import";
56
259
  const DESCRIBE_PATH = "/api/v2/workflows/describe";
260
+ const ASSET_UPLOAD_URL_PATH = "/api/v2/workflows/asset-upload-url";
261
+ const ASSETS_PATH = "/api/v2/workflows/assets";
57
262
  const CATALOG_PATH = "/api/v2/workflows/catalog";
58
- const VALUE_FLAGS = new Set(["id", "input", "out", "category", "slug", "update"]);
263
+ const TRIGGERS_SET_ENABLED_PATH = "/api/v2/workflows/triggers/set-enabled";
264
+ const TRIGGERS_FIRE_PATH = "/api/v2/workflows/triggers/fire";
265
+ const TEMPLATES_PATH = "/api/v2/workflows/templates";
266
+ const SCHEMA_PATH = "/api/v2/workflows/schema";
267
+ const VERSIONS_PATH = "/api/v2/workflows/versions";
268
+ const VERSIONS_CAP = 50;
269
+ const INBOX_PATH = "/api/v2/workflow/inbox";
270
+ const APPROVE_PATH = "/api/v2/workflow/approve";
271
+ const CANCEL_PATH = "/api/v2/workflow/cancel";
272
+ const ANSWER_PATH = "/api/v2/workflow/answer";
273
+ const REPAIR_RETRY_PATH = "/api/v2/workflow/repair/retry";
274
+ const REPAIR_SKIP_PATH = "/api/v2/workflow/repair/skip";
275
+ const CHECKPOINT_RETRY_PATH = "/api/v2/workflow/checkpoint/retry";
276
+ const CHECKPOINT_EDIT_PATH = "/api/v2/workflow/checkpoint/edit";
277
+ const CHECKPOINT_RESOLVE_ITEMS_PATH = "/api/v2/workflow/checkpoint/resolve-items";
278
+ const RUN_PAGE_PREFIX = "/runs/";
279
+ const VALUE_FLAGS = new Set([
280
+ "id",
281
+ "input",
282
+ "out",
283
+ "category",
284
+ "slug",
285
+ "update",
286
+ "terminal",
287
+ "fill",
288
+ "text",
289
+ "kind",
290
+ "face",
291
+ "version",
292
+ "file",
293
+ "reason",
294
+ "slot",
295
+ "reject",
296
+ "rig-overrides",
297
+ "note",
298
+ ]);
299
+ function defaultMkdirp(dir) {
300
+ fs.mkdirSync(dir, { recursive: true });
301
+ }
302
+ async function defaultDownloadToFile(url, path) {
303
+ const res = await fetch(url);
304
+ if (!res.ok)
305
+ throw new Error(`download failed with HTTP ${res.status}`);
306
+ const buf = Buffer.from(await res.arrayBuffer());
307
+ fs.writeFileSync(path, buf);
308
+ }
59
309
  const defaultDeps = {
60
310
  get: (path) => apiGet(path),
311
+ getText: (path) => apiGetText(path),
61
312
  post: (path, body) => apiPost(path, body),
62
313
  readFile: (path) => fs.readFileSync(path, "utf-8"),
63
314
  writeFile: (path, text) => fs.writeFileSync(path, text, "utf-8"),
64
315
  poll: (opts) => pollUntilDone(opts),
316
+ mkdirp: defaultMkdirp,
317
+ downloadToFile: defaultDownloadToFile,
318
+ postDashboard: (path, body, opts) => apiPostDashboard(path, body, opts),
319
+ dashboardUrl: getDashboardUrl(),
320
+ statFile: (filePath) => {
321
+ try {
322
+ const stat = fs.statSync(filePath);
323
+ return stat.isFile() ? { size: stat.size } : null;
324
+ }
325
+ catch {
326
+ return null;
327
+ }
328
+ },
329
+ readFileBytes: (filePath) => fs.readFileSync(filePath),
330
+ uploadBytes: async (uploadUrl, contentType, bytes) => {
331
+ const res = await fetch(uploadUrl, {
332
+ method: "POST",
333
+ headers: { "Content-Type": contentType },
334
+ body: new Blob([bytes]),
335
+ });
336
+ if (!res.ok) {
337
+ const body = await res.text().catch(() => "");
338
+ return { ok: false, status: res.status, body };
339
+ }
340
+ const parsed = (await res.json().catch(() => ({})));
341
+ return { ok: true, status: res.status, storageId: parsed.storageId };
342
+ },
65
343
  };
66
344
  function asErrorResult(res, json) {
67
345
  return {
68
346
  code: 1,
69
347
  lines: json
70
348
  ? [JSON.stringify({ ok: false, status: res.status, data: res.data })]
71
- : [formatError(res)],
349
+ : [formatApiError(res)],
350
+ };
351
+ }
352
+ function resolveIdErrorResult(e, json) {
353
+ if (e instanceof WorkflowResolveError) {
354
+ return {
355
+ code: 1,
356
+ lines: json
357
+ ? [JSON.stringify({ ok: false, status: e.status, data: e.data })]
358
+ : [e.message],
359
+ };
360
+ }
361
+ const message = e instanceof Error ? e.message : String(e);
362
+ return {
363
+ code: 1,
364
+ lines: json
365
+ ? [JSON.stringify({ ok: false, status: 0, data: { error: { message } } })]
366
+ : [message],
72
367
  };
73
368
  }
74
369
  function isRecord(value) {
@@ -113,12 +408,73 @@ function outputLines(output) {
113
408
  if (output.type === "primer") {
114
409
  return [` primer:${output.primerKind}: ${truncateText(output.text)}`];
115
410
  }
116
- return [` image: ${output.imageUrl ?? output.storageId}`];
411
+ if (output.type === "image") {
412
+ const url = output.imageUrl ?? output.storageId;
413
+ return url ? [` image: ${url}`] : [];
414
+ }
415
+ return [];
117
416
  }
118
- function progressLine(node) {
417
+ function progressLine(node, parked = false) {
119
418
  const err = node.error ? ` — error: ${node.error}` : "";
419
+ if (parked) {
420
+ return ` ⏸ ${node.nodeId} (${node.kind}) awaiting approval`;
421
+ }
120
422
  return ` ${statusIcon(node.status)} ${node.nodeId} (${node.kind}) ${node.status}${err}`;
121
423
  }
424
+ function gateParkedNodeId(status, pauseReason, pausedNodeId) {
425
+ if (!status || normalizeRunStatus(status) !== "awaiting-approval")
426
+ return undefined;
427
+ if (pauseReason === "taste" || pauseReason === "checkpoint" || pauseReason === undefined) {
428
+ return pausedNodeId;
429
+ }
430
+ return undefined;
431
+ }
432
+ function runVerdict(run) {
433
+ const presented = workflowRunPresentation(run.status, run.pauseReason);
434
+ if ((presented.status === "succeeded" || presented.status === "succeeded-with-warnings") &&
435
+ (run.counts?.failed ?? 0) > 0 &&
436
+ run.deliveries !== undefined &&
437
+ run.deliveries.length > 0 &&
438
+ !run.deliveries.some((d) => d.status === "delivered")) {
439
+ return `${RUN_STATUS_LABELS.failed} — nothing delivered`;
440
+ }
441
+ return presented.detail ? `${presented.label} — ${presented.detail}` : presented.label;
442
+ }
443
+ const RETIRED_GATE_VERB_POINTER = "The Gate node retired in 2.0 — runs now pause at a Checkpoint box on the canvas. " +
444
+ "Use: exodus workflow checkpoint <runId> [approve|edit|retry|cancel]";
445
+ export function formatPauseNotice(pauseReason, runId, dashboardUrl) {
446
+ if (!pauseReason) {
447
+ return [
448
+ " ⏸ paused at the cost gate — approve or edit the storyboard in the web app to continue.",
449
+ ];
450
+ }
451
+ if (pauseReason === "call") {
452
+ return [" ⏸ waiting on a child workflow run — it resumes on its own."];
453
+ }
454
+ if (pauseReason === "checkpoint") {
455
+ return [
456
+ " ⏸ paused at a checkpoint — what's flowing through it is waiting on your approval.",
457
+ ` Resolve here: exodus workflow checkpoint ${runId}`,
458
+ ` Or in the app: ${dashboardUrl}${RUN_PAGE_PREFIX}${runId}`,
459
+ ];
460
+ }
461
+ if (pauseReason === "taste") {
462
+ return [
463
+ " ⏸ paused at a Gate box, which retired in 2.0. Approvals now happen at a Checkpoint box.",
464
+ ` Cancel it here: exodus workflow checkpoint ${runId} cancel`,
465
+ ` Or in the app: ${dashboardUrl}${RUN_PAGE_PREFIX}${runId}`,
466
+ " Then run the workflow again.",
467
+ ];
468
+ }
469
+ const resolveVerb = pauseReason === "repair"
470
+ ? `exodus workflow repair ${runId} retry|skip|kill`
471
+ : `exodus workflow answer ${runId} --slot key=value`;
472
+ return [
473
+ " ⏸ paused for review — waiting on you.",
474
+ ` Resolve here: ${resolveVerb}`,
475
+ ` Or in the app: ${dashboardUrl}${RUN_PAGE_PREFIX}${runId}`,
476
+ ];
477
+ }
122
478
  function expandInputValue(key, value, readFile) {
123
479
  if (value.startsWith("@@"))
124
480
  return value.slice(1);
@@ -140,7 +496,14 @@ function expandInputValue(key, value, readFile) {
140
496
  }
141
497
  return value;
142
498
  }
143
- export function parseInputFlags(args, readFile) {
499
+ function normalizeMultiValue(value) {
500
+ return value
501
+ .split(",")
502
+ .map((p) => p.trim())
503
+ .filter((p) => p.length > 0)
504
+ .join(", ");
505
+ }
506
+ export function parseRawInputFlags(args) {
144
507
  const inputs = {};
145
508
  for (let i = 0; i < args.length; i++) {
146
509
  const arg = args[i];
@@ -163,10 +526,425 @@ export function parseInputFlags(args, readFile) {
163
526
  const key = raw.slice(0, eq).trim();
164
527
  if (!key)
165
528
  throw new Error(`--input must include a key (got "${raw}")`);
166
- inputs[key] = expandInputValue(key, raw.slice(eq + 1), readFile);
529
+ inputs[key] = raw.slice(eq + 1);
530
+ }
531
+ return inputs;
532
+ }
533
+ export function parseInputFlags(args, readFile) {
534
+ const inputs = parseRawInputFlags(args);
535
+ for (const [key, value] of Object.entries(inputs)) {
536
+ inputs[key] = expandInputValue(key, value, readFile);
167
537
  }
168
538
  return inputs;
169
539
  }
540
+ const MB = 1024 * 1024;
541
+ export const ASSET_UPLOAD_POLICY = {
542
+ image: {
543
+ mimeByExtension: {
544
+ ".png": "image/png",
545
+ ".jpg": "image/jpeg",
546
+ ".jpeg": "image/jpeg",
547
+ ".webp": "image/webp",
548
+ ".gif": "image/gif",
549
+ },
550
+ maxBytes: 15 * MB,
551
+ accepts: "PNG, JPEG, WebP, GIF",
552
+ },
553
+ video: {
554
+ mimeByExtension: {
555
+ ".mp4": "video/mp4",
556
+ ".m4v": "video/mp4",
557
+ ".mov": "video/quicktime",
558
+ ".webm": "video/webm",
559
+ },
560
+ maxBytes: 200 * MB,
561
+ accepts: "MP4, MOV, WebM",
562
+ },
563
+ audio: {
564
+ mimeByExtension: {
565
+ ".mp3": "audio/mpeg",
566
+ ".m4a": "audio/mp4",
567
+ ".wav": "audio/wav",
568
+ ".ogg": "audio/ogg",
569
+ },
570
+ maxBytes: 50 * MB,
571
+ accepts: "MP3, M4A, WAV, OGG",
572
+ },
573
+ document: {
574
+ mimeByExtension: {
575
+ ".pdf": "application/pdf",
576
+ ".txt": "text/plain",
577
+ ".md": "text/markdown",
578
+ ".doc": "application/msword",
579
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
580
+ },
581
+ maxBytes: 25 * MB,
582
+ accepts: "PDF, TXT, Markdown, DOC, DOCX",
583
+ },
584
+ };
585
+ const MEDIA_FAMILIES = ["image", "video", "audio", "document"];
586
+ function sizeLabel(bytes) {
587
+ return `${(bytes / MB).toFixed(1)}MB`;
588
+ }
589
+ function capLabel(bytes) {
590
+ return `${Math.round(bytes / MB)}MB`;
591
+ }
592
+ function assetMimeFor(filePath, assetType) {
593
+ const ext = path.extname(filePath).toLowerCase();
594
+ if (!ext)
595
+ return null;
596
+ for (const family of assetType ? [assetType] : MEDIA_FAMILIES) {
597
+ const mime = ASSET_UPLOAD_POLICY[family].mimeByExtension[ext];
598
+ if (mime)
599
+ return { mime, family };
600
+ }
601
+ return null;
602
+ }
603
+ function acceptedLabel(assetType) {
604
+ if (assetType) {
605
+ const policy = ASSET_UPLOAD_POLICY[assetType];
606
+ return `${assetType} files (${policy.accepts}, up to ${capLabel(policy.maxBytes)})`;
607
+ }
608
+ return MEDIA_FAMILIES.map((family) => `${family} (${ASSET_UPLOAD_POLICY[family].accepts})`).join(", ");
609
+ }
610
+ function looksLikePath(value) {
611
+ if (value.includes("/") || value.includes("\\"))
612
+ return true;
613
+ if (value.startsWith("~"))
614
+ return true;
615
+ return /\.[A-Za-z0-9]{1,8}$/.test(value);
616
+ }
617
+ function planAssetUpload(field, filePath, size, assetType, deps) {
618
+ const name = path.basename(filePath);
619
+ const picked = assetMimeFor(filePath, assetType);
620
+ if (!picked) {
621
+ throw new Error(`--input ${field}: can't tell what kind of file "${name}" is — ${field} takes ${acceptedLabel(assetType)}`);
622
+ }
623
+ const { maxBytes } = ASSET_UPLOAD_POLICY[picked.family];
624
+ if (size > maxBytes) {
625
+ throw new Error(`--input ${field}: "${name}" is ${sizeLabel(size)} — over the ${capLabel(maxBytes)} limit for ${picked.family} uploads`);
626
+ }
627
+ if (!deps.readFileBytes || !deps.uploadBytes) {
628
+ throw new Error(`--input ${field}: cannot upload files here (no file access)`);
629
+ }
630
+ return { field, filePath, name, size, mime: picked.mime, family: picked.family };
631
+ }
632
+ async function pushAssetFile(plan, deps) {
633
+ const { field, name } = plan;
634
+ const mint = await deps.post(ASSET_UPLOAD_URL_PATH, {});
635
+ if (!mint.ok) {
636
+ throw new Error(missingRouteLine(mint, "workflow file inputs") ?? formatApiError(mint));
637
+ }
638
+ const minted = mint.data;
639
+ if (!minted.uploadUrl) {
640
+ throw new Error(`--input ${field}: the server did not return an upload URL for "${name}"`);
641
+ }
642
+ if (!minted.receiptId) {
643
+ throw new Error(`--input ${field}: the server did not return an upload receipt for "${name}"`);
644
+ }
645
+ let bytes;
646
+ try {
647
+ bytes = deps.readFileBytes(plan.filePath);
648
+ }
649
+ catch (e) {
650
+ const msg = e instanceof Error ? e.message : String(e);
651
+ throw new Error(`--input ${field}: could not read file "${plan.filePath}": ${msg}`);
652
+ }
653
+ const put = await deps.uploadBytes(minted.uploadUrl, plan.mime, bytes);
654
+ if (!put.ok || !put.storageId) {
655
+ const detail = put.body ? `: ${put.body.slice(0, 200)}` : "";
656
+ throw new Error(`--input ${field}: upload of "${name}" failed (HTTP ${put.status})${detail}`);
657
+ }
658
+ const registered = await deps.post(ASSETS_PATH, {
659
+ storageId: put.storageId,
660
+ receiptId: minted.receiptId,
661
+ filename: name,
662
+ });
663
+ if (!registered.ok) {
664
+ throw new Error(missingRouteLine(registered, "workflow file inputs") ?? formatApiError(registered));
665
+ }
666
+ const data = registered.data;
667
+ if (!data.assetId) {
668
+ throw new Error(`--input ${field}: the server did not return an asset id for "${name}"`);
669
+ }
670
+ return { assetId: data.assetId, mediaType: data.mediaType ?? plan.family };
671
+ }
672
+ function formatInputProblems(problems) {
673
+ if (problems.length === 1)
674
+ return problems[0];
675
+ return [
676
+ `${problems.length} of the --input values can't be used:`,
677
+ ...problems.map((line) => ` ${line}`),
678
+ ].join("\n");
679
+ }
680
+ function withReusableAssetIds(message, done) {
681
+ if (done.length === 0)
682
+ return message;
683
+ const flags = done.map((d) => `--input ${d.field}=${d.assetId}`).join(" ");
684
+ return (`${message}\n` +
685
+ `These files did upload — pass their ids to skip re-uploading them: ${flags}`);
686
+ }
687
+ function looksLikeFileArgument(value, deps) {
688
+ if (value.startsWith("@@"))
689
+ return false;
690
+ if (value.startsWith("@"))
691
+ return true;
692
+ if ((deps.statFile?.(value) ?? null) !== null)
693
+ return true;
694
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value))
695
+ return false;
696
+ if (/\s/.test(value))
697
+ return false;
698
+ return looksLikePath(value);
699
+ }
700
+ export const NO_DELIVERIES_WARNING = "Warning: this workflow has no Output node — the run will finish with no named " +
701
+ "deliveries (nothing for --out to save, and nothing to send to a webhook).";
702
+ export function noDeliveriesWarning(described) {
703
+ if (!isRecord(described))
704
+ return undefined;
705
+ const deliveries = described["deliveries"];
706
+ if (Array.isArray(deliveries)) {
707
+ return deliveries.length === 0 ? NO_DELIVERIES_WARNING : undefined;
708
+ }
709
+ return undefined;
710
+ }
711
+ export function serverWarningsToPrint(serverWarnings, alreadyPrinted) {
712
+ if (!Array.isArray(serverWarnings))
713
+ return [];
714
+ const key = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
715
+ const printedKeys = new Set(alreadyPrinted.map(key));
716
+ const saidNoDeliveries = alreadyPrinted.includes(NO_DELIVERIES_WARNING);
717
+ const out = [];
718
+ for (const raw of serverWarnings) {
719
+ if (typeof raw !== "string")
720
+ continue;
721
+ const text = raw.trim();
722
+ if (text === "")
723
+ continue;
724
+ const k = key(text);
725
+ if (printedKeys.has(k))
726
+ continue;
727
+ if (saidNoDeliveries && (k.includes("no output node") || k.includes("no named deliver"))) {
728
+ continue;
729
+ }
730
+ printedKeys.add(k);
731
+ out.push(text);
732
+ }
733
+ return out;
734
+ }
735
+ async function prepareRunInputs(workflowId, raw, deps, note, scoped) {
736
+ const described = await deps.get(`${DESCRIBE_PATH}?id=${encodeURIComponent(workflowId)}`);
737
+ if (!described.ok) {
738
+ const fileish = Object.keys(raw).filter((key) => looksLikeFileArgument(raw[key], deps));
739
+ if (fileish.length > 0) {
740
+ const reason = formatApiError(described).split("\n")[0];
741
+ throw new Error(`--input ${fileish.join(", ")}: couldn't confirm this workflow's inputs ` +
742
+ `(describe failed: ${reason}) — retry, or pass an already-uploaded asset id ` +
743
+ `instead of a file path.`);
744
+ }
745
+ const text = {};
746
+ for (const [key, value] of Object.entries(raw)) {
747
+ text[key] = expandInputValue(key, value, deps.readFile);
748
+ }
749
+ return { inputs: text, warnings: [] };
750
+ }
751
+ const warnings = [];
752
+ const noDeliveries = noDeliveriesWarning(described.data);
753
+ if (noDeliveries)
754
+ warnings.push(noDeliveries);
755
+ const descriptors = described.data.inputs ?? [];
756
+ const assetFields = new Map();
757
+ const multiFields = new Set();
758
+ for (const descriptor of descriptors) {
759
+ if (descriptor?.source === "asset")
760
+ assetFields.set(descriptor.fieldName, descriptor);
761
+ if (descriptor?.type === "multi-select")
762
+ multiFields.add(descriptor.fieldName);
763
+ }
764
+ if (!scoped) {
765
+ const missing = [...assetFields.values()].filter((d) => d.required && (raw[d.fieldName] ?? "").trim() === "");
766
+ if (missing.length > 0) {
767
+ const names = missing.map((d) => d.fieldName).join(", ");
768
+ const first = missing[0];
769
+ throw new Error(`Missing required file input(s): ${names}. Pass each one as a local file ` +
770
+ `or a URL — e.g. --input ${first.fieldName}=./path/to/file or ` +
771
+ `--input ${first.fieldName}=https://…` +
772
+ (first.assetType ? ` (${acceptedLabel(first.assetType)})` : ""));
773
+ }
774
+ }
775
+ const prepared = {};
776
+ const planned = [];
777
+ const problems = [];
778
+ for (const [key, value] of Object.entries(raw)) {
779
+ const descriptor = assetFields.get(key);
780
+ if (!descriptor) {
781
+ try {
782
+ const expanded = expandInputValue(key, value, deps.readFile);
783
+ prepared[key] = multiFields.has(key)
784
+ ? normalizeMultiValue(expanded)
785
+ : expanded;
786
+ }
787
+ catch (e) {
788
+ problems.push(e instanceof Error ? e.message : String(e));
789
+ }
790
+ continue;
791
+ }
792
+ if (/^https?:\/\//i.test(value)) {
793
+ prepared[key] = value;
794
+ continue;
795
+ }
796
+ const hinted = value.startsWith("@");
797
+ const candidate = hinted ? value.slice(1) : value;
798
+ const stat = deps.statFile?.(candidate) ?? null;
799
+ if (!stat) {
800
+ if (hinted || looksLikePath(candidate)) {
801
+ problems.push(`--input ${key}: file not found: ${candidate}`);
802
+ continue;
803
+ }
804
+ prepared[key] = value;
805
+ continue;
806
+ }
807
+ try {
808
+ planned.push(planAssetUpload(key, candidate, stat.size, descriptor.assetType, deps));
809
+ }
810
+ catch (e) {
811
+ problems.push(e instanceof Error ? e.message : String(e));
812
+ }
813
+ }
814
+ if (problems.length > 0)
815
+ throw new Error(formatInputProblems(problems));
816
+ const done = [];
817
+ for (const plan of planned) {
818
+ let uploaded;
819
+ try {
820
+ uploaded = await pushAssetFile(plan, deps);
821
+ }
822
+ catch (e) {
823
+ const message = e instanceof Error ? e.message : String(e);
824
+ throw new Error(withReusableAssetIds(message, done));
825
+ }
826
+ note(` uploaded ${plan.name} → ${plan.field} (${uploaded.mediaType}, ${sizeLabel(plan.size)})`);
827
+ prepared[plan.field] = uploaded.assetId;
828
+ done.push({ field: plan.field, assetId: uploaded.assetId });
829
+ }
830
+ return { inputs: prepared, warnings };
831
+ }
832
+ export function parseTerminalFlags(args) {
833
+ const ids = [];
834
+ for (let i = 0; i < args.length; i++) {
835
+ const arg = args[i];
836
+ let raw;
837
+ if (arg === "--terminal") {
838
+ raw = args[i + 1];
839
+ i++;
840
+ }
841
+ else if (arg.startsWith("--terminal=")) {
842
+ raw = arg.slice("--terminal=".length);
843
+ }
844
+ else {
845
+ continue;
846
+ }
847
+ if (raw === undefined)
848
+ throw new Error("--terminal requires a node id");
849
+ const id = raw.trim();
850
+ if (!id)
851
+ throw new Error("--terminal requires a node id");
852
+ ids.push(id);
853
+ }
854
+ return ids;
855
+ }
856
+ export function parseAutoApproveFlag(args) {
857
+ for (const arg of args) {
858
+ if (arg === "--auto-approve")
859
+ return true;
860
+ if (arg.startsWith("--auto-approve=")) {
861
+ throw new Error("--auto-approve takes no value — pass it bare");
862
+ }
863
+ }
864
+ return false;
865
+ }
866
+ export function parseRigOverridesFlag(args, readFile) {
867
+ let raw;
868
+ for (let i = 0; i < args.length; i++) {
869
+ const arg = args[i];
870
+ let value;
871
+ if (arg === "--rig-overrides") {
872
+ value = args[i + 1];
873
+ i++;
874
+ }
875
+ else if (arg.startsWith("--rig-overrides=")) {
876
+ value = arg.slice("--rig-overrides=".length);
877
+ }
878
+ else {
879
+ continue;
880
+ }
881
+ if (value === undefined || value.startsWith("--")) {
882
+ throw new Error("--rig-overrides requires JSON or @path/to/file.json");
883
+ }
884
+ raw = value;
885
+ }
886
+ if (raw === undefined)
887
+ return undefined;
888
+ let text = raw.trim();
889
+ if (!text)
890
+ throw new Error("--rig-overrides requires JSON or @path/to/file.json");
891
+ if (text.startsWith("@@")) {
892
+ text = text.slice(1);
893
+ }
894
+ else if (text.startsWith("@")) {
895
+ const filePath = text.slice(1);
896
+ if (!filePath) {
897
+ throw new Error("--rig-overrides @<file> needs a file path after \"@\"");
898
+ }
899
+ if (!readFile) {
900
+ throw new Error(`--rig-overrides: cannot load @${filePath} here (no file access)`);
901
+ }
902
+ try {
903
+ text = readFile(filePath);
904
+ }
905
+ catch (e) {
906
+ const msg = e instanceof Error ? e.message : String(e);
907
+ throw new Error(`--rig-overrides: could not read file "${filePath}": ${msg}`);
908
+ }
909
+ }
910
+ let parsed;
911
+ try {
912
+ parsed = JSON.parse(text);
913
+ }
914
+ catch (e) {
915
+ const msg = e instanceof Error ? e.message : String(e);
916
+ throw new Error(`--rig-overrides is not valid JSON: ${msg}`);
917
+ }
918
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
919
+ throw new Error("--rig-overrides must be a JSON object keyed by Image Rig node id, e.g. '{\"rig_1\":{\"lines\":{\"line_1\":{\"count\":3}}}}'");
920
+ }
921
+ return parsed;
922
+ }
923
+ export function parseFillFlag(args) {
924
+ let name;
925
+ for (let i = 0; i < args.length; i++) {
926
+ const arg = args[i];
927
+ let raw;
928
+ if (arg === "--fill") {
929
+ raw = args[i + 1];
930
+ i++;
931
+ }
932
+ else if (arg.startsWith("--fill=")) {
933
+ raw = arg.slice("--fill=".length);
934
+ }
935
+ else {
936
+ continue;
937
+ }
938
+ if (raw === undefined || raw.startsWith("--")) {
939
+ throw new Error("--fill requires a saved fill's name");
940
+ }
941
+ const trimmed = raw.trim();
942
+ if (!trimmed)
943
+ throw new Error("--fill requires a saved fill's name");
944
+ name = trimmed;
945
+ }
946
+ return name;
947
+ }
170
948
  export function formatWorkflowList(workflows) {
171
949
  if (workflows.length === 0)
172
950
  return "No workflows found for the active brand.";
@@ -181,23 +959,61 @@ export function formatWorkflowList(workflows) {
181
959
  export function formatRecentRuns(runs) {
182
960
  if (runs.length === 0)
183
961
  return "No workflow runs found for the active brand.";
184
- return table(["workflow", "status", "created", "id"], runs.map((r) => [r.workflowName, r.status, dateOnly(r.createdAt), r._id]));
962
+ return table(["workflow", "status", "created", "id"], runs.map((r) => [r.workflowName, runVerdict(r), dateOnly(r.createdAt), r._id]));
963
+ }
964
+ export function formatWorkflowVersions(versions) {
965
+ if (versions.length === 0) {
966
+ return "no saved versions yet — versions start recording on the workflow's next save";
967
+ }
968
+ const lines = versions.map((v) => {
969
+ const by = v.savedByName ? ` · by ${v.savedByName}` : "";
970
+ return `v${v.version} · ${v.name} · saved ${dateOnly(v.savedAt)}${by}`;
971
+ });
972
+ if (versions.length === VERSIONS_CAP) {
973
+ lines.push("");
974
+ lines.push(`(showing the ${VERSIONS_CAP} most recent versions — older versions may exist beyond this cap)`);
975
+ }
976
+ return lines.join("\n");
185
977
  }
186
978
  export function formatImportSummary(result, mode = {}) {
187
979
  const lines = [];
188
- const heading = mode.dryRun
189
- ? "Workflow import preview:"
190
- : result.created
191
- ? "Workflow imported."
192
- : mode.update
193
- ? "Workflow updated."
194
- : "Workflow import preview:";
980
+ const heading = mode.validate
981
+ ? "Workflow validation passed:"
982
+ : mode.dryRun
983
+ ? "Workflow import preview:"
984
+ : result.created
985
+ ? "Workflow imported."
986
+ : mode.update
987
+ ? "Workflow updated."
988
+ : "Workflow import preview:";
195
989
  lines.push(heading);
196
990
  lines.push(`name: ${result.name}`);
197
991
  if (result.workflowId)
198
992
  lines.push(`workflowId: ${result.workflowId}`);
199
993
  lines.push(`nodes: ${result.nodeCount}`);
200
994
  lines.push(`edges: ${result.edgeCount}`);
995
+ if (result.triggers && result.triggers.length > 0) {
996
+ lines.push("");
997
+ const enabledCount = result.triggers.filter((t) => t.enabled).length;
998
+ lines.push(`Triggers (${result.triggers.length}):`);
999
+ for (const t of result.triggers) {
1000
+ const detail = t.type === "event" ? `event (${t.event})` : `cron (${t.cron})`;
1001
+ if (t.enabled) {
1002
+ const fires = t.type === "event"
1003
+ ? t.event === "winner-promoted"
1004
+ ? "fires on every promote"
1005
+ : `fires on ${t.event}`
1006
+ : `fires on schedule ${t.cron}`;
1007
+ lines.push(` ⚠ ${detail} — ENABLED, ${fires}`);
1008
+ }
1009
+ else {
1010
+ lines.push(` ${detail} — disabled`);
1011
+ }
1012
+ }
1013
+ if (enabledCount > 0) {
1014
+ lines.push(` ⚠ ${enabledCount} enabled trigger${enabledCount === 1 ? "" : "s"} armed — a background run may start on the owner's keys. Disable with: exodus workflow triggers <id> disable <n>`);
1015
+ }
1016
+ }
201
1017
  if (result.unresolved.length > 0) {
202
1018
  lines.push("");
203
1019
  lines.push(`Unresolved references (${result.unresolved.length}):`);
@@ -221,7 +1037,7 @@ export function formatWorkflowRun(run) {
221
1037
  lines.push(`workflowId: ${run.workflowId}`);
222
1038
  if (run.triggerRunId)
223
1039
  lines.push(`triggerRunId: ${run.triggerRunId}`);
224
- lines.push(`verdict: ${run.status}${counts ? ` (${counts})` : ""}`);
1040
+ lines.push(`verdict: ${runVerdict(run)}${counts ? ` (${counts})` : ""}`);
225
1041
  if (run.isTerminal)
226
1042
  lines.push("terminal: yes");
227
1043
  if (run.error)
@@ -230,47 +1046,251 @@ export function formatWorkflowRun(run) {
230
1046
  const inputs = Object.entries(run.inputs).map(([k, v]) => `${k}=${v}`).join(", ");
231
1047
  lines.push(`inputs: ${inputs}`);
232
1048
  }
1049
+ if (run.autoApprovals && run.autoApprovals.length > 0) {
1050
+ lines.push(`auto-approved: ${run.autoApprovals.length} checkpoint stop${run.autoApprovals.length === 1 ? "" : "s"} (${run.autoApprovals.map((a) => a.nodeId).join(", ")}) — launched with --auto-approve, nobody reviewed these`);
1051
+ }
1052
+ const parkedNodeId = gateParkedNodeId(run.status, run.pauseReason, run.pausedNodeId);
233
1053
  if (run.nodes.length > 0) {
234
1054
  lines.push("");
235
1055
  lines.push(`Nodes (${run.nodes.length}):`);
236
1056
  for (const node of run.nodes) {
237
- lines.push(progressLine(node));
1057
+ lines.push(progressLine(node, parkedNodeId !== undefined && node.nodeId === parkedNodeId));
238
1058
  for (const output of node.outputs)
239
1059
  lines.push(...outputLines(output));
240
1060
  }
241
1061
  }
1062
+ if (run.deliveries && run.deliveries.length > 0) {
1063
+ lines.push("");
1064
+ lines.push(`Deliveries (${run.deliveries.length}):`);
1065
+ for (const delivery of run.deliveries) {
1066
+ lines.push(...deliveryLines(delivery, parkedNodeId));
1067
+ }
1068
+ }
242
1069
  if (run.outputs && run.outputs.length > 0) {
243
1070
  lines.push("");
244
1071
  lines.push(`Outputs (${run.outputs.length}):`);
245
- for (const output of run.outputs)
246
- lines.push(...runOutputLines(output));
1072
+ for (const output of run.outputs) {
1073
+ lines.push(...runOutputLines(output, parkedNodeId !== undefined && output.nodeId === parkedNodeId));
1074
+ }
1075
+ }
1076
+ if (run.sessions && run.sessions.length > 0) {
1077
+ lines.push("");
1078
+ lines.push(`Sessions (${run.sessions.length}):`);
1079
+ for (const s of run.sessions) {
1080
+ lines.push(` session: ${s.sessionId} · "${s.title}" · continue: exodus session chat ${s.sessionId} "..."`);
1081
+ }
247
1082
  }
248
1083
  return lines.join("\n");
249
1084
  }
250
- function runOutputLines(output) {
1085
+ const NOT_YET_APPROVED = "awaiting approval, not yet approved";
1086
+ function runOutputLines(output, awaitingReview = false) {
251
1087
  const slug = output.botSlug ? ` (${output.botSlug})` : "";
1088
+ const review = awaitingReview ? ` — ${NOT_YET_APPROVED}` : "";
252
1089
  if (output.type === "image") {
253
- return [` ${output.label} [image]${slug}: ${output.imageUrl ?? output.imageId ?? "(no url)"}`];
1090
+ return [` ${output.label} [image]${slug}: ${output.imageUrl ?? output.imageId ?? "(no url)"}${review}`];
254
1091
  }
255
1092
  if (output.type === "video") {
256
1093
  const tag = output.final === true ? "final video" : "video";
257
- return [` ${output.label} [${tag}]${slug}: ${output.videoUrl ?? "(no url)"}`];
1094
+ return [` ${output.label} [${tag}]${slug}: ${output.videoUrl ?? "(no url)"}${review}`];
258
1095
  }
259
1096
  if (output.type === "audio") {
260
- return [` ${output.label} [audio]${slug}: ${output.audioUrl ?? "(no url)"}`];
1097
+ return [` ${output.label} [audio]${slug}: ${output.audioUrl ?? "(no url)"}${review}`];
1098
+ }
1099
+ if (output.type === "document") {
1100
+ const name = output.filename ? ` ${output.filename}` : "";
1101
+ return [
1102
+ ` ${output.label} [document]${slug}:${name} ${output.documentUrl ?? "(no url)"}${review}`,
1103
+ ];
261
1104
  }
262
1105
  if (output.type === "frames") {
263
1106
  const n = output.frames?.length ?? 0;
264
- return [` ${output.label} [frames]${slug}: ${n} scene${n === 1 ? "" : "s"}`];
1107
+ return [` ${output.label} [frames]${slug}: ${n} scene${n === 1 ? "" : "s"}${review}`];
265
1108
  }
266
1109
  if (output.type === "storyboard") {
267
- return [` ${output.label} [storyboard]${slug}: use --json for the scene plan`];
1110
+ return [` ${output.label} [storyboard]${slug}: use --json for the scene plan${review}`];
268
1111
  }
269
1112
  const raw = output.text ?? "";
270
1113
  const normalized = raw.replace(/\s+/g, " ").trim();
271
1114
  const body = truncateText(raw, 400);
272
1115
  const note = normalized.length > 400 ? "\n (truncated — use --json for the full text)" : "";
273
- return [` ${output.label} [text]${slug}:`, ` ${body}${note}`];
1116
+ return [` ${output.label} [text]${slug}${review}:`, ` ${body}${note}`];
1117
+ }
1118
+ function deliveryLines(delivery, parkedNodeId) {
1119
+ const heldArtifact = (a) => parkedNodeId !== undefined && a.nodeId === parkedNodeId;
1120
+ const held = delivery.status === "delivered" && delivery.artifacts.some(heldArtifact);
1121
+ const status = held
1122
+ ? `held — ${NOT_YET_APPROVED}`
1123
+ : delivery.status === "unfulfilled" && delivery.error
1124
+ ? `unfulfilled — ${delivery.error}`
1125
+ : delivery.status;
1126
+ const lines = [` ${delivery.label} (${delivery.key}) · ${delivery.type} · ${status}`];
1127
+ for (const artifact of delivery.artifacts) {
1128
+ for (const line of runOutputLines(artifact, heldArtifact(artifact))) {
1129
+ lines.push(` ${line}`);
1130
+ }
1131
+ }
1132
+ return lines;
1133
+ }
1134
+ const ASSET_FALLBACK_EXT = {
1135
+ image: "png",
1136
+ video: "mp4",
1137
+ audio: "mp3",
1138
+ };
1139
+ export function workflowFilenameSlug(name) {
1140
+ const slug = (name ?? "")
1141
+ .toLowerCase()
1142
+ .replace(/[^a-z0-9]+/g, "-")
1143
+ .replace(/^-+|-+$/g, "");
1144
+ return slug || "workflow";
1145
+ }
1146
+ function extensionFromUrl(url) {
1147
+ const withoutQuery = url.split(/[?#]/)[0];
1148
+ const m = withoutQuery.match(/\.([a-z0-9]{1,5})$/i);
1149
+ return m ? m[1].toLowerCase() : undefined;
1150
+ }
1151
+ function planArtifactFile(artifact) {
1152
+ if (artifact.type === "text") {
1153
+ return { kind: "text", ext: "md", body: artifact.text ?? "" };
1154
+ }
1155
+ if (artifact.type === "storyboard") {
1156
+ const json = artifact.storyboardJson;
1157
+ if (!json)
1158
+ return { kind: "none", reason: "no storyboard JSON on this artifact" };
1159
+ return { kind: "text", ext: "json", body: json.endsWith("\n") ? json : `${json}\n` };
1160
+ }
1161
+ if (artifact.type === "frames") {
1162
+ return {
1163
+ kind: "text",
1164
+ ext: "json",
1165
+ body: `${JSON.stringify(artifact.frames ?? [], null, 2)}\n`,
1166
+ };
1167
+ }
1168
+ const url = artifact.type === "image"
1169
+ ? (artifact.imageUrl ?? undefined)
1170
+ : artifact.type === "video"
1171
+ ? artifact.videoUrl
1172
+ : artifact.type === "document"
1173
+ ?
1174
+ artifact.documentUrl
1175
+ : artifact.audioUrl;
1176
+ if (!url)
1177
+ return { kind: "none", reason: "no downloadable URL on this artifact" };
1178
+ const filenameExt = artifact.type === "document" && artifact.filename
1179
+ ? extensionFromUrl(artifact.filename)
1180
+ : undefined;
1181
+ return {
1182
+ kind: "download",
1183
+ ext: filenameExt ??
1184
+ extensionFromUrl(url) ??
1185
+ ASSET_FALLBACK_EXT[artifact.type] ??
1186
+ "bin",
1187
+ url,
1188
+ };
1189
+ }
1190
+ export async function saveDeliveries(run, dir, deps) {
1191
+ const paths = [];
1192
+ if (!run.isTerminal) {
1193
+ return {
1194
+ paths,
1195
+ lines: [
1196
+ `Nothing saved — this run isn't finished yet (${run.status}). Try again once it is: exodus workflow status --id ${run._id} --out ${dir}`,
1197
+ ],
1198
+ };
1199
+ }
1200
+ const deliveries = run.deliveries ?? [];
1201
+ if (deliveries.length === 0) {
1202
+ return {
1203
+ paths,
1204
+ lines: [
1205
+ "Nothing saved — this run has no named delivery slots. Either the workflow has no Output nodes, or the backend it ran on predates named outputs.",
1206
+ ],
1207
+ };
1208
+ }
1209
+ const mkdirp = deps.mkdirp ?? defaultMkdirp;
1210
+ const downloadToFile = deps.downloadToFile ?? defaultDownloadToFile;
1211
+ mkdirp(dir);
1212
+ const stem = `${workflowFilenameSlug(run.workflowName)}-${run._id.slice(-8)}`;
1213
+ const lines = [`Saved deliveries to ${dir}:`];
1214
+ for (const delivery of deliveries) {
1215
+ if (delivery.status !== "delivered" || delivery.artifacts.length === 0) {
1216
+ const why = delivery.error !== undefined
1217
+ ? `unfulfilled: ${delivery.error}`
1218
+ : delivery.status === "delivered"
1219
+ ? "delivered but empty"
1220
+ : "unfulfilled";
1221
+ lines.push(` skipped ${delivery.label} (${delivery.key}) — ${why}`);
1222
+ continue;
1223
+ }
1224
+ for (let i = 0; i < delivery.artifacts.length; i++) {
1225
+ const plan = planArtifactFile(delivery.artifacts[i]);
1226
+ const suffix = i === 0 ? "" : `-${i + 1}`;
1227
+ if (plan.kind === "none") {
1228
+ lines.push(` skipped ${delivery.label} (${delivery.key})${suffix} — ${plan.reason}`);
1229
+ continue;
1230
+ }
1231
+ const file = nodePath.join(dir, `${stem}-${workflowFilenameSlug(delivery.key)}${suffix}.${plan.ext}`);
1232
+ try {
1233
+ if (plan.kind === "text")
1234
+ deps.writeFile(file, plan.body);
1235
+ else
1236
+ await downloadToFile(plan.url, file);
1237
+ lines.push(` wrote ${file}`);
1238
+ paths.push(file);
1239
+ }
1240
+ catch (e) {
1241
+ lines.push(` failed ${file} — ${e instanceof Error ? e.message : String(e)}`);
1242
+ }
1243
+ }
1244
+ }
1245
+ lines.push(`${paths.length} file${paths.length === 1 ? "" : "s"} written.`);
1246
+ return { lines, paths };
1247
+ }
1248
+ function inputValueHint(input) {
1249
+ const open = input.allowOther ? ", or your own answer" : "";
1250
+ if (input.type === "select") {
1251
+ const options = input.options ?? [];
1252
+ return options.length > 0 ? `one of: ${options.join(", ")}${open}` : undefined;
1253
+ }
1254
+ if (input.type === "multi-select") {
1255
+ const options = input.options ?? [];
1256
+ return options.length > 0
1257
+ ? `one or more of: ${options.join(", ")} (comma-separated)${open}`
1258
+ : undefined;
1259
+ }
1260
+ if (input.type === "toggle")
1261
+ return "true or false";
1262
+ return undefined;
1263
+ }
1264
+ export function deliveryTypeWord(type) {
1265
+ switch (type) {
1266
+ case "text":
1267
+ return "text";
1268
+ case "structured":
1269
+ return "structured data";
1270
+ case "asset":
1271
+ return "file";
1272
+ case "collection":
1273
+ return "set of files";
1274
+ default:
1275
+ return type;
1276
+ }
1277
+ }
1278
+ export function deliveryContractLines(deliveries) {
1279
+ if (deliveries === undefined)
1280
+ return [];
1281
+ if (deliveries.length === 0)
1282
+ return ["Delivers: nothing — no Output node."];
1283
+ const lines = [`Delivers (${deliveries.length}):`];
1284
+ const ordered = deliveries
1285
+ .map((delivery, index) => ({ delivery, index }))
1286
+ .sort((a, b) => (a.delivery.order ?? a.index) - (b.delivery.order ?? b.index) || a.index - b.index)
1287
+ .map((entry) => entry.delivery);
1288
+ for (const delivery of ordered) {
1289
+ lines.push(` ${delivery.label} (${delivery.key}) — ${deliveryTypeWord(delivery.type)}`);
1290
+ if (delivery.description)
1291
+ lines.push(` ${delivery.description}`);
1292
+ }
1293
+ return lines;
274
1294
  }
275
1295
  export function formatDescribe(res) {
276
1296
  const lines = [];
@@ -287,8 +1307,14 @@ export function formatDescribe(res) {
287
1307
  else {
288
1308
  for (const input of res.inputs) {
289
1309
  const req = input.required ? "required" : "optional";
1310
+ const type = input.type && input.type !== "text" ? ` (${input.type})` : "";
290
1311
  const bundle = input.bundleSize !== undefined ? `, bundle=${input.bundleSize}` : "";
291
- lines.push(` ${input.fieldName} — ${input.source}, ${req}${bundle}`);
1312
+ const family = input.source === "asset" && input.assetType ? ` (${input.assetType})` : "";
1313
+ const label = input.label ? ` (${input.label})` : "";
1314
+ lines.push(` ${input.fieldName}${label} — ${input.source}${family}${type}, ${req}${bundle}`);
1315
+ const hint = inputValueHint(input);
1316
+ if (hint)
1317
+ lines.push(` ${hint}`);
292
1318
  if (input.description)
293
1319
  lines.push(` ${input.description}`);
294
1320
  }
@@ -322,6 +1348,11 @@ export function formatDescribe(res) {
322
1348
  lines.push(` ${output.label} [${output.type}]${slug}`);
323
1349
  }
324
1350
  }
1351
+ const delivers = deliveryContractLines(res.deliveries);
1352
+ if (delivers.length > 0) {
1353
+ lines.push("");
1354
+ lines.push(...delivers);
1355
+ }
325
1356
  return lines.join("\n");
326
1357
  }
327
1358
  function formatBotVocabulary(catalog) {
@@ -335,6 +1366,9 @@ function formatBotVocabulary(catalog) {
335
1366
  lines.push(` aspect ratios: ${v.aspectRatios.join(", ")}`);
336
1367
  lines.push(` custom bot: set a bot node's slug to "${catalog.customBot.slug}" and ` +
337
1368
  `config.${catalog.customBot.configKey}=<genesis-slug> to reach any bot not listed here.`);
1369
+ lines.push(` prompt bot: set a bot node's slug to "${catalog.promptBot.slug}" and ` +
1370
+ `config.${catalog.promptBot.configKey}=<your instructions> — the prompt IS the bot ` +
1371
+ "(runs on the workspace's own LLM key, not Genesis).");
338
1372
  return lines.join("\n");
339
1373
  }
340
1374
  export function formatBotsList(catalog, category) {
@@ -370,7 +1404,6 @@ export function formatBotDetail(bot) {
370
1404
  lines.push(`category: ${bot.categoryLabel} (${bot.category})`);
371
1405
  lines.push(`blurb: ${bot.blurb}`);
372
1406
  lines.push(`outputType: ${bot.outputType}`);
373
- lines.push(`splits: ${bot.splitsOutput ? "yes (can split into per-item deliverables)" : "no"}`);
374
1407
  lines.push("");
375
1408
  lines.push(`Input ports (${bot.inputs.length}):`);
376
1409
  if (bot.inputs.length === 0) {
@@ -412,51 +1445,224 @@ export function formatBotDetail(bot) {
412
1445
  }
413
1446
  return lines.join("\n");
414
1447
  }
415
- function graphIssueLines(issue) {
416
- const node = issue.nodeId ? ` [node ${issue.nodeId}]` : "";
417
- const port = issue.portId ? ` [port ${issue.portId}]` : "";
418
- const edge = !issue.nodeId && issue.edgeId ? ` [edge ${issue.edgeId}]` : "";
419
- const out = [`${issue.code}${node}${edge}${port}: ${issue.message}`];
420
- if (issue.remedy)
421
- out.push(` fix: ${issue.remedy}`);
422
- return out;
1448
+ function firstLine(text) {
1449
+ const nl = text.indexOf("\n");
1450
+ return (nl === -1 ? text : text.slice(0, nl)).trim();
423
1451
  }
424
- function formatImportError(res) {
425
- const data = isRecord(res.data) ? res.data : {};
426
- const err = isRecord(data.error) ? data.error : {};
427
- const code = typeof err.code === "string" ? err.code : undefined;
428
- const message = typeof err.message === "string" ? err.message : "Import failed";
429
- if (code === "INVALID_GRAPH") {
430
- const issues = Array.isArray(data.issues) ? data.issues : [];
431
- const lines = [`Import rejected — invalid graph: ${message}`];
432
- if (issues.length > 0) {
433
- lines.push("");
434
- lines.push(`Issues (${issues.length}):`);
435
- for (const issue of issues)
436
- lines.push(...graphIssueLines(issue));
437
- }
438
- return lines.join("\n");
1452
+ export function formatTemplatesList(templates) {
1453
+ if (templates.length === 0)
1454
+ return "No workflow templates available on this backend.";
1455
+ const lines = [
1456
+ table(["key", "label", "description"], templates.map((t) => [
1457
+ t.key,
1458
+ t.module ? `${t.label} [${t.module} module]` : t.label,
1459
+ firstLine(t.description ?? ""),
1460
+ ])),
1461
+ ];
1462
+ if (templates.some((t) => t.module)) {
1463
+ lines.push("");
1464
+ lines.push("Templates badged [<module> module] are owned by a module (e.g. video) — " +
1465
+ "their runs start from the show surfaces, not `workflow run`. Export one to " +
1466
+ "study or adapt its graph.");
439
1467
  }
440
- if (code === "CONFLICT") {
441
- const lines = [`Import conflict — ${message}`];
442
- if (typeof data.currentUpdatedAt === "string") {
443
- lines.push(`current updatedAt: ${data.currentUpdatedAt}`);
444
- }
445
- const remedy = typeof data.remedy === "string"
1468
+ lines.push("");
1469
+ lines.push("Export one to start authoring: exodus workflow templates export <key> --out my.yaml");
1470
+ return lines.join("\n");
1471
+ }
1472
+ const SCHEMA_LABEL_KEYS = ["kind", "face", "type", "name", "id", "code", "key", "label"];
1473
+ function schemaEntryLabel(entry) {
1474
+ for (const key of SCHEMA_LABEL_KEYS) {
1475
+ const v = entry[key];
1476
+ if (typeof v === "string" && v)
1477
+ return { key, value: v };
1478
+ }
1479
+ return undefined;
1480
+ }
1481
+ function schemaValueLines(value, indent) {
1482
+ if (value === null || value === undefined)
1483
+ return [`${indent}(none)`];
1484
+ if (Array.isArray(value)) {
1485
+ if (value.length === 0)
1486
+ return [`${indent}(none)`];
1487
+ const lines = [];
1488
+ for (const el of value) {
1489
+ if (isRecord(el)) {
1490
+ const label = schemaEntryLabel(el);
1491
+ if (label) {
1492
+ const parked = el["parked"] === true;
1493
+ lines.push(`${indent}- ${label.value}${parked ? " (parked)" : ""}`);
1494
+ const rest = { ...el };
1495
+ delete rest[label.key];
1496
+ if (parked)
1497
+ delete rest["parked"];
1498
+ lines.push(...schemaValueLines(rest, `${indent} `));
1499
+ }
1500
+ else {
1501
+ lines.push(`${indent}-`);
1502
+ lines.push(...schemaValueLines(el, `${indent} `));
1503
+ }
1504
+ }
1505
+ else {
1506
+ lines.push(`${indent}- ${String(el)}`);
1507
+ }
1508
+ }
1509
+ return lines;
1510
+ }
1511
+ if (isRecord(value)) {
1512
+ const entries = Object.entries(value);
1513
+ if (entries.length === 0)
1514
+ return [`${indent}(none)`];
1515
+ const lines = [];
1516
+ for (const [k, v] of entries) {
1517
+ if (isRecord(v) || Array.isArray(v)) {
1518
+ lines.push(`${indent}${k}:`);
1519
+ lines.push(...schemaValueLines(v, `${indent} `));
1520
+ }
1521
+ else {
1522
+ lines.push(`${indent}${k}: ${String(v)}`);
1523
+ }
1524
+ }
1525
+ return lines;
1526
+ }
1527
+ return [`${indent}${String(value)}`];
1528
+ }
1529
+ const SCHEMA_SECTIONS = [
1530
+ { title: "Graph contract version", keys: ["graphVersion"] },
1531
+ { title: "Port types", keys: ["portTypes"] },
1532
+ { title: "Node kinds", keys: ["nodeKinds"] },
1533
+ { title: "Transform faces", keys: ["transformFaces"] },
1534
+ { title: "Collector policy", keys: ["collectorPolicy"] },
1535
+ { title: "Deposits", keys: ["deposits"] },
1536
+ { title: "Slots", keys: ["slots"] },
1537
+ { title: "Triggers", keys: ["triggers"] },
1538
+ { title: "Edge / graph rules", keys: ["edgeRules", "graphRules"] },
1539
+ {
1540
+ title: "Bots",
1541
+ keys: ["botsPointer", "botsPointerNote", "bots-pointer-note", "botsNote", "bots"],
1542
+ },
1543
+ ];
1544
+ function schemaSectionValue(payload, keys) {
1545
+ for (const key of keys) {
1546
+ if (payload[key] !== undefined)
1547
+ return { key, value: payload[key] };
1548
+ }
1549
+ return undefined;
1550
+ }
1551
+ export function formatSchema(payload) {
1552
+ const lines = [];
1553
+ const version = payload["version"];
1554
+ lines.push(`Workflow schema${version !== undefined ? ` (version ${version})` : ""}`);
1555
+ for (const section of SCHEMA_SECTIONS) {
1556
+ const found = schemaSectionValue(payload, section.keys);
1557
+ if (!found)
1558
+ continue;
1559
+ lines.push("");
1560
+ lines.push(`${section.title}:`);
1561
+ lines.push(...schemaValueLines(found.value, " "));
1562
+ }
1563
+ return lines.join("\n");
1564
+ }
1565
+ function schemaEntryIds(value) {
1566
+ if (!Array.isArray(value))
1567
+ return [];
1568
+ const ids = [];
1569
+ for (const el of value) {
1570
+ if (isRecord(el)) {
1571
+ const label = schemaEntryLabel(el);
1572
+ if (label)
1573
+ ids.push(label.value);
1574
+ }
1575
+ else if (typeof el === "string") {
1576
+ ids.push(el);
1577
+ }
1578
+ }
1579
+ return ids;
1580
+ }
1581
+ function formatSchemaFilter(payload, sectionKeys, axis, wanted) {
1582
+ const found = schemaSectionValue(payload, sectionKeys);
1583
+ const list = found && Array.isArray(found.value) ? found.value : [];
1584
+ const match = list.find((el) => {
1585
+ if (!isRecord(el))
1586
+ return typeof el === "string" && el === wanted;
1587
+ const label = schemaEntryLabel(el);
1588
+ return label?.value === wanted;
1589
+ });
1590
+ if (match === undefined) {
1591
+ const valid = schemaEntryIds(found?.value).join(", ") || "(none)";
1592
+ return { code: 1, lines: [`Unknown ${axis} "${wanted}". Valid ${axis}s: ${valid}`] };
1593
+ }
1594
+ const title = axis === "kind" ? "Node kind" : "Transform face";
1595
+ const lines = [`${title}: ${wanted}`];
1596
+ if (isRecord(match)) {
1597
+ const label = schemaEntryLabel(match);
1598
+ const rest = { ...match };
1599
+ if (label)
1600
+ delete rest[label.key];
1601
+ lines.push(...schemaValueLines(rest, " "));
1602
+ }
1603
+ return { code: 0, lines };
1604
+ }
1605
+ function graphIssueLines(issue) {
1606
+ const node = issue.nodeId ? ` [node ${issue.nodeId}]` : "";
1607
+ const port = issue.portId ? ` [port ${issue.portId}]` : "";
1608
+ const edge = !issue.nodeId && issue.edgeId ? ` [edge ${issue.edgeId}]` : "";
1609
+ const out = [`${issue.code}${node}${edge}${port}: ${issue.message}`];
1610
+ if (issue.remedy)
1611
+ out.push(` fix: ${issue.remedy}`);
1612
+ return out;
1613
+ }
1614
+ function formatImportError(res) {
1615
+ const data = isRecord(res.data) ? res.data : {};
1616
+ const err = isRecord(data.error) ? data.error : {};
1617
+ const code = typeof err.code === "string" ? err.code : undefined;
1618
+ const message = typeof err.message === "string" ? err.message : "Import failed";
1619
+ if (code === "INVALID_GRAPH") {
1620
+ const issues = Array.isArray(data.issues) ? data.issues : [];
1621
+ const lines = [`Import rejected — invalid graph: ${message}`];
1622
+ if (issues.length > 0) {
1623
+ lines.push("");
1624
+ lines.push(`Issues (${issues.length}):`);
1625
+ for (const issue of issues)
1626
+ lines.push(...graphIssueLines(issue));
1627
+ }
1628
+ return lines.join("\n");
1629
+ }
1630
+ if (code === "CONFLICT") {
1631
+ const lines = [`Import conflict — ${message}`];
1632
+ if (typeof data.currentUpdatedAt === "string") {
1633
+ lines.push(`current updatedAt: ${data.currentUpdatedAt}`);
1634
+ }
1635
+ const remedy = typeof data.remedy === "string"
446
1636
  ? data.remedy
447
1637
  : "Re-export the workflow, reapply your edits, and import again with the fresh updatedAt.";
448
1638
  lines.push(`fix: ${remedy}`);
449
1639
  return lines.join("\n");
450
1640
  }
451
- return formatError(res);
1641
+ return formatApiError(res);
1642
+ }
1643
+ class WorkflowResolveError extends Error {
1644
+ status;
1645
+ data;
1646
+ constructor(status, data, message) {
1647
+ super(message);
1648
+ this.status = status;
1649
+ this.data = data;
1650
+ this.name = "WorkflowResolveError";
1651
+ }
452
1652
  }
453
1653
  export async function resolveWorkflowId(ref, deps) {
454
1654
  const res = await deps.get(LIST_PATH);
455
1655
  if (!res.ok)
456
- throw new Error(formatError(res));
1656
+ throw new WorkflowResolveError(res.status, res.data, formatApiError(res));
457
1657
  const workflows = res.data.workflows ?? [];
458
- const match = workflows.find((w) => w.name.toLowerCase() === ref.toLowerCase());
459
- return match?._id ?? ref;
1658
+ const byName = workflows.find((w) => w.name.toLowerCase() === ref.toLowerCase());
1659
+ if (byName)
1660
+ return byName._id;
1661
+ const byId = workflows.find((w) => w._id === ref);
1662
+ if (byId)
1663
+ return byId._id;
1664
+ const message = `No workflow named "${ref}" on this brand — run: exodus workflow list`;
1665
+ throw new WorkflowResolveError(404, { error: { code: "NOT_FOUND", message } }, message);
460
1666
  }
461
1667
  export async function listFlow(json, deps) {
462
1668
  const res = await deps.get(LIST_PATH);
@@ -474,7 +1680,7 @@ export async function describeFlow(workflowRef, opts, deps) {
474
1680
  workflowId = await resolveWorkflowId(workflowRef, deps);
475
1681
  }
476
1682
  catch (e) {
477
- return { code: 1, lines: [e instanceof Error ? e.message : String(e)] };
1683
+ return resolveIdErrorResult(e, opts.json ?? false);
478
1684
  }
479
1685
  const res = await deps.get(`${DESCRIBE_PATH}?id=${encodeURIComponent(workflowId)}`);
480
1686
  if (!res.ok)
@@ -508,85 +1714,201 @@ export async function runFlow(workflowRef, opts, deps) {
508
1714
  workflowId = await resolveWorkflowId(workflowRef, deps);
509
1715
  }
510
1716
  catch (e) {
511
- return { code: 1, lines: [e instanceof Error ? e.message : String(e)] };
1717
+ return resolveIdErrorResult(e, opts.json ?? false);
1718
+ }
1719
+ const preface = [];
1720
+ const scoped = (opts.terminalNodeIds?.length ?? 0) > 0;
1721
+ let prepared;
1722
+ try {
1723
+ prepared = await prepareRunInputs(workflowId, opts.inputs, deps, (line) => {
1724
+ if (opts.json)
1725
+ return;
1726
+ if (opts.onProgressLine)
1727
+ opts.onProgressLine(line);
1728
+ else
1729
+ preface.push(line);
1730
+ }, scoped);
1731
+ }
1732
+ catch (e) {
1733
+ const message = e instanceof Error ? e.message : String(e);
1734
+ return {
1735
+ code: 1,
1736
+ lines: opts.json
1737
+ ?
1738
+ [JSON.stringify({ ok: false, status: 400, data: { error: { code: "BAD_REQUEST", message } } })]
1739
+ : [...preface, message],
1740
+ };
1741
+ }
1742
+ const inputs = prepared.inputs;
1743
+ const warned = [];
1744
+ for (const warning of prepared.warnings) {
1745
+ warned.push(warning);
1746
+ opts.onWarningLine?.(warning);
512
1747
  }
513
1748
  const body = {
514
1749
  workflowId,
515
- ...(Object.keys(opts.inputs).length > 0 ? { inputs: opts.inputs } : {}),
1750
+ ...(Object.keys(inputs).length > 0 ? { inputs } : {}),
1751
+ ...(opts.fill && opts.fill.trim() !== "" ? { fill: opts.fill.trim() } : {}),
1752
+ ...(opts.terminalNodeIds && opts.terminalNodeIds.length > 0
1753
+ ? { terminalNodeIds: opts.terminalNodeIds }
1754
+ : {}),
1755
+ ...(opts.autoApprove === true ? { autoApprove: true } : {}),
1756
+ ...(opts.imageRigOverrides ? { imageRigOverrides: opts.imageRigOverrides } : {}),
1757
+ launchedVia: "cli",
516
1758
  };
517
1759
  const start = await deps.post(RUN_PATH, body);
518
1760
  if (!start.ok)
519
1761
  return asErrorResult(start, opts.json);
520
1762
  const data = start.data;
1763
+ for (const warning of serverWarningsToPrint(data?.warnings, warned)) {
1764
+ warned.push(warning);
1765
+ opts.onWarningLine?.(warning);
1766
+ }
521
1767
  const base = { ...data, workflowId };
522
1768
  if (opts.json && !opts.wait)
523
1769
  return { code: 0, lines: [JSON.stringify(base)] };
524
1770
  const lines = opts.json
525
1771
  ? []
526
1772
  : [
1773
+ ...preface,
527
1774
  "Workflow run started.",
528
1775
  `runId: ${data.runId}`,
529
1776
  `triggerRunId: ${data.triggerRunId}`,
530
1777
  `Poll: exodus workflow status --id ${data.runId}`,
531
1778
  ];
532
- if (!opts.wait)
1779
+ if (!opts.wait) {
1780
+ if (opts.out !== undefined && !opts.json) {
1781
+ lines.push(`Nothing saved to ${opts.out} yet — the run is still going. Add --wait, or save later: exodus workflow status --id ${data.runId} --out ${opts.out}`);
1782
+ }
533
1783
  return { code: 0, lines };
1784
+ }
534
1785
  if (!opts.json && opts.onProgressLine) {
535
1786
  for (const line of lines)
536
1787
  opts.onProgressLine(line);
537
1788
  lines.length = 0;
538
1789
  }
1790
+ const waited = await waitForRun(data.runId, { json: opts.json, onProgressLine: opts.onProgressLine, jsonBase: base, out: opts.out }, deps);
1791
+ if (opts.json)
1792
+ return waited;
1793
+ return { code: waited.code, lines: [...lines, ...waited.lines] };
1794
+ }
1795
+ const WAIT_TERMINAL_STATUSES = TERMINAL_RUN_STATUSES.flatMap((s) => storedWorkflowStatusForms(s));
1796
+ async function waitForRun(runId, opts, deps) {
539
1797
  const seen = new Map();
540
1798
  let pausedNotified = false;
1799
+ const landOnPark = opts.landOnPark;
541
1800
  const pollResult = await deps.poll({
542
- path: `${STATUS_PATH}?runId=${encodeURIComponent(data.runId)}`,
1801
+ path: `${STATUS_PATH}?runId=${encodeURIComponent(runId)}`,
543
1802
  intervalMs: 3_000,
544
1803
  timeoutMs: 60 * 60 * 1000,
545
- terminalStatuses: ["completed", "partial", "failed", "canceled"],
1804
+ terminalStatuses: landOnPark
1805
+ ? [...WAIT_TERMINAL_STATUSES, ...storedWorkflowStatusForms("awaiting-approval")]
1806
+ : WAIT_TERMINAL_STATUSES,
1807
+ ...(landOnPark
1808
+ ? {
1809
+ isDone: (raw) => !(typeof raw["status"] === "string" &&
1810
+ normalizeRunStatus(raw["status"]) === "awaiting-approval") || raw["pauseReason"] === landOnPark.pauseReason,
1811
+ }
1812
+ : {}),
546
1813
  onProgress: (raw) => {
547
1814
  if (opts.json || !opts.onProgressLine)
548
1815
  return;
549
- if (raw["status"] === "awaiting-review" && !pausedNotified) {
1816
+ const rawStatus = raw["status"];
1817
+ const parked = typeof rawStatus === "string" &&
1818
+ normalizeRunStatus(rawStatus) === "awaiting-approval";
1819
+ const isLanding = landOnPark !== undefined && raw["pauseReason"] === landOnPark.pauseReason;
1820
+ if (parked && !pausedNotified && !isLanding) {
550
1821
  pausedNotified = true;
551
- opts.onProgressLine(" ⏸ paused at the cost gate — approve or edit the storyboard in the web app to continue.");
1822
+ const dashboardUrl = deps.dashboardUrl ?? getDashboardUrl();
1823
+ const pauseReason = raw["pauseReason"];
1824
+ for (const line of formatPauseNotice(pauseReason, runId, dashboardUrl)) {
1825
+ opts.onProgressLine(line);
1826
+ }
552
1827
  }
1828
+ const parkedNodeId = gateParkedNodeId(raw["status"], raw["pauseReason"], raw["pausedNodeId"]);
553
1829
  const nodes = Array.isArray(raw["nodes"]) ? raw["nodes"] : [];
554
1830
  for (const node of nodes) {
555
- if (seen.get(node.nodeId) === node.status)
1831
+ const isParked = parkedNodeId !== undefined && node.nodeId === parkedNodeId;
1832
+ const renderKey = `${node.status}:${isParked}`;
1833
+ if (seen.get(node.nodeId) === renderKey)
556
1834
  continue;
557
- seen.set(node.nodeId, node.status);
558
- opts.onProgressLine(progressLine(node));
1835
+ seen.set(node.nodeId, renderKey);
1836
+ opts.onProgressLine(progressLine(node, isParked));
559
1837
  }
560
1838
  },
561
1839
  });
1840
+ const terminalRun = !pollResult.timedOut &&
1841
+ isRecord(pollResult.data) &&
1842
+ typeof pollResult.data["_id"] === "string"
1843
+ ? pollResult.data
1844
+ : undefined;
1845
+ const saved = opts.out !== undefined && terminalRun
1846
+ ? await saveDeliveries(terminalRun, opts.out, deps)
1847
+ : undefined;
562
1848
  if (opts.json) {
563
1849
  return {
564
1850
  code: pollResult.ok ? 0 : 1,
565
- lines: [JSON.stringify({ ...base, result: pollResult.data, timedOut: pollResult.timedOut })],
1851
+ lines: [
1852
+ JSON.stringify({
1853
+ ...opts.jsonBase,
1854
+ result: pollResult.data,
1855
+ timedOut: pollResult.timedOut,
1856
+ ...(saved ? { saved: saved.paths } : {}),
1857
+ }),
1858
+ ],
566
1859
  };
567
1860
  }
568
1861
  if (pollResult.timedOut) {
569
- lines.push(`Timed out waiting. Check later: exodus workflow status --id ${data.runId}`);
570
- return { code: 1, lines };
1862
+ return {
1863
+ code: 1,
1864
+ lines: [`Timed out waiting. Check later: exodus workflow status --id ${runId}`],
1865
+ };
571
1866
  }
572
- lines.push("");
573
- if (isRecord(pollResult.data) && typeof pollResult.data["_id"] === "string") {
574
- lines.push(formatWorkflowRun(pollResult.data));
1867
+ const lines = [""];
1868
+ if (terminalRun) {
1869
+ lines.push(formatWorkflowRun(terminalRun));
575
1870
  }
576
1871
  else {
577
1872
  lines.push(`Polling failed: ${JSON.stringify(pollResult.data)}`);
578
1873
  }
1874
+ if (saved)
1875
+ lines.push("", ...saved.lines);
1876
+ if (landOnPark &&
1877
+ isRecord(pollResult.data) &&
1878
+ typeof pollResult.data["status"] === "string" &&
1879
+ normalizeRunStatus(pollResult.data["status"]) === "awaiting-approval" &&
1880
+ pollResult.data["pauseReason"] === landOnPark.pauseReason) {
1881
+ const dashboardUrl = deps.dashboardUrl ?? getDashboardUrl();
1882
+ lines.push("", landOnPark.headline, ...formatPauseNotice(landOnPark.pauseReason, runId, dashboardUrl).slice(1));
1883
+ }
579
1884
  return { code: pollResult.ok ? 0 : 1, lines };
580
1885
  }
581
1886
  export async function statusFlow(opts, deps) {
1887
+ if (opts.out !== undefined && !opts.id) {
1888
+ return {
1889
+ code: 1,
1890
+ lines: [
1891
+ "--out saves ONE run's outputs, so it needs the run: exodus workflow status --id <runId> --out <dir>",
1892
+ ],
1893
+ };
1894
+ }
582
1895
  const path = opts.id ? `${STATUS_PATH}?runId=${encodeURIComponent(opts.id)}` : STATUS_PATH;
583
1896
  const res = await deps.get(path);
584
1897
  if (!res.ok)
585
1898
  return asErrorResult(res, opts.json);
586
- if (opts.json)
587
- return { code: 0, lines: [JSON.stringify(res.data)] };
588
- if (opts.id)
589
- return { code: 0, lines: [formatWorkflowRun(res.data)] };
1899
+ const saved = opts.out !== undefined && opts.id
1900
+ ? await saveDeliveries(res.data, opts.out, deps)
1901
+ : undefined;
1902
+ if (opts.json) {
1903
+ const payload = saved ? { ...res.data, saved: saved.paths } : res.data;
1904
+ return { code: 0, lines: [JSON.stringify(payload)] };
1905
+ }
1906
+ if (opts.id) {
1907
+ const lines = [formatWorkflowRun(res.data)];
1908
+ if (saved)
1909
+ lines.push("", ...saved.lines);
1910
+ return { code: 0, lines };
1911
+ }
590
1912
  const runs = (res.data.runs ?? []);
591
1913
  return { code: 0, lines: [formatRecentRuns(runs)] };
592
1914
  }
@@ -596,36 +1918,81 @@ export async function exportFlow(workflowRef, opts, deps) {
596
1918
  workflowId = await resolveWorkflowId(workflowRef, deps);
597
1919
  }
598
1920
  catch (e) {
599
- return { code: 1, lines: [e instanceof Error ? e.message : String(e)] };
1921
+ return resolveIdErrorResult(e, opts.json ?? false);
600
1922
  }
601
- const res = await deps.get(`${EXPORT_PATH}?id=${encodeURIComponent(workflowId)}`);
1923
+ const versionParam = opts.version !== undefined ? `&version=${encodeURIComponent(String(opts.version))}` : "";
1924
+ const res = await deps.get(`${EXPORT_PATH}?id=${encodeURIComponent(workflowId)}${versionParam}`);
602
1925
  if (!res.ok)
603
1926
  return asErrorResult(res, false);
604
- const doc = JSON.stringify(res.data, null, 2);
1927
+ const doc = opts.json
1928
+ ? JSON.stringify(res.data, null, 2)
1929
+ : workflowToYaml(res.data);
605
1930
  if (opts.out) {
606
- deps.writeFile(opts.out, `${doc}\n`);
1931
+ const text = doc.endsWith("\n") ? doc : `${doc}\n`;
1932
+ deps.writeFile(opts.out, text);
607
1933
  return { code: 0, lines: [`Wrote workflow contract to ${opts.out}.`] };
608
1934
  }
609
- return { code: 0, lines: [doc] };
1935
+ return { code: 0, lines: [doc.endsWith("\n") ? doc.slice(0, -1) : doc] };
610
1936
  }
611
- export async function importFlow(file, opts, deps) {
1937
+ export function parseVersionFlag(flags) {
1938
+ const raw = flags["version"];
1939
+ if (raw === undefined)
1940
+ return undefined;
1941
+ if (typeof raw !== "string")
1942
+ throw new Error("--version requires a positive integer");
1943
+ const n = Number(raw);
1944
+ if (!Number.isInteger(n) || n < 1) {
1945
+ throw new Error(`--version must be a positive integer (got "${raw}")`);
1946
+ }
1947
+ return n;
1948
+ }
1949
+ export async function versionsFlow(workflowRef, opts, deps, channel = getChannel()) {
1950
+ let workflowId;
1951
+ try {
1952
+ workflowId = await resolveWorkflowId(workflowRef, deps);
1953
+ }
1954
+ catch (e) {
1955
+ return resolveIdErrorResult(e, opts.json ?? false);
1956
+ }
1957
+ const res = await deps.get(`${VERSIONS_PATH}?id=${encodeURIComponent(workflowId)}`);
1958
+ const unsupported = missingRouteLine(res, "workflow versions", channel);
1959
+ if (unsupported)
1960
+ return { code: 1, lines: [unsupported] };
1961
+ if (!res.ok)
1962
+ return asErrorResult(res, opts.json);
1963
+ if (opts.json)
1964
+ return { code: 0, lines: [JSON.stringify(res.data)] };
1965
+ const body = res.data;
1966
+ const versions = Array.isArray(body)
1967
+ ? body
1968
+ : (body.versions ?? []);
1969
+ return { code: 0, lines: [formatWorkflowVersions(versions)] };
1970
+ }
1971
+ function buildImportBody(file, opts, deps) {
612
1972
  let text;
613
1973
  try {
614
1974
  text = deps.readFile(file);
615
1975
  }
616
1976
  catch {
617
- return { code: 1, lines: [`Error: file not found: ${file}`] };
1977
+ return { error: { code: 1, lines: [`Error: file not found: ${file}`] } };
618
1978
  }
619
1979
  let parsed;
620
1980
  try {
621
- parsed = JSON.parse(text);
1981
+ parsed = parseWorkflowText(text);
622
1982
  }
623
1983
  catch (e) {
624
- const msg = e instanceof Error ? e.message : String(e);
625
- return { code: 1, lines: [`Error: ${file} is not valid JSON: ${msg}`] };
1984
+ const raw = e instanceof Error ? e.message : String(e);
1985
+ const detail = raw.replace(/^workflow file is not valid YAML or JSON:?\s*/, "");
1986
+ const suffix = detail ? `: ${detail}` : "";
1987
+ return { error: { code: 1, lines: [`Error: ${file} is not valid YAML or JSON${suffix}`] } };
626
1988
  }
627
1989
  if (!isRecord(parsed)) {
628
- return { code: 1, lines: [`Error: ${file} is not a workflow contract (expected a JSON object).`] };
1990
+ return {
1991
+ error: {
1992
+ code: 1,
1993
+ lines: [`Error: ${file} is not a workflow contract (expected a JSON object).`],
1994
+ },
1995
+ };
629
1996
  }
630
1997
  const body = { ...parsed };
631
1998
  delete body.dryRun;
@@ -637,17 +2004,25 @@ export async function importFlow(file, opts, deps) {
637
2004
  const updatedAt = typeof parsed.updatedAt === "string" ? parsed.updatedAt : undefined;
638
2005
  if (!updatedAt) {
639
2006
  return {
640
- code: 1,
641
- lines: [
642
- `Error: ${file} has no "updatedAt" anchor, so drift can't be detected. ` +
643
- `Re-export the workflow first (exodus workflow export <id> --out ${file}) and retry --update.`,
644
- ],
2007
+ error: {
2008
+ code: 1,
2009
+ lines: [
2010
+ `Error: ${file} has no "updatedAt" anchor, so drift can't be detected. ` +
2011
+ `Re-export the workflow first (exodus workflow export <id> --out ${file}) and retry --update.`,
2012
+ ],
2013
+ },
645
2014
  };
646
2015
  }
647
2016
  body.targetWorkflowId = opts.update;
648
2017
  body.expectedUpdatedAt = updatedAt;
649
2018
  }
650
- const res = await deps.post(IMPORT_PATH, body);
2019
+ return { body };
2020
+ }
2021
+ async function runImport(file, opts, deps) {
2022
+ const built = buildImportBody(file, { dryRun: opts.dryRun, update: opts.update }, deps);
2023
+ if ("error" in built)
2024
+ return built.error;
2025
+ const res = await deps.post(IMPORT_PATH, built.body);
651
2026
  if (!res.ok) {
652
2027
  return {
653
2028
  code: 1,
@@ -661,9 +2036,737 @@ export async function importFlow(file, opts, deps) {
661
2036
  code: 0,
662
2037
  lines: opts.json
663
2038
  ? [JSON.stringify(data)]
664
- : [formatImportSummary(data, { dryRun: opts.dryRun, update: !!opts.update })],
2039
+ : [
2040
+ formatImportSummary(data, {
2041
+ dryRun: opts.dryRun,
2042
+ update: !!opts.update,
2043
+ validate: opts.validate,
2044
+ }),
2045
+ ],
2046
+ };
2047
+ }
2048
+ export function triggerExpect(t) {
2049
+ return t.type === "event"
2050
+ ? { type: "event", event: t.event }
2051
+ : { type: "cron", cron: t.cron };
2052
+ }
2053
+ function triggerDetail(t) {
2054
+ return t.type === "event" ? t.event : t.cron;
2055
+ }
2056
+ const NO_TRIGGERS = "no triggers — add them via `exodus workflow export` / `import`";
2057
+ export function formatTriggers(triggers) {
2058
+ if (triggers.length === 0)
2059
+ return NO_TRIGGERS;
2060
+ return triggers
2061
+ .map((t, i) => {
2062
+ const state = t.enabled ? "enabled" : "disabled";
2063
+ return `${i + 1} · ${t.type} · ${triggerDetail(t)} · ${state}`;
2064
+ })
2065
+ .join("\n");
2066
+ }
2067
+ function triggerErrorResult(res, verb, json) {
2068
+ const missing = missingRouteLine(res, verb);
2069
+ if (missing) {
2070
+ return {
2071
+ code: 1,
2072
+ lines: json
2073
+ ? [JSON.stringify({ ok: false, status: res.status, error: missing })]
2074
+ : [missing],
2075
+ };
2076
+ }
2077
+ return asErrorResult(res, json);
2078
+ }
2079
+ async function fetchTriggers(workflowId, deps) {
2080
+ const res = await deps.get(`${EXPORT_PATH}?id=${encodeURIComponent(workflowId)}`);
2081
+ if (!res.ok)
2082
+ return { ok: false, res };
2083
+ const triggers = res.data.triggers ?? [];
2084
+ return { ok: true, triggers };
2085
+ }
2086
+ export async function triggersListFlow(workflowRef, opts, deps) {
2087
+ let workflowId;
2088
+ try {
2089
+ workflowId = await resolveWorkflowId(workflowRef, deps);
2090
+ }
2091
+ catch (e) {
2092
+ return resolveIdErrorResult(e, opts.json ?? false);
2093
+ }
2094
+ const fetched = await fetchTriggers(workflowId, deps);
2095
+ if (!fetched.ok)
2096
+ return triggerErrorResult(fetched.res, "workflow triggers", opts.json);
2097
+ if (opts.json) {
2098
+ return {
2099
+ code: 0,
2100
+ lines: [JSON.stringify(fetched.triggers.map((t, i) => ({ n: i + 1, ...t })))],
2101
+ };
2102
+ }
2103
+ return { code: 0, lines: [formatTriggers(fetched.triggers)] };
2104
+ }
2105
+ function triggerIndexError(message, triggers, json) {
2106
+ if (json) {
2107
+ return {
2108
+ code: 1,
2109
+ lines: [JSON.stringify({ ok: false, error: message, triggers: triggers.map((t, i) => ({ n: i + 1, ...t })) })],
2110
+ };
2111
+ }
2112
+ return { code: 1, lines: [message, "", formatTriggers(triggers)] };
2113
+ }
2114
+ export async function triggersSetEnabledFlow(workflowRef, n, enabled, opts, deps) {
2115
+ const verb = `workflow triggers ${enabled ? "enable" : "disable"}`;
2116
+ let workflowId;
2117
+ try {
2118
+ workflowId = await resolveWorkflowId(workflowRef, deps);
2119
+ }
2120
+ catch (e) {
2121
+ return resolveIdErrorResult(e, opts.json ?? false);
2122
+ }
2123
+ const fetched = await fetchTriggers(workflowId, deps);
2124
+ if (!fetched.ok)
2125
+ return triggerErrorResult(fetched.res, verb, opts.json);
2126
+ const triggers = fetched.triggers;
2127
+ const idx = n - 1;
2128
+ if (idx < 0 || idx >= triggers.length) {
2129
+ return triggerIndexError(`Trigger ${n} is out of range — this workflow has ${triggers.length} trigger(s).`, triggers, opts.json);
2130
+ }
2131
+ const res = await deps.post(TRIGGERS_SET_ENABLED_PATH, {
2132
+ workflowId,
2133
+ triggerIndex: idx,
2134
+ enabled,
2135
+ expect: triggerExpect(triggers[idx]),
2136
+ });
2137
+ if (!res.ok)
2138
+ return triggerErrorResult(res, verb, opts.json);
2139
+ if (opts.json)
2140
+ return { code: 0, lines: [JSON.stringify(res.data)] };
2141
+ return { code: 0, lines: [`Trigger ${n} ${enabled ? "enabled" : "disabled"}.`] };
2142
+ }
2143
+ export async function triggersFireFlow(workflowRef, opts, deps) {
2144
+ const verb = "workflow triggers fire";
2145
+ let workflowId;
2146
+ try {
2147
+ workflowId = await resolveWorkflowId(workflowRef, deps);
2148
+ }
2149
+ catch (e) {
2150
+ return resolveIdErrorResult(e, opts.json ?? false);
2151
+ }
2152
+ const fetched = await fetchTriggers(workflowId, deps);
2153
+ if (!fetched.ok)
2154
+ return triggerErrorResult(fetched.res, verb, opts.json);
2155
+ const triggers = fetched.triggers;
2156
+ if (triggers.length === 0) {
2157
+ return { code: 1, lines: [`This workflow has no triggers. ${NO_TRIGGERS}`] };
2158
+ }
2159
+ let idx;
2160
+ if (opts.n !== undefined) {
2161
+ idx = opts.n - 1;
2162
+ if (idx < 0 || idx >= triggers.length) {
2163
+ return triggerIndexError(`Trigger ${opts.n} is out of range — this workflow has ${triggers.length} trigger(s).`, triggers, opts.json);
2164
+ }
2165
+ }
2166
+ else if (triggers.length === 1) {
2167
+ idx = 0;
2168
+ }
2169
+ else {
2170
+ return triggerIndexError(`This workflow has ${triggers.length} triggers — specify which one to fire (e.g. \`fire 1\`).`, triggers, opts.json);
2171
+ }
2172
+ const t = triggers[idx];
2173
+ const n = idx + 1;
2174
+ if (t.type === "event" && (opts.text === undefined || opts.text === "")) {
2175
+ return {
2176
+ code: 1,
2177
+ lines: [
2178
+ `Trigger ${n} fires on the "${t.event}" event — pass --text with the input this run should carry.`,
2179
+ ],
2180
+ };
2181
+ }
2182
+ if (t.type === "cron" && opts.text !== undefined) {
2183
+ return {
2184
+ code: 1,
2185
+ lines: [`Trigger ${n} is a cron trigger ("${t.cron}") — it takes no --text.`],
2186
+ };
2187
+ }
2188
+ const res = await deps.post(TRIGGERS_FIRE_PATH, {
2189
+ workflowId,
2190
+ triggerIndex: idx,
2191
+ expect: triggerExpect(t),
2192
+ ...(opts.text !== undefined ? { text: opts.text } : {}),
2193
+ ...(opts.imageRigOverrides
2194
+ ? { imageRigOverrides: opts.imageRigOverrides }
2195
+ : {}),
2196
+ });
2197
+ if (!res.ok)
2198
+ return triggerErrorResult(res, verb, opts.json);
2199
+ const runId = res.data.runId;
2200
+ const base = { runId, workflowId };
2201
+ if (!opts.wait) {
2202
+ if (opts.json)
2203
+ return { code: 0, lines: [JSON.stringify(base)] };
2204
+ return {
2205
+ code: 0,
2206
+ lines: [
2207
+ `Trigger ${n} fired.`,
2208
+ `runId: ${runId}`,
2209
+ "This run executes as the workflow OWNER in the background.",
2210
+ `Poll: exodus workflow status --id ${runId}`,
2211
+ ],
2212
+ };
2213
+ }
2214
+ const startLines = [
2215
+ `Trigger ${n} fired.`,
2216
+ `runId: ${runId}`,
2217
+ "This run executes as the workflow OWNER in the background.",
2218
+ `Poll: exodus workflow status --id ${runId}`,
2219
+ ];
2220
+ if (!opts.json && opts.onProgressLine) {
2221
+ for (const line of startLines)
2222
+ opts.onProgressLine(line);
2223
+ }
2224
+ const waited = await waitForRun(runId, { json: opts.json, onProgressLine: opts.onProgressLine, jsonBase: base }, deps);
2225
+ if (opts.json)
2226
+ return waited;
2227
+ const prefix = opts.onProgressLine ? [] : startLines;
2228
+ return { code: waited.code, lines: [...prefix, ...waited.lines] };
2229
+ }
2230
+ export async function importFlow(file, opts, deps) {
2231
+ return runImport(file, opts, deps);
2232
+ }
2233
+ export async function validateFlow(file, opts, deps) {
2234
+ return runImport(file, { dryRun: true, json: opts.json, update: opts.update, validate: true }, deps);
2235
+ }
2236
+ export async function templatesListFlow(json, deps) {
2237
+ const res = await deps.get(TEMPLATES_PATH);
2238
+ if (!res.ok) {
2239
+ const missing = missingRouteLine(res, "workflow templates");
2240
+ if (missing)
2241
+ return { code: 1, lines: [missing] };
2242
+ return asErrorResult(res, json);
2243
+ }
2244
+ const data = res.data;
2245
+ if (json)
2246
+ return { code: 0, lines: [JSON.stringify(data)] };
2247
+ return { code: 0, lines: [formatTemplatesList(data.templates ?? [])] };
2248
+ }
2249
+ export async function templatesExportFlow(key, opts, deps) {
2250
+ const query = opts.json
2251
+ ? `?key=${encodeURIComponent(key)}&format=json`
2252
+ : `?key=${encodeURIComponent(key)}`;
2253
+ const res = await deps.getText(`${TEMPLATES_PATH}${query}`);
2254
+ if (!res.ok) {
2255
+ let parsedBody = res.data;
2256
+ try {
2257
+ parsedBody = JSON.parse(res.data);
2258
+ }
2259
+ catch {
2260
+ }
2261
+ const missing = missingRouteLine({ ...res, data: parsedBody }, "workflow templates export");
2262
+ if (missing)
2263
+ return { code: 1, lines: [missing] };
2264
+ return { code: 1, lines: [formatTextError(res)] };
2265
+ }
2266
+ const doc = res.data;
2267
+ if (opts.out) {
2268
+ const text = doc.endsWith("\n") ? doc : `${doc}\n`;
2269
+ deps.writeFile(opts.out, text);
2270
+ return { code: 0, lines: [`Wrote template "${key}" to ${opts.out}.`] };
2271
+ }
2272
+ return { code: 0, lines: [doc.endsWith("\n") ? doc.slice(0, -1) : doc] };
2273
+ }
2274
+ function formatTextError(res) {
2275
+ const body = res.data;
2276
+ let parsed;
2277
+ try {
2278
+ parsed = JSON.parse(body);
2279
+ }
2280
+ catch {
2281
+ const snippet = body.replace(/\s+/g, " ").trim().slice(0, 300);
2282
+ return formatApiError({ ok: false, status: res.status, data: snippet || "(empty response)" });
2283
+ }
2284
+ return formatApiError({ ok: false, status: res.status, data: parsed });
2285
+ }
2286
+ export async function schemaFlow(opts, deps) {
2287
+ const res = await deps.get(SCHEMA_PATH);
2288
+ if (!res.ok) {
2289
+ const missing = missingRouteLine(res, "workflow schema");
2290
+ if (missing)
2291
+ return { code: 1, lines: [missing] };
2292
+ return asErrorResult(res, opts.json);
2293
+ }
2294
+ if (opts.json)
2295
+ return { code: 0, lines: [JSON.stringify(res.data)] };
2296
+ const payload = isRecord(res.data) ? res.data : {};
2297
+ if (opts.kind !== undefined) {
2298
+ return formatSchemaFilter(payload, ["nodeKinds"], "kind", opts.kind);
2299
+ }
2300
+ if (opts.face !== undefined) {
2301
+ return formatSchemaFilter(payload, ["transformFaces"], "face", opts.face);
2302
+ }
2303
+ return { code: 0, lines: [formatSchema(payload)] };
2304
+ }
2305
+ export function formatAge(value, now = Date.now()) {
2306
+ if (value === undefined || value === null)
2307
+ return "-";
2308
+ const t = typeof value === "number" ? value : Date.parse(value);
2309
+ if (Number.isNaN(t))
2310
+ return "-";
2311
+ const sec = Math.max(0, Math.floor((now - t) / 1000));
2312
+ if (sec < 60)
2313
+ return `${sec}s`;
2314
+ const min = Math.floor(sec / 60);
2315
+ if (min < 60)
2316
+ return `${min}m`;
2317
+ const hr = Math.floor(min / 60);
2318
+ if (hr < 24)
2319
+ return `${hr}h`;
2320
+ return `${Math.floor(hr / 24)}d`;
2321
+ }
2322
+ export function parkBadge(pauseReason) {
2323
+ if (pauseReason === "taste")
2324
+ return "gate";
2325
+ if (pauseReason === "repair")
2326
+ return "repair";
2327
+ if (pauseReason === "slots")
2328
+ return "slots";
2329
+ if (pauseReason === "checkpoint")
2330
+ return "checkpoint";
2331
+ return "legacy";
2332
+ }
2333
+ export function invocationBadge(row) {
2334
+ if (row.triggeredBy)
2335
+ return `trig:${row.triggeredBy.event ?? row.triggeredBy.type}`;
2336
+ if (row.invocationMode === "background")
2337
+ return "bg";
2338
+ return "";
2339
+ }
2340
+ const NO_INBOX = "Nothing waiting on you — the review inbox is empty.";
2341
+ export function formatInbox(rows, now = Date.now()) {
2342
+ if (rows.length === 0)
2343
+ return NO_INBOX;
2344
+ return table(["run", "workflow", "kind", "node", "via", "age"], rows.map((r) => [
2345
+ r._id,
2346
+ r.workflowName || "(unnamed)",
2347
+ parkBadge(r.pauseReason),
2348
+ r.pausedNodeId ?? "-",
2349
+ invocationBadge(r) || "-",
2350
+ formatAge(r.createdAt, now),
2351
+ ]));
2352
+ }
2353
+ export async function inboxFlow(json, deps) {
2354
+ const res = await deps.get(INBOX_PATH);
2355
+ if (!res.ok)
2356
+ return triggerErrorResult(res, "workflow inbox", json);
2357
+ const data = res.data;
2358
+ const rows = data.runs ?? [];
2359
+ return { code: 0, lines: json ? [JSON.stringify(rows)] : [formatInbox(rows)] };
2360
+ }
2361
+ function errLine(message, json, status) {
2362
+ return {
2363
+ code: 1,
2364
+ lines: [
2365
+ json
2366
+ ? JSON.stringify({ ok: false, ...(status ? { status } : {}), error: message })
2367
+ : message,
2368
+ ],
665
2369
  };
666
2370
  }
2371
+ function okLine(message, payload, json) {
2372
+ return { code: 0, lines: [json ? JSON.stringify(payload) : message] };
2373
+ }
2374
+ function asWorkflowRun(data) {
2375
+ return isRecord(data) && typeof data["_id"] === "string"
2376
+ ? data
2377
+ : undefined;
2378
+ }
2379
+ function describePark(run) {
2380
+ if (normalizeRunStatus(run.status) !== "awaiting-approval") {
2381
+ return `status: ${runStatusLabel(run.status)}`;
2382
+ }
2383
+ switch (run.pauseReason) {
2384
+ case "taste":
2385
+ return "parked at a Gate box, which retired in 2.0 (cancel and re-run)";
2386
+ case "repair":
2387
+ return "parked for repair";
2388
+ case "slots":
2389
+ return "parked for slot answers";
2390
+ case "call":
2391
+ return "parked on a child workflow";
2392
+ case "checkpoint":
2393
+ return `parked at a checkpoint (use: exodus workflow checkpoint ${run._id})`;
2394
+ default:
2395
+ return "parked at the cost gate (legacy)";
2396
+ }
2397
+ }
2398
+ const PARK_LABEL = {
2399
+ taste: "a retired Gate review",
2400
+ repair: "a repair",
2401
+ slots: "slot answers",
2402
+ call: "a child workflow",
2403
+ checkpoint: "a checkpoint approval",
2404
+ };
2405
+ async function preflightPark(runId, expected, verb, json, deps) {
2406
+ const res = await deps.get(`${STATUS_PATH}?runId=${encodeURIComponent(runId)}`);
2407
+ if (!res.ok)
2408
+ return { ok: false, result: triggerErrorResult(res, verb, json) };
2409
+ const run = asWorkflowRun(res.data);
2410
+ if (!run) {
2411
+ return { ok: false, result: errLine(`Could not read run ${runId}.`, json) };
2412
+ }
2413
+ const allowed = Array.isArray(expected)
2414
+ ? expected
2415
+ : [expected];
2416
+ if (normalizeRunStatus(run.status) !== "awaiting-approval" ||
2417
+ run.pauseReason === undefined ||
2418
+ !allowed.includes(run.pauseReason)) {
2419
+ return {
2420
+ ok: false,
2421
+ result: errLine(`Run ${runId} is not parked for ${PARK_LABEL[allowed[0]]} — it is ${describePark(run)}.`, json),
2422
+ };
2423
+ }
2424
+ return { ok: true, run };
2425
+ }
2426
+ function checkpointOutputs(run) {
2427
+ const node = (run.nodes ?? []).find((x) => x.nodeId === run.pausedNodeId);
2428
+ if (!node)
2429
+ return [];
2430
+ const out = [];
2431
+ let n = 0;
2432
+ (node.outputs ?? []).forEach((a, idx) => {
2433
+ if (a.type !== "text")
2434
+ return;
2435
+ n += 1;
2436
+ out.push({
2437
+ n,
2438
+ outputIndex: idx,
2439
+ text: a.text,
2440
+ label: a.label,
2441
+ humanEdited: !!a.humanEdited,
2442
+ ...(a.item ? { item: a.item } : {}),
2443
+ });
2444
+ });
2445
+ return out;
2446
+ }
2447
+ function checkpointItemIndexes(outputs) {
2448
+ const seen = new Set();
2449
+ for (const o of outputs)
2450
+ if (o.item)
2451
+ seen.add(o.item.index);
2452
+ return [...seen].sort((a, b) => a - b);
2453
+ }
2454
+ function checkpointNode(run) {
2455
+ return (run.nodes ?? []).find((x) => x.nodeId === run.pausedNodeId);
2456
+ }
2457
+ function checkpointOutputRow(o, indent) {
2458
+ const label = o.label ? ` [${o.label}]` : "";
2459
+ const edited = o.humanEdited ? " (edited)" : "";
2460
+ return `${indent}${o.n}.${label} ${truncateText(o.text, 200)}${edited}`;
2461
+ }
2462
+ function formatCheckpointOutputs(outputs) {
2463
+ if (outputs.length === 0)
2464
+ return " (this step produced no text to review)";
2465
+ const indexes = checkpointItemIndexes(outputs);
2466
+ if (indexes.length === 0) {
2467
+ return outputs.map((o) => checkpointOutputRow(o, " ")).join("\n");
2468
+ }
2469
+ const lines = [];
2470
+ for (const index of indexes) {
2471
+ const rows = outputs.filter((o) => o.item?.index === index);
2472
+ const total = rows[0]?.item?.total ?? indexes.length;
2473
+ lines.push(` Item ${index + 1} of ${total}`);
2474
+ for (const row of rows)
2475
+ lines.push(checkpointOutputRow(row, " "));
2476
+ }
2477
+ const shared = outputs.filter((o) => !o.item);
2478
+ if (shared.length > 0) {
2479
+ lines.push(" Not tied to an item");
2480
+ for (const row of shared)
2481
+ lines.push(checkpointOutputRow(row, " "));
2482
+ }
2483
+ return lines.join("\n");
2484
+ }
2485
+ function checkpointRangeError(num, count, json) {
2486
+ const range = count > 0 ? ` (valid: 1–${count})` : "";
2487
+ return errLine(`Output ${num} is out of range — this step has ${count} text output${count === 1 ? "" : "s"}${range}.`, json);
2488
+ }
2489
+ export async function checkpointShowFlow(runId, opts, deps) {
2490
+ const pf = await preflightPark(runId, "checkpoint", "workflow checkpoint", opts.json, deps);
2491
+ if (!pf.ok)
2492
+ return pf.result;
2493
+ const outputs = checkpointOutputs(pf.run);
2494
+ const node = checkpointNode(pf.run);
2495
+ const itemIndexes = checkpointItemIndexes(outputs);
2496
+ if (opts.json) {
2497
+ return {
2498
+ code: 0,
2499
+ lines: [
2500
+ JSON.stringify({
2501
+ runId,
2502
+ pausedNodeId: pf.run.pausedNodeId,
2503
+ pausedNodeKind: node?.kind,
2504
+ ...(node?.botSlug ? { botSlug: node.botSlug } : {}),
2505
+ ...(itemIndexes.length > 0 ? { itemIndexes } : {}),
2506
+ outputs: outputs.map((o) => ({
2507
+ n: o.n,
2508
+ text: o.text,
2509
+ ...(o.label ? { label: o.label } : {}),
2510
+ humanEdited: o.humanEdited,
2511
+ ...(o.item ? { item: o.item } : {}),
2512
+ })),
2513
+ }),
2514
+ ],
2515
+ };
2516
+ }
2517
+ const stepLabel = node
2518
+ ? `${node.nodeId} (${node.botSlug ? `${node.kind}: ${node.botSlug}` : node.kind})`
2519
+ : (pf.run.pausedNodeId ?? "-");
2520
+ const itemsNote = itemIndexes.length > 0
2521
+ ? [
2522
+ `This step ran once per item (${itemIndexes.length} of them). Approve keeps every item;`,
2523
+ "reject drops the ones you name and the run carries on with the rest.",
2524
+ "",
2525
+ ]
2526
+ : [];
2527
+ const rejectLine = itemIndexes.length > 0
2528
+ ? [`Reject: exodus workflow checkpoint ${runId} approve --reject 2 --wait`]
2529
+ : [];
2530
+ return {
2531
+ code: 0,
2532
+ lines: [
2533
+ `Checkpoint — ${pf.run.workflowName}`,
2534
+ `runId: ${runId}`,
2535
+ `step: ${stepLabel}`,
2536
+ "",
2537
+ "The run is holding at this checkpoint until you say go.",
2538
+ "",
2539
+ ...itemsNote,
2540
+ `Its output (${outputs.length}):`,
2541
+ formatCheckpointOutputs(outputs),
2542
+ "",
2543
+ `Approve: exodus workflow checkpoint ${runId} approve --wait`,
2544
+ ...rejectLine,
2545
+ `Edit: exodus workflow checkpoint ${runId} edit 1 --text "..."`,
2546
+ `Redo: exodus workflow checkpoint ${runId} retry --wait`,
2547
+ `Cancel: exodus workflow checkpoint ${runId} cancel --reason "..."`,
2548
+ ],
2549
+ };
2550
+ }
2551
+ export function parseRejectItems(raw) {
2552
+ const bad = (why) => ({
2553
+ ok: false,
2554
+ message: `${why} --reject takes the item numbers you see in "checkpoint show", like --reject 2 or --reject 2,5.`,
2555
+ });
2556
+ if (raw === undefined || raw.trim() === "")
2557
+ return bad("--reject needs at least one item number.");
2558
+ const parts = raw
2559
+ .split(",")
2560
+ .map((s) => s.trim())
2561
+ .filter((s) => s.length > 0);
2562
+ if (parts.length === 0)
2563
+ return bad("--reject needs at least one item number.");
2564
+ const items = [];
2565
+ for (const part of parts) {
2566
+ if (!/^\d+$/.test(part))
2567
+ return bad(`"${part}" isn't an item number.`);
2568
+ const n = Number(part);
2569
+ if (n < 1)
2570
+ return bad("Items are numbered from 1.");
2571
+ if (!items.includes(n))
2572
+ items.push(n);
2573
+ }
2574
+ return { ok: true, items: items.sort((a, b) => a - b) };
2575
+ }
2576
+ export async function checkpointApproveFlow(runId, opts, deps) {
2577
+ let rejectItems;
2578
+ if (opts.reject !== undefined) {
2579
+ const parsed = parseRejectItems(opts.reject);
2580
+ if (!parsed.ok)
2581
+ return errLine(parsed.message, opts.json);
2582
+ rejectItems = parsed.items;
2583
+ }
2584
+ const pf = await preflightPark(runId, "checkpoint", "workflow checkpoint approve", opts.json, deps);
2585
+ if (!pf.ok)
2586
+ return pf.result;
2587
+ if (rejectItems === undefined) {
2588
+ const res = await deps.post(APPROVE_PATH, { runId });
2589
+ if (!res.ok)
2590
+ return triggerErrorResult(res, "workflow checkpoint approve", opts.json);
2591
+ const triggerRunId = res.data.triggerRunId;
2592
+ return resumeAndMaybeWait(runId, triggerRunId, ["Checkpoint approved — the run resumes."], opts, deps);
2593
+ }
2594
+ const rejections = rejectItems.map((n) => n - 1);
2595
+ const res = await deps.post(CHECKPOINT_RESOLVE_ITEMS_PATH, { runId, rejections });
2596
+ if (!res.ok)
2597
+ return triggerErrorResult(res, "workflow checkpoint approve", opts.json);
2598
+ const data = (res.data ?? {});
2599
+ const rejected = (data.rejected ?? rejections).map((i) => i + 1).sort((a, b) => a - b);
2600
+ const kept = data.remaining ?? 0;
2601
+ const total = kept + rejected.length;
2602
+ return resumeAndMaybeWait(runId, data.triggerRunId, [`Approved — kept ${kept} of ${total} items (rejected: ${rejected.join(", ")}).`], opts, deps, undefined, { rejected, remaining: kept });
2603
+ }
2604
+ export async function checkpointEditFlow(runId, n, sources, opts, deps) {
2605
+ const provided = [sources.text, sources.file, sources.stdin].filter((x) => x !== undefined);
2606
+ if (provided.length === 0) {
2607
+ return errLine("Provide the replacement text via one of --text, --file <path>, or piped stdin.", opts.json);
2608
+ }
2609
+ if (provided.length > 1) {
2610
+ return errLine("Provide the replacement text via exactly one of --text, --file, or stdin — not several.", opts.json);
2611
+ }
2612
+ let text;
2613
+ if (sources.text !== undefined) {
2614
+ text = sources.text;
2615
+ }
2616
+ else if (sources.file !== undefined) {
2617
+ try {
2618
+ text = deps.readFile(sources.file);
2619
+ }
2620
+ catch (e) {
2621
+ const msg = e instanceof Error ? e.message : String(e);
2622
+ return errLine(`Could not read file "${sources.file}": ${msg}`, opts.json);
2623
+ }
2624
+ }
2625
+ else {
2626
+ text = sources.stdin;
2627
+ }
2628
+ const pf = await preflightPark(runId, "checkpoint", "workflow checkpoint edit", opts.json, deps);
2629
+ if (!pf.ok)
2630
+ return pf.result;
2631
+ const outputs = checkpointOutputs(pf.run);
2632
+ const target = outputs.find((o) => o.n === n);
2633
+ if (!target)
2634
+ return checkpointRangeError(n, outputs.length, opts.json);
2635
+ const res = await deps.post(CHECKPOINT_EDIT_PATH, {
2636
+ runId,
2637
+ nodeId: pf.run.pausedNodeId,
2638
+ outputIndex: target.outputIndex,
2639
+ text,
2640
+ });
2641
+ if (!res.ok)
2642
+ return triggerErrorResult(res, "workflow checkpoint edit", opts.json);
2643
+ return okLine(`Edited output ${n} at ${pf.run.pausedNodeId}. Approve to continue: exodus workflow checkpoint ${runId} approve --wait`, { ok: true, runId, nodeId: pf.run.pausedNodeId, outputIndex: target.outputIndex }, opts.json);
2644
+ }
2645
+ export async function checkpointRetryFlow(runId, opts, deps) {
2646
+ const pf = await preflightPark(runId, "checkpoint", "workflow checkpoint retry", opts.json, deps);
2647
+ if (!pf.ok)
2648
+ return pf.result;
2649
+ const note = opts.note?.trim();
2650
+ const res = await deps.post(CHECKPOINT_RETRY_PATH, {
2651
+ runId,
2652
+ ...(note ? { note } : {}),
2653
+ });
2654
+ if (!res.ok)
2655
+ return triggerErrorResult(res, "workflow checkpoint retry", opts.json);
2656
+ const triggerRunId = res.data.triggerRunId;
2657
+ return resumeAndMaybeWait(runId, triggerRunId, ["Redoing the step that feeds this checkpoint — its old output is discarded."], opts, deps, {
2658
+ pauseReason: "checkpoint",
2659
+ headline: " ⏸ The step re-ran — its fresh output is waiting on your approval.",
2660
+ });
2661
+ }
2662
+ export async function checkpointCancelFlow(runId, opts, deps) {
2663
+ const pf = await preflightPark(runId, ["checkpoint", "taste"], "workflow checkpoint cancel", opts.json, deps);
2664
+ if (!pf.ok)
2665
+ return pf.result;
2666
+ const res = await deps.post(CANCEL_PATH, {
2667
+ runId,
2668
+ ...(opts.reason !== undefined ? { reason: opts.reason } : {}),
2669
+ });
2670
+ if (!res.ok)
2671
+ return triggerErrorResult(res, "workflow checkpoint cancel", opts.json);
2672
+ return okLine(`Checkpoint canceled — run ${runId} stopped.`, { ok: true, runId }, opts.json);
2673
+ }
2674
+ export async function repairFlow(runId, action, opts, deps) {
2675
+ const verb = `workflow repair ${action}`;
2676
+ const pf = await preflightPark(runId, "repair", verb, opts.json, deps);
2677
+ if (!pf.ok)
2678
+ return pf.result;
2679
+ if (action === "kill") {
2680
+ const res = await deps.post(CANCEL_PATH, { runId });
2681
+ if (!res.ok)
2682
+ return triggerErrorResult(res, verb, opts.json);
2683
+ return okLine(`Repair killed — run ${runId} canceled.`, { ok: true, runId }, opts.json);
2684
+ }
2685
+ const path = action === "retry" ? REPAIR_RETRY_PATH : REPAIR_SKIP_PATH;
2686
+ const res = await deps.post(path, { runId });
2687
+ if (!res.ok)
2688
+ return triggerErrorResult(res, verb, opts.json);
2689
+ const triggerRunId = res.data.triggerRunId;
2690
+ return resumeAndMaybeWait(runId, triggerRunId, [`Repair ${action} started — the run resumes.`], opts, deps);
2691
+ }
2692
+ async function resumeAndMaybeWait(runId, triggerRunId, headline, opts, deps, landOnPark, extraJson) {
2693
+ const base = { runId, triggerRunId, ...(extraJson ?? {}) };
2694
+ const startLines = [
2695
+ ...headline,
2696
+ `runId: ${runId}`,
2697
+ `triggerRunId: ${triggerRunId ?? "-"}`,
2698
+ `Poll: exodus workflow status --id ${runId}`,
2699
+ ];
2700
+ if (!opts.wait) {
2701
+ if (opts.json)
2702
+ return { code: 0, lines: [JSON.stringify(base)] };
2703
+ return { code: 0, lines: startLines };
2704
+ }
2705
+ if (!opts.json && opts.onProgressLine) {
2706
+ for (const line of startLines)
2707
+ opts.onProgressLine(line);
2708
+ }
2709
+ const waited = await waitForRun(runId, {
2710
+ json: opts.json,
2711
+ onProgressLine: opts.onProgressLine,
2712
+ jsonBase: base,
2713
+ ...(landOnPark ? { landOnPark } : {}),
2714
+ }, deps);
2715
+ if (opts.json)
2716
+ return waited;
2717
+ const prefix = opts.onProgressLine ? [] : startLines;
2718
+ return { code: waited.code, lines: [...prefix, ...waited.lines] };
2719
+ }
2720
+ export function parseSlotFlags(args) {
2721
+ const values = {};
2722
+ for (let i = 0; i < args.length; i++) {
2723
+ const arg = args[i];
2724
+ let raw;
2725
+ if (arg === "--slot") {
2726
+ raw = args[i + 1];
2727
+ i++;
2728
+ }
2729
+ else if (arg.startsWith("--slot=")) {
2730
+ raw = arg.slice("--slot=".length);
2731
+ }
2732
+ else {
2733
+ continue;
2734
+ }
2735
+ if (!raw)
2736
+ throw new Error("--slot requires key=value");
2737
+ const eq = raw.indexOf("=");
2738
+ if (eq <= 0)
2739
+ throw new Error(`--slot must be key=value (got "${raw}")`);
2740
+ const key = raw.slice(0, eq).trim();
2741
+ if (!key)
2742
+ throw new Error(`--slot must include a key (got "${raw}")`);
2743
+ values[key] = raw.slice(eq + 1);
2744
+ }
2745
+ return values;
2746
+ }
2747
+ export async function answerFlow(runId, values, opts, deps) {
2748
+ const pf = await preflightPark(runId, "slots", "workflow answer", opts.json, deps);
2749
+ if (!pf.ok)
2750
+ return pf.result;
2751
+ const pending = pf.run.pendingSlots ?? [];
2752
+ if (Object.keys(values).length === 0) {
2753
+ if (opts.json) {
2754
+ return { code: 0, lines: [JSON.stringify({ runId, pendingSlots: pending })] };
2755
+ }
2756
+ const lines = [`Run ${runId} is waiting on ${pending.length} slot answer(s):`];
2757
+ for (const s of pending) {
2758
+ const label = s.label ? ` — ${s.label}` : "";
2759
+ const hint = s.hint ? ` (${s.hint})` : "";
2760
+ lines.push(` ${s.id}${label}${hint}`);
2761
+ }
2762
+ lines.push("", `Answer: exodus workflow answer ${runId} --slot ${pending[0]?.id ?? "key"}=value`);
2763
+ return { code: 0, lines };
2764
+ }
2765
+ const res = await deps.post(ANSWER_PATH, { runId, values });
2766
+ if (!res.ok)
2767
+ return triggerErrorResult(res, "workflow answer", opts.json);
2768
+ return okLine(`Answered ${Object.keys(values).length} slot(s) for run ${runId} — the child resumes.`, { ok: true, runId, values }, opts.json);
2769
+ }
667
2770
  function flagString(flags, name) {
668
2771
  const v = flags[name];
669
2772
  return typeof v === "string" ? v : undefined;
@@ -692,6 +2795,23 @@ async function printResult(result) {
692
2795
  if (result.code !== 0)
693
2796
  process.exit(result.code);
694
2797
  }
2798
+ async function readAllStdin() {
2799
+ const chunks = [];
2800
+ for await (const chunk of process.stdin)
2801
+ chunks.push(chunk);
2802
+ return Buffer.concat(chunks).toString("utf-8");
2803
+ }
2804
+ async function maybeReadStdin(flags) {
2805
+ if (flagString(flags, "text") !== undefined || flagString(flags, "file") !== undefined) {
2806
+ return undefined;
2807
+ }
2808
+ if (process.stdin.isTTY)
2809
+ return undefined;
2810
+ const raw = await readAllStdin();
2811
+ if (raw.length === 0)
2812
+ return undefined;
2813
+ return raw.endsWith("\n") ? raw.slice(0, -1) : raw;
2814
+ }
695
2815
  export async function run(flags) {
696
2816
  const positional = parsePositional();
697
2817
  const [sub, ...rest] = positional;
@@ -714,16 +2834,54 @@ export async function run(flags) {
714
2834
  if (sub === "bots") {
715
2835
  return printResult(await botsFlow({ category: flagString(flags, "category"), slug: flagString(flags, "slug"), json }, defaultDeps));
716
2836
  }
2837
+ if (sub === "templates") {
2838
+ const action = rest[0];
2839
+ if (!action || action === "list") {
2840
+ return printResult(await templatesListFlow(json, defaultDeps));
2841
+ }
2842
+ if (action === "export") {
2843
+ const key = rest[1];
2844
+ if (!key) {
2845
+ console.error("Error: workflow templates export requires <key>.");
2846
+ console.log("Usage: exodus workflow templates export <key> [--out <file>] [--json]");
2847
+ process.exit(1);
2848
+ }
2849
+ return printResult(await templatesExportFlow(key, { out: flagString(flags, "out"), json }, defaultDeps));
2850
+ }
2851
+ console.error(`Unknown templates action: "${action}"`);
2852
+ console.log("Usage: exodus workflow templates [list] | exodus workflow templates export <key>");
2853
+ process.exit(1);
2854
+ }
2855
+ if (sub === "schema") {
2856
+ return printResult(await schemaFlow({ json, kind: flagString(flags, "kind"), face: flagString(flags, "face") }, defaultDeps));
2857
+ }
2858
+ if (sub === "validate") {
2859
+ const file = rest[0];
2860
+ if (!file) {
2861
+ console.error("Error: workflow validate requires <file>.");
2862
+ console.log("Usage: exodus workflow validate <file> [--update <workflowId>] [--json]");
2863
+ process.exit(1);
2864
+ }
2865
+ return printResult(await validateFlow(file, { json, update: flagString(flags, "update") }, defaultDeps));
2866
+ }
717
2867
  if (sub === "run") {
718
2868
  const workflowRef = rest[0];
719
2869
  if (!workflowRef) {
720
2870
  console.error("Error: workflow run requires <workflowId|name>.");
721
- console.log("Usage: exodus workflow run <workflowId|name> [--input key=value ...] [--wait] [--json]");
2871
+ console.log("Usage: exodus workflow run <workflowId|name> [--fill <name>] [--input key=value ...] [--input <fileField>=./path/to/file ...] [--auto-approve] [--wait] [--json]");
722
2872
  process.exit(1);
723
2873
  }
724
2874
  let inputs;
2875
+ let terminalNodeIds;
2876
+ let fill;
2877
+ let autoApprove;
2878
+ let imageRigOverrides;
725
2879
  try {
726
- inputs = parseInputFlags(process.argv.slice(3), defaultDeps.readFile);
2880
+ inputs = parseRawInputFlags(process.argv.slice(3));
2881
+ terminalNodeIds = parseTerminalFlags(process.argv.slice(3));
2882
+ fill = parseFillFlag(process.argv.slice(3));
2883
+ autoApprove = parseAutoApproveFlag(process.argv.slice(3));
2884
+ imageRigOverrides = parseRigOverridesFlag(process.argv.slice(3), defaultDeps.readFile);
727
2885
  }
728
2886
  catch (e) {
729
2887
  console.error(`Error: ${e instanceof Error ? e.message : String(e)}`);
@@ -731,22 +2889,45 @@ export async function run(flags) {
731
2889
  }
732
2890
  return printResult(await runFlow(workflowRef, {
733
2891
  inputs,
2892
+ terminalNodeIds,
2893
+ fill,
2894
+ autoApprove,
2895
+ imageRigOverrides,
734
2896
  wait: flags["wait"] === true,
735
2897
  json,
2898
+ out: flagString(flags, "out"),
736
2899
  onProgressLine: (line) => console.log(line),
2900
+ onWarningLine: (line) => console.error(line),
737
2901
  }, defaultDeps));
738
2902
  }
739
2903
  if (sub === "status") {
740
- return printResult(await statusFlow({ id: flagString(flags, "id"), json }, defaultDeps));
2904
+ return printResult(await statusFlow({ id: flagString(flags, "id"), json, out: flagString(flags, "out") }, defaultDeps));
2905
+ }
2906
+ if (sub === "versions") {
2907
+ const workflowRef = rest[0];
2908
+ if (!workflowRef) {
2909
+ console.error("Error: workflow versions requires <workflowId|name>.");
2910
+ console.log("Usage: exodus workflow versions <workflowId|name> [--json]");
2911
+ process.exit(1);
2912
+ }
2913
+ return printResult(await versionsFlow(workflowRef, { json }, defaultDeps));
741
2914
  }
742
2915
  if (sub === "export") {
743
2916
  const workflowRef = rest[0];
744
2917
  if (!workflowRef) {
745
2918
  console.error("Error: workflow export requires <workflowId|name>.");
746
- console.log("Usage: exodus workflow export <workflowId|name> [--out <file>]");
2919
+ console.log("Usage: exodus workflow export <workflowId|name> [--out <file>] [--version <n>]");
2920
+ process.exit(1);
2921
+ }
2922
+ let version;
2923
+ try {
2924
+ version = parseVersionFlag(flags);
2925
+ }
2926
+ catch (e) {
2927
+ console.error(`Error: ${e instanceof Error ? e.message : String(e)}`);
747
2928
  process.exit(1);
748
2929
  }
749
- return printResult(await exportFlow(workflowRef, { out: flagString(flags, "out") }, defaultDeps));
2930
+ return printResult(await exportFlow(workflowRef, { out: flagString(flags, "out"), json, version }, defaultDeps));
750
2931
  }
751
2932
  if (sub === "import") {
752
2933
  const file = rest[0];
@@ -757,7 +2938,150 @@ export async function run(flags) {
757
2938
  }
758
2939
  return printResult(await importFlow(file, { dryRun: flags["dry-run"] === true, json, update: flagString(flags, "update") }, defaultDeps));
759
2940
  }
2941
+ if (sub === "inbox") {
2942
+ return printResult(await inboxFlow(json, defaultDeps));
2943
+ }
2944
+ if (sub === "gate") {
2945
+ console.error(RETIRED_GATE_VERB_POINTER);
2946
+ process.exit(1);
2947
+ }
2948
+ if (sub === "checkpoint") {
2949
+ const runId = rest[0];
2950
+ if (!runId) {
2951
+ console.error("Error: workflow checkpoint requires <runId>.");
2952
+ console.log('Usage: exodus workflow checkpoint <runId> [show | edit <n> | approve [--reject <n,..>] | retry | cancel]');
2953
+ process.exit(1);
2954
+ }
2955
+ const action = rest[1];
2956
+ if (!action || action === "show") {
2957
+ return printResult(await checkpointShowFlow(runId, { json }, defaultDeps));
2958
+ }
2959
+ if (action === "edit") {
2960
+ const n = parseTriggerIndex(rest[2]);
2961
+ if (n === undefined) {
2962
+ console.error("Error: checkpoint edit needs a 1-based output number <n>.");
2963
+ console.log(`Usage: exodus workflow checkpoint <runId> edit <n> [--text "..." | --file <path> | (stdin)]`);
2964
+ process.exit(1);
2965
+ }
2966
+ const stdin = await maybeReadStdin(flags);
2967
+ return printResult(await checkpointEditFlow(runId, n, { text: flagString(flags, "text"), file: flagString(flags, "file"), stdin }, { json }, defaultDeps));
2968
+ }
2969
+ if (action === "approve") {
2970
+ return printResult(await checkpointApproveFlow(runId, {
2971
+ wait: flags["wait"] === true,
2972
+ json,
2973
+ onProgressLine: (line) => console.log(line),
2974
+ ...(flags["reject"] !== undefined
2975
+ ? { reject: flagString(flags, "reject") ?? "" }
2976
+ : {}),
2977
+ }, defaultDeps));
2978
+ }
2979
+ if (action === "retry") {
2980
+ return printResult(await checkpointRetryFlow(runId, {
2981
+ wait: flags["wait"] === true,
2982
+ json,
2983
+ ...(flags["note"] !== undefined
2984
+ ? { note: flagString(flags, "note") }
2985
+ : {}),
2986
+ onProgressLine: (line) => console.log(line),
2987
+ }, defaultDeps));
2988
+ }
2989
+ if (action === "cancel") {
2990
+ return printResult(await checkpointCancelFlow(runId, { reason: flagString(flags, "reason"), json }, defaultDeps));
2991
+ }
2992
+ console.error(`Error: unknown checkpoint action "${action}" (expected show, edit, approve, retry, or cancel).`);
2993
+ process.exit(1);
2994
+ }
2995
+ if (sub === "repair") {
2996
+ const runId = rest[0];
2997
+ if (!runId) {
2998
+ console.error("Error: workflow repair requires <runId>.");
2999
+ console.log("Usage: exodus workflow repair <runId> retry|skip|kill [--wait]");
3000
+ process.exit(1);
3001
+ }
3002
+ const action = rest[1];
3003
+ if (action !== "retry" && action !== "skip" && action !== "kill") {
3004
+ console.error(`Error: workflow repair needs an action (retry, skip, or kill)${action ? ` — got "${action}"` : ""}.`);
3005
+ console.log("Usage: exodus workflow repair <runId> retry|skip|kill [--wait]");
3006
+ process.exit(1);
3007
+ }
3008
+ return printResult(await repairFlow(runId, action, { wait: flags["wait"] === true, json, onProgressLine: (line) => console.log(line) }, defaultDeps));
3009
+ }
3010
+ if (sub === "answer") {
3011
+ const runId = rest[0];
3012
+ if (!runId) {
3013
+ console.error("Error: workflow answer requires <runId>.");
3014
+ console.log("Usage: exodus workflow answer <runId> --slot key=value [--slot key=value ...]");
3015
+ process.exit(1);
3016
+ }
3017
+ let values;
3018
+ try {
3019
+ values = parseSlotFlags(process.argv.slice(3));
3020
+ }
3021
+ catch (e) {
3022
+ console.error(`Error: ${e instanceof Error ? e.message : String(e)}`);
3023
+ process.exit(1);
3024
+ }
3025
+ return printResult(await answerFlow(runId, values, { json }, defaultDeps));
3026
+ }
3027
+ if (sub === "triggers") {
3028
+ const workflowRef = rest[0];
3029
+ if (!workflowRef) {
3030
+ console.error("Error: workflow triggers requires <workflowId|name>.");
3031
+ console.log("Usage: exodus workflow triggers <workflowId|name> [enable|disable <n> | fire [<n>]] [--json]");
3032
+ process.exit(1);
3033
+ }
3034
+ const action = rest[1];
3035
+ if (!action)
3036
+ return printResult(await triggersListFlow(workflowRef, { json }, defaultDeps));
3037
+ if (action === "enable" || action === "disable") {
3038
+ const n = parseTriggerIndex(rest[2]);
3039
+ if (n === undefined) {
3040
+ console.error(`Error: workflow triggers ${action} requires a 1-based trigger number <n>.`);
3041
+ console.log(`Usage: exodus workflow triggers <workflowId|name> ${action} <n>`);
3042
+ process.exit(1);
3043
+ }
3044
+ return printResult(await triggersSetEnabledFlow(workflowRef, n, action === "enable", { json }, defaultDeps));
3045
+ }
3046
+ if (action === "fire") {
3047
+ let n;
3048
+ if (rest[2] !== undefined) {
3049
+ n = parseTriggerIndex(rest[2]);
3050
+ if (n === undefined) {
3051
+ console.error(`Error: trigger number must be a positive integer (got "${rest[2]}").`);
3052
+ process.exit(1);
3053
+ }
3054
+ }
3055
+ let fireOverrides;
3056
+ try {
3057
+ fireOverrides = parseRigOverridesFlag(process.argv.slice(3), defaultDeps.readFile);
3058
+ }
3059
+ catch (e) {
3060
+ console.error(`Error: ${e instanceof Error ? e.message : String(e)}`);
3061
+ process.exit(1);
3062
+ }
3063
+ return printResult(await triggersFireFlow(workflowRef, {
3064
+ n,
3065
+ text: flagString(flags, "text"),
3066
+ imageRigOverrides: fireOverrides,
3067
+ wait: flags["wait"] === true,
3068
+ json,
3069
+ onProgressLine: (line) => console.log(line),
3070
+ }, defaultDeps));
3071
+ }
3072
+ console.error(`Error: unknown triggers action "${action}" (expected enable, disable, or fire).`);
3073
+ console.log("Usage: exodus workflow triggers <workflowId|name> [enable|disable <n> | fire [<n>]] [--json]");
3074
+ process.exit(1);
3075
+ }
760
3076
  console.error(`Unknown subcommand: "${sub}"\n`);
761
3077
  console.log(helpText);
762
3078
  process.exit(1);
763
3079
  }
3080
+ function parseTriggerIndex(raw) {
3081
+ if (raw === undefined)
3082
+ return undefined;
3083
+ if (!/^\d+$/.test(raw))
3084
+ return undefined;
3085
+ const n = Number(raw);
3086
+ return n >= 1 ? n : undefined;
3087
+ }