@relayflows/sdk 2.0.30 → 2.0.32

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 (347) hide show
  1. package/dist/agent-artifacts.d.ts.map +1 -1
  2. package/dist/agent-artifacts.js +2 -9
  3. package/dist/agent-artifacts.js.map +1 -1
  4. package/dist/agent-cwd.d.ts +69 -0
  5. package/dist/agent-cwd.d.ts.map +1 -0
  6. package/dist/agent-cwd.js +140 -0
  7. package/dist/agent-cwd.js.map +1 -0
  8. package/dist/artifact-scan-policy.d.ts +35 -0
  9. package/dist/artifact-scan-policy.d.ts.map +1 -0
  10. package/dist/artifact-scan-policy.js +49 -0
  11. package/dist/artifact-scan-policy.js.map +1 -0
  12. package/dist/authored-completion-record.d.ts +35 -0
  13. package/dist/authored-completion-record.d.ts.map +1 -0
  14. package/dist/authored-completion-record.js +92 -0
  15. package/dist/authored-completion-record.js.map +1 -0
  16. package/dist/authored-completion.d.ts +99 -0
  17. package/dist/authored-completion.d.ts.map +1 -0
  18. package/dist/authored-completion.js +184 -0
  19. package/dist/authored-completion.js.map +1 -0
  20. package/dist/authored-flow-error.d.ts +13 -1
  21. package/dist/authored-flow-error.d.ts.map +1 -1
  22. package/dist/authored-flow-error.js +12 -0
  23. package/dist/authored-flow-error.js.map +1 -1
  24. package/dist/authored-flow-executor.d.ts +7 -30
  25. package/dist/authored-flow-executor.d.ts.map +1 -1
  26. package/dist/authored-flow-executor.js +54 -47
  27. package/dist/authored-flow-executor.js.map +1 -1
  28. package/dist/authored-human.d.ts.map +1 -1
  29. package/dist/authored-human.js +1 -3
  30. package/dist/authored-human.js.map +1 -1
  31. package/dist/authored-node-entry.js +4 -1
  32. package/dist/authored-node-entry.js.map +1 -1
  33. package/dist/authored-node-runner.d.ts +9 -1
  34. package/dist/authored-node-runner.d.ts.map +1 -1
  35. package/dist/authored-node-runner.js +92 -17
  36. package/dist/authored-node-runner.js.map +1 -1
  37. package/dist/authored-preflight.d.ts +4 -0
  38. package/dist/authored-preflight.d.ts.map +1 -0
  39. package/dist/authored-preflight.js +50 -0
  40. package/dist/authored-preflight.js.map +1 -0
  41. package/dist/authored-root.d.ts +5 -0
  42. package/dist/authored-root.d.ts.map +1 -1
  43. package/dist/authored-root.js +20 -2
  44. package/dist/authored-root.js.map +1 -1
  45. package/dist/authored-step-output.d.ts +35 -10
  46. package/dist/authored-step-output.d.ts.map +1 -1
  47. package/dist/authored-step-output.js +108 -40
  48. package/dist/authored-step-output.js.map +1 -1
  49. package/dist/authored-verdict.d.ts +28 -0
  50. package/dist/authored-verdict.d.ts.map +1 -0
  51. package/dist/authored-verdict.js +79 -0
  52. package/dist/authored-verdict.js.map +1 -0
  53. package/dist/authored-worker-step.d.ts +5 -2
  54. package/dist/authored-worker-step.d.ts.map +1 -1
  55. package/dist/authored-worker-step.js +51 -13
  56. package/dist/authored-worker-step.js.map +1 -1
  57. package/dist/cli/check-worker-surface.d.ts +27 -0
  58. package/dist/cli/check-worker-surface.d.ts.map +1 -0
  59. package/dist/cli/check-worker-surface.js +63 -0
  60. package/dist/cli/check-worker-surface.js.map +1 -0
  61. package/dist/cli/check.d.ts +28 -3
  62. package/dist/cli/check.d.ts.map +1 -1
  63. package/dist/cli/check.js +27 -140
  64. package/dist/cli/check.js.map +1 -1
  65. package/dist/cli/cli-probe.d.ts +20 -0
  66. package/dist/cli/cli-probe.d.ts.map +1 -0
  67. package/dist/cli/cli-probe.js +166 -0
  68. package/dist/cli/cli-probe.js.map +1 -0
  69. package/dist/cli/cloud-format.d.ts +9 -0
  70. package/dist/cli/cloud-format.d.ts.map +1 -0
  71. package/dist/cli/cloud-format.js +77 -0
  72. package/dist/cli/cloud-format.js.map +1 -0
  73. package/dist/cli/cloud-live.d.ts +39 -0
  74. package/dist/cli/cloud-live.d.ts.map +1 -0
  75. package/dist/cli/cloud-live.js +325 -0
  76. package/dist/cli/cloud-live.js.map +1 -0
  77. package/dist/cli/cloud-mirror-session.d.ts +97 -0
  78. package/dist/cli/cloud-mirror-session.d.ts.map +1 -0
  79. package/dist/cli/cloud-mirror-session.js +264 -0
  80. package/dist/cli/cloud-mirror-session.js.map +1 -0
  81. package/dist/cli/cloud-read.d.ts +3 -7
  82. package/dist/cli/cloud-read.d.ts.map +1 -1
  83. package/dist/cli/cloud-read.js +14 -266
  84. package/dist/cli/cloud-read.js.map +1 -1
  85. package/dist/cli/cloud-refusal.d.ts +39 -0
  86. package/dist/cli/cloud-refusal.d.ts.map +1 -0
  87. package/dist/cli/cloud-refusal.js +95 -0
  88. package/dist/cli/cloud-refusal.js.map +1 -0
  89. package/dist/cli/cloud-status-view.d.ts +7 -0
  90. package/dist/cli/cloud-status-view.d.ts.map +1 -0
  91. package/dist/cli/cloud-status-view.js +214 -0
  92. package/dist/cli/cloud-status-view.js.map +1 -0
  93. package/dist/cli/direct-run.d.ts.map +1 -1
  94. package/dist/cli/direct-run.js +16 -2
  95. package/dist/cli/direct-run.js.map +1 -1
  96. package/dist/cli/hn-monitor.d.ts +0 -13
  97. package/dist/cli/hn-monitor.d.ts.map +1 -1
  98. package/dist/cli/hn-monitor.js +2 -1
  99. package/dist/cli/hn-monitor.js.map +1 -1
  100. package/dist/cli/local-agent-remedy.d.ts +80 -0
  101. package/dist/cli/local-agent-remedy.d.ts.map +1 -0
  102. package/dist/cli/local-agent-remedy.js +116 -0
  103. package/dist/cli/local-agent-remedy.js.map +1 -0
  104. package/dist/cli/observer-session.d.ts +41 -0
  105. package/dist/cli/observer-session.d.ts.map +1 -0
  106. package/dist/cli/observer-session.js +78 -0
  107. package/dist/cli/observer-session.js.map +1 -0
  108. package/dist/cli/run.d.ts +30 -2
  109. package/dist/cli/run.d.ts.map +1 -1
  110. package/dist/cli/run.js +186 -24
  111. package/dist/cli/run.js.map +1 -1
  112. package/dist/cli/status.d.ts +9 -0
  113. package/dist/cli/status.d.ts.map +1 -1
  114. package/dist/cli/status.js +31 -2
  115. package/dist/cli/status.js.map +1 -1
  116. package/dist/cli/step-evidence.d.ts +90 -0
  117. package/dist/cli/step-evidence.d.ts.map +1 -0
  118. package/dist/cli/step-evidence.js +259 -0
  119. package/dist/cli/step-evidence.js.map +1 -0
  120. package/dist/cli/step-failure.d.ts +14 -4
  121. package/dist/cli/step-failure.d.ts.map +1 -1
  122. package/dist/cli/step-failure.js +41 -76
  123. package/dist/cli/step-failure.js.map +1 -1
  124. package/dist/cli-commands.d.ts +12 -0
  125. package/dist/cli-commands.d.ts.map +1 -1
  126. package/dist/cli-commands.js +3 -0
  127. package/dist/cli-commands.js.map +1 -1
  128. package/dist/cli.d.ts +17 -0
  129. package/dist/cli.d.ts.map +1 -1
  130. package/dist/cli.js +134 -57
  131. package/dist/cli.js.map +1 -1
  132. package/dist/cloud-deploy.d.ts +1 -1
  133. package/dist/cloud-deploy.d.ts.map +1 -1
  134. package/dist/cloud-deploy.js +24 -8
  135. package/dist/cloud-deploy.js.map +1 -1
  136. package/dist/cloud-mirror-ledger.d.ts +40 -0
  137. package/dist/cloud-mirror-ledger.d.ts.map +1 -0
  138. package/dist/cloud-mirror-ledger.js +142 -0
  139. package/dist/cloud-mirror-ledger.js.map +1 -0
  140. package/dist/cloud-mirror-step.d.ts +168 -0
  141. package/dist/cloud-mirror-step.d.ts.map +1 -0
  142. package/dist/cloud-mirror-step.js +504 -0
  143. package/dist/cloud-mirror-step.js.map +1 -0
  144. package/dist/cloud-mirror-transport.d.ts +94 -0
  145. package/dist/cloud-mirror-transport.d.ts.map +1 -0
  146. package/dist/cloud-mirror-transport.js +163 -0
  147. package/dist/cloud-mirror-transport.js.map +1 -0
  148. package/dist/cloud-mirror.d.ts +132 -0
  149. package/dist/cloud-mirror.d.ts.map +1 -0
  150. package/dist/cloud-mirror.js +556 -0
  151. package/dist/cloud-mirror.js.map +1 -0
  152. package/dist/cloud-read.d.ts +15 -0
  153. package/dist/cloud-read.d.ts.map +1 -1
  154. package/dist/cloud-read.js +20 -1
  155. package/dist/cloud-read.js.map +1 -1
  156. package/dist/cloud-run-record.d.ts +27 -0
  157. package/dist/cloud-run-record.d.ts.map +1 -0
  158. package/dist/cloud-run-record.js +56 -0
  159. package/dist/cloud-run-record.js.map +1 -0
  160. package/dist/cloud-run.d.ts +2 -9
  161. package/dist/cloud-run.d.ts.map +1 -1
  162. package/dist/cloud-run.js +3 -20
  163. package/dist/cloud-run.js.map +1 -1
  164. package/dist/communication/local.d.ts.map +1 -1
  165. package/dist/communication/local.js +2 -1
  166. package/dist/communication/local.js.map +1 -1
  167. package/dist/communication/worker.d.ts +1 -1
  168. package/dist/communication/worker.d.ts.map +1 -1
  169. package/dist/communication/worker.js +13 -5
  170. package/dist/communication/worker.js.map +1 -1
  171. package/dist/compile.d.ts.map +1 -1
  172. package/dist/compile.js +28 -6
  173. package/dist/compile.js.map +1 -1
  174. package/dist/direct-input.d.ts.map +1 -1
  175. package/dist/direct-input.js +21 -1
  176. package/dist/direct-input.js.map +1 -1
  177. package/dist/failure-kinds.d.ts +96 -6
  178. package/dist/failure-kinds.d.ts.map +1 -1
  179. package/dist/failure-kinds.js +29 -2
  180. package/dist/failure-kinds.js.map +1 -1
  181. package/dist/flow-requirements.d.ts.map +1 -1
  182. package/dist/flow-requirements.js +24 -9
  183. package/dist/flow-requirements.js.map +1 -1
  184. package/dist/gate-contract.d.ts +7 -0
  185. package/dist/gate-contract.d.ts.map +1 -1
  186. package/dist/gate-contract.js +6 -1
  187. package/dist/gate-contract.js.map +1 -1
  188. package/dist/helper-preflight.d.ts.map +1 -1
  189. package/dist/helper-preflight.js +10 -3
  190. package/dist/helper-preflight.js.map +1 -1
  191. package/dist/helper-reference.d.ts +25 -0
  192. package/dist/helper-reference.d.ts.map +1 -0
  193. package/dist/helper-reference.js +129 -0
  194. package/dist/helper-reference.js.map +1 -0
  195. package/dist/hosted-extension-runtime.js +1 -1
  196. package/dist/index.d.ts +1 -1
  197. package/dist/index.d.ts.map +1 -1
  198. package/dist/index.js.map +1 -1
  199. package/dist/journal-client.d.ts +3 -1
  200. package/dist/journal-client.d.ts.map +1 -1
  201. package/dist/journal-client.js +17 -2
  202. package/dist/journal-client.js.map +1 -1
  203. package/dist/journal-projection.d.ts +16 -0
  204. package/dist/journal-projection.d.ts.map +1 -0
  205. package/dist/journal-projection.js +108 -0
  206. package/dist/journal-projection.js.map +1 -0
  207. package/dist/llm-worker.js +1 -1
  208. package/dist/llm-worker.js.map +1 -1
  209. package/dist/local-agent.d.ts +1 -1
  210. package/dist/local-agent.d.ts.map +1 -1
  211. package/dist/local-agent.js +4 -3
  212. package/dist/local-agent.js.map +1 -1
  213. package/dist/named-gate-lowering.js +35 -5
  214. package/dist/named-gate-lowering.js.map +1 -1
  215. package/dist/named-gate-preflight.d.ts +27 -0
  216. package/dist/named-gate-preflight.d.ts.map +1 -0
  217. package/dist/named-gate-preflight.js +47 -0
  218. package/dist/named-gate-preflight.js.map +1 -0
  219. package/dist/named-gates.d.ts +1 -1
  220. package/dist/named-gates.d.ts.map +1 -1
  221. package/dist/named-gates.js +3 -0
  222. package/dist/named-gates.js.map +1 -1
  223. package/dist/observer-link.d.ts +7 -0
  224. package/dist/observer-link.d.ts.map +1 -1
  225. package/dist/observer-link.js +3 -1
  226. package/dist/observer-link.js.map +1 -1
  227. package/dist/package-version.d.ts +10 -0
  228. package/dist/package-version.d.ts.map +1 -0
  229. package/dist/package-version.js +22 -0
  230. package/dist/package-version.js.map +1 -0
  231. package/dist/preflight.d.ts +14 -0
  232. package/dist/preflight.d.ts.map +1 -1
  233. package/dist/preflight.js +25 -3
  234. package/dist/preflight.js.map +1 -1
  235. package/dist/protocol.d.ts +2 -0
  236. package/dist/protocol.d.ts.map +1 -1
  237. package/dist/redact.d.ts +42 -0
  238. package/dist/redact.d.ts.map +1 -1
  239. package/dist/redact.js +128 -0
  240. package/dist/redact.js.map +1 -1
  241. package/dist/relay-cli.d.ts.map +1 -1
  242. package/dist/relay-cli.js +1 -21
  243. package/dist/relay-cli.js.map +1 -1
  244. package/dist/run-projection.d.ts +83 -0
  245. package/dist/run-projection.d.ts.map +1 -0
  246. package/dist/run-projection.js +199 -0
  247. package/dist/run-projection.js.map +1 -0
  248. package/dist/shell-word.d.ts +19 -0
  249. package/dist/shell-word.d.ts.map +1 -0
  250. package/dist/shell-word.js +23 -0
  251. package/dist/shell-word.js.map +1 -0
  252. package/dist/spec.d.ts +52 -3
  253. package/dist/spec.d.ts.map +1 -1
  254. package/dist/spec.js.map +1 -1
  255. package/dist/step-fields.d.ts +1 -1
  256. package/dist/step-fields.js +1 -1
  257. package/dist/step-fields.js.map +1 -1
  258. package/dist/steps-green.d.ts +27 -0
  259. package/dist/steps-green.d.ts.map +1 -0
  260. package/dist/steps-green.js +164 -0
  261. package/dist/steps-green.js.map +1 -0
  262. package/dist/validate.d.ts.map +1 -1
  263. package/dist/validate.js +39 -8
  264. package/dist/validate.js.map +1 -1
  265. package/dist/worker-lease.d.ts +8 -1
  266. package/dist/worker-lease.d.ts.map +1 -1
  267. package/dist/worker-lease.js +34 -4
  268. package/dist/worker-lease.js.map +1 -1
  269. package/dist/worker.d.ts +8 -0
  270. package/dist/worker.d.ts.map +1 -1
  271. package/dist/worker.js +17 -9
  272. package/dist/worker.js.map +1 -1
  273. package/package.json +3 -7
  274. package/src/agent-artifacts.ts +2 -10
  275. package/src/agent-cwd.ts +139 -0
  276. package/src/artifact-scan-policy.ts +51 -0
  277. package/src/authored-completion-record.ts +119 -0
  278. package/src/authored-completion.ts +203 -0
  279. package/src/authored-flow-error.ts +13 -1
  280. package/src/authored-flow-executor.ts +91 -58
  281. package/src/authored-human.ts +1 -4
  282. package/src/authored-node-entry.ts +4 -1
  283. package/src/authored-node-runner.ts +96 -22
  284. package/src/authored-preflight.ts +46 -0
  285. package/src/authored-root.ts +20 -2
  286. package/src/authored-step-output.ts +139 -42
  287. package/src/authored-verdict.ts +87 -0
  288. package/src/authored-worker-step.ts +63 -14
  289. package/src/cli/check-worker-surface.ts +66 -0
  290. package/src/cli/check.ts +59 -166
  291. package/src/cli/cli-probe.ts +194 -0
  292. package/src/cli/cloud-format.ts +82 -0
  293. package/src/cli/cloud-live.ts +366 -0
  294. package/src/cli/cloud-mirror-session.ts +329 -0
  295. package/src/cli/cloud-read.ts +13 -282
  296. package/src/cli/cloud-refusal.ts +113 -0
  297. package/src/cli/cloud-status-view.ts +213 -0
  298. package/src/cli/direct-run.ts +19 -2
  299. package/src/cli/hn-monitor.ts +2 -1
  300. package/src/cli/local-agent-remedy.ts +160 -0
  301. package/src/cli/observer-session.ts +107 -0
  302. package/src/cli/run.ts +233 -28
  303. package/src/cli/status.ts +59 -3
  304. package/src/cli/step-evidence.ts +310 -0
  305. package/src/cli/step-failure.ts +57 -81
  306. package/src/cli-commands.ts +3 -0
  307. package/src/cli.ts +155 -60
  308. package/src/cloud-deploy.ts +26 -8
  309. package/src/cloud-mirror-ledger.ts +161 -0
  310. package/src/cloud-mirror-step.ts +618 -0
  311. package/src/cloud-mirror-transport.ts +261 -0
  312. package/src/cloud-mirror.ts +633 -0
  313. package/src/cloud-read.ts +25 -1
  314. package/src/cloud-run-record.ts +64 -0
  315. package/src/cloud-run.ts +5 -24
  316. package/src/communication/local.ts +2 -1
  317. package/src/communication/worker.ts +13 -5
  318. package/src/compile.ts +28 -6
  319. package/src/direct-input.ts +22 -1
  320. package/src/failure-kinds.ts +104 -2
  321. package/src/flow-requirements.ts +24 -9
  322. package/src/gate-contract.ts +13 -1
  323. package/src/helper-preflight.ts +10 -3
  324. package/src/helper-reference.ts +130 -0
  325. package/src/hosted-extension-runtime.ts +1 -1
  326. package/src/index.ts +2 -0
  327. package/src/journal-client.ts +19 -2
  328. package/src/journal-projection.ts +106 -0
  329. package/src/llm-worker.ts +1 -1
  330. package/src/local-agent.ts +4 -2
  331. package/src/named-gate-lowering.ts +35 -5
  332. package/src/named-gate-preflight.ts +47 -0
  333. package/src/named-gates.ts +3 -0
  334. package/src/observer-link.ts +10 -1
  335. package/src/package-version.ts +23 -0
  336. package/src/preflight.ts +38 -7
  337. package/src/protocol.ts +2 -0
  338. package/src/redact.ts +111 -0
  339. package/src/relay-cli.ts +1 -24
  340. package/src/run-projection.ts +247 -0
  341. package/src/shell-word.ts +24 -0
  342. package/src/spec.ts +54 -3
  343. package/src/step-fields.ts +1 -1
  344. package/src/steps-green.ts +168 -0
  345. package/src/validate.ts +35 -8
  346. package/src/worker-lease.ts +35 -5
  347. package/src/worker.ts +27 -11
@@ -0,0 +1,168 @@
1
+ import { type RunView } from './run-state.js';
2
+ import type { JournalEvent } from './journal-reader.js';
3
+ /** Steps one snapshot may carry; a longer run publishes its live tail. */
4
+ export declare const SNAPSHOT_MAX_STEPS = 64;
5
+ /** Serialized snapshot envelope cap, against the real UTF-8 byte count. */
6
+ export declare const SNAPSHOT_MAX_BYTES: number;
7
+ /** Artifact paths named per step; the rest are counted. */
8
+ export declare const SNAPSHOT_ARTIFACTS_MAX = 5;
9
+ export declare const SNAPSHOT_ARTIFACT_MAX_CHARS = 200;
10
+ /** `stepName`, `journalRunId`, `stepType`, `completionReason`, gate, model. */
11
+ export declare const IDENTIFIER_MAX_CHARS = 128;
12
+ /** Predecessors one live step lists. */
13
+ export declare const SNAPSHOT_DEPENDS_ON_MAX = 32;
14
+ /** Predecessors a final row lists. */
15
+ export declare const DEPENDS_ON_MAX_ENTRIES = 256;
16
+ /** The backing columns are PostgreSQL 32-bit integers. */
17
+ export declare const MAX_INT32 = 2147483647;
18
+ /** `workflow_steps.display_name`, in code points. */
19
+ export declare const LABEL_MAX_CHARS = 120;
20
+ /** `workflow_steps.output_summary`. */
21
+ export declare const OUTPUT_SUMMARY_MAX_CHARS = 1000;
22
+ /** `workflow_steps.error`. */
23
+ export declare const ERROR_MAX_CHARS = 1024;
24
+ /** Serialized `workflow_steps.detail`. */
25
+ export declare const DETAIL_MAX_BYTES: number;
26
+ /** Attempt rows kept on `detail.attempts`; older ones are counted, not listed. */
27
+ export declare const DETAIL_MAX_ATTEMPTS = 20;
28
+ /**
29
+ * The one completion reason the kernel uses for success. Cloud keys a step's
30
+ * status off exactly this value, so the live derivation and the final row
31
+ * agree about what "completed" means.
32
+ */
33
+ export declare const SUCCESS_COMPLETION_REASON = "success";
34
+ /** The authored root step spans the whole flow; its children carry the steps. */
35
+ export declare const AUTHORED_ROOT_STEP = "authored-root";
36
+ /** Live kernel states Cloud publishes. A step that has not begun has no honest rendering. */
37
+ export type SnapshotState = 'running' | 'backoff' | 'waiting' | 'needs_human' | 'done';
38
+ export interface SnapshotStep {
39
+ stepName: string;
40
+ /** Child runs may repeat a step id, so identity is the pair. */
41
+ journalRunId: string;
42
+ stepType: string;
43
+ state: SnapshotState;
44
+ attempt: number;
45
+ elapsedMs: number;
46
+ completionReason?: string;
47
+ gate?: {
48
+ name: string;
49
+ verdict: string;
50
+ };
51
+ model?: string;
52
+ turns?: number;
53
+ toolCalls?: number;
54
+ costUsd?: number;
55
+ artifactCount?: number;
56
+ artifacts?: string[];
57
+ label?: string;
58
+ dependsOn?: string[];
59
+ }
60
+ /** One row of the final report; the field names are `workflow_steps`'s own. */
61
+ export interface FinalStep {
62
+ stepName: string;
63
+ stepType: string;
64
+ agent: string;
65
+ preset: string;
66
+ cli: string;
67
+ sandboxId: string;
68
+ startTime: string;
69
+ endTime: string;
70
+ durationMs: number;
71
+ exitCode: number;
72
+ outputSummary: string;
73
+ status: 'completed' | 'failed';
74
+ completionReason: string;
75
+ retryCount: number;
76
+ model?: string;
77
+ tokensInput?: number;
78
+ tokensOutput?: number;
79
+ costUsd?: number;
80
+ error?: string;
81
+ detail?: Record<string, unknown>;
82
+ detailTruncated?: true;
83
+ label?: string;
84
+ dependsOn?: string[];
85
+ }
86
+ /** One step's per-attempt transcript files, for the `<stepName>/agent.log` upload. */
87
+ export interface StepTranscriptRef {
88
+ stepName: string;
89
+ attempts: Array<{
90
+ attempt: number;
91
+ path: string;
92
+ }>;
93
+ }
94
+ /** What one journal contributes, keyed for the caller's cross-journal cache. */
95
+ export interface MirroredJournal {
96
+ runId: string;
97
+ status: RunView['status'];
98
+ terminal: boolean;
99
+ steps: SnapshotStep[];
100
+ finals: FinalStep[];
101
+ transcripts: StepTranscriptRef[];
102
+ /** Child journals this run admitted, from an authored root's step index. */
103
+ children: string[];
104
+ /** Authored graph hints by step id, from an authored root's step index. */
105
+ hints: Map<string, {
106
+ label?: string;
107
+ after?: string[];
108
+ }>;
109
+ }
110
+ /**
111
+ * Redact, then normalize, then clip — in that order. Clipping first could
112
+ * leave the head of a secret standing; normalizing first would let a
113
+ * multi-character replacement push the result back over the cap.
114
+ */
115
+ export declare function identifier(value: unknown, env: NodeJS.ProcessEnv, maxChars?: number): string | undefined;
116
+ /** Free text, redacted then bounded by code points. Empty becomes undefined. */
117
+ export declare function text(value: unknown, env: NodeJS.ProcessEnv, maxChars: number): string | undefined;
118
+ /**
119
+ * A step label as `workflow_steps.display_name` accepts it: control characters
120
+ * become spaces, whitespace runs collapse, the result is trimmed and clipped.
121
+ */
122
+ export declare function label(value: unknown, env: NodeJS.ProcessEnv): string | undefined;
123
+ /** Cloud's own vocabulary for a live step, derived rather than carried. */
124
+ export declare function snapshotStepStatus(step: Pick<SnapshotStep, 'state' | 'completionReason'>): 'running' | 'completed' | 'failed';
125
+ /**
126
+ * Fold one journal into everything the mirror can say about it.
127
+ *
128
+ * The authored root is deliberately not published as a step: it spans the
129
+ * whole flow, so a snapshot carrying it would show one node called
130
+ * `authored-root` sitting at 100% for the run's entire duration beside the
131
+ * steps that actually did the work. Its journal is still read, for the step
132
+ * index that names the child journals and their graph edges.
133
+ */
134
+ export declare function mirrorJournal(runId: string, events: readonly JournalEvent[], nowMs: number, env?: NodeJS.ProcessEnv): MirroredJournal;
135
+ /**
136
+ * Build a snapshot envelope that actually fits both bounds.
137
+ *
138
+ * The count cap applies unconditionally — 65 tiny steps are 65 steps. Only
139
+ * then does the byte cap bite: first the artifact *names* go (their count
140
+ * survives), then the `dependsOn` edges, then whole entries from the head of
141
+ * the display order, because the tail is the newest work and that is what a
142
+ * live view exists to show. A capped view announces itself as incomplete;
143
+ * silently showing fewer steps than ran is the one thing it must not do.
144
+ */
145
+ export declare function fitSnapshot(steps: readonly SnapshotStep[], envelope: {
146
+ sequence: number;
147
+ capturedAt: string;
148
+ alreadyOmitted?: number;
149
+ }): {
150
+ sequence: number;
151
+ capturedAt: string;
152
+ truncated?: true;
153
+ omittedStepCount?: number;
154
+ steps: SnapshotStep[];
155
+ };
156
+ /** Apply an authored root's graph hints to a step, bounded for the live view. */
157
+ export declare function withGraphHints<T extends {
158
+ stepName: string;
159
+ journalRunId?: string;
160
+ }>(step: T, hints: Map<string, {
161
+ label?: string;
162
+ after?: string[];
163
+ }>, journalRunId: string, maxDependsOn: number, knownSteps: ReadonlySet<string>): T & {
164
+ label?: string;
165
+ dependsOn?: string[];
166
+ };
167
+ export type { RunView };
168
+ //# sourceMappingURL=cloud-mirror-step.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud-mirror-step.d.ts","sourceRoot":"","sources":["../src/cloud-mirror-step.ts"],"names":[],"mappings":"AAiCA,OAAO,EAAgB,KAAK,OAAO,EAAiB,MAAM,gBAAgB,CAAC;AAC3E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGxD,0EAA0E;AAC1E,eAAO,MAAM,kBAAkB,KAAK,CAAC;AACrC,2EAA2E;AAC3E,eAAO,MAAM,kBAAkB,QAAY,CAAC;AAC5C,2DAA2D;AAC3D,eAAO,MAAM,sBAAsB,IAAI,CAAC;AACxC,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAC/C,+EAA+E;AAC/E,eAAO,MAAM,oBAAoB,MAAM,CAAC;AACxC,wCAAwC;AACxC,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAC1C,sCAAsC;AACtC,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAC1C,0DAA0D;AAC1D,eAAO,MAAM,SAAS,aAAgB,CAAC;AACvC,qDAAqD;AACrD,eAAO,MAAM,eAAe,MAAM,CAAC;AACnC,uCAAuC;AACvC,eAAO,MAAM,wBAA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;CAAE,CA4B9G;AAED,iFAAiF;AACjF,wBAAgB,cAAc,CAAC,CAAC,SAAS;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,EAClF,IAAI,EAAE,CAAC,EACP,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,EACxD,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,WAAW,CAAC,MAAM,CAAC,GAC9B,CAAC,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAa9C;AAED,YAAY,EAAE,OAAO,EAAE,CAAC"}
@@ -0,0 +1,504 @@
1
+ // One journal, folded into the two step shapes Cloud stores for a run.
2
+ //
3
+ // A hosted run's steps reach Cloud twice: as a *live snapshot* while it runs
4
+ // (`POST /runs/<id>/steps/snapshot`) and as the *final report* once it is over
5
+ // (`POST /runs/<id>/steps`). The sandbox derives both from `flows status`;
6
+ // this module derives them from the same journal fold `flows status` uses
7
+ // (`run-state.ts`), so a local run and a hosted one put the same facts in the
8
+ // same fields and the dashboard cannot tell which produced a row.
9
+ //
10
+ // Nothing here does I/O or reads a clock: the caller passes the events and
11
+ // `now_ms`, exactly as `foldRunState` does. That is what lets a test fold a
12
+ // hand-built journal and assert the exact bytes a push would carry.
13
+ //
14
+ // ## The bounds are the server's, restated
15
+ //
16
+ // Every cap below is the one Cloud's own parser enforces
17
+ // (`@cloud/core` `storage/step-snapshot.ts` and `storage/step-detail.ts`).
18
+ // They are restated rather than imported because this package cannot depend on
19
+ // the Cloud app — the same reason `cloud-transcript.ts` restates the
20
+ // dashboard's transcript vocabulary. A push that violates one is refused
21
+ // whole, so producing a bounded value here is not politeness: it is the
22
+ // difference between a run that appears on the dashboard and one that does
23
+ // not.
24
+ //
25
+ // ## Redaction
26
+ //
27
+ // Every dynamic string goes through `redact` before it is bounded, never
28
+ // after: clipping first can leave the head of a secret standing where the
29
+ // redactor would have replaced the whole value. Identifier-shaped fields are
30
+ // then normalized into the shape Cloud's parser accepts, because the redactor
31
+ // emits `[redacted:NAME]`, which no identifier pattern admits.
32
+ import { redact } from './redact.js';
33
+ import { foldRunState } from './run-state.js';
34
+ import { AUTHORED_STEP_STREAM, foldAuthoredStepRecords } from './authored-step-index.js';
35
+ /** Steps one snapshot may carry; a longer run publishes its live tail. */
36
+ export const SNAPSHOT_MAX_STEPS = 64;
37
+ /** Serialized snapshot envelope cap, against the real UTF-8 byte count. */
38
+ export const SNAPSHOT_MAX_BYTES = 64 * 1024;
39
+ /** Artifact paths named per step; the rest are counted. */
40
+ export const SNAPSHOT_ARTIFACTS_MAX = 5;
41
+ export const SNAPSHOT_ARTIFACT_MAX_CHARS = 200;
42
+ /** `stepName`, `journalRunId`, `stepType`, `completionReason`, gate, model. */
43
+ export const IDENTIFIER_MAX_CHARS = 128;
44
+ /** Predecessors one live step lists. */
45
+ export const SNAPSHOT_DEPENDS_ON_MAX = 32;
46
+ /** Predecessors a final row lists. */
47
+ export const DEPENDS_ON_MAX_ENTRIES = 256;
48
+ /** The backing columns are PostgreSQL 32-bit integers. */
49
+ export const MAX_INT32 = 2_147_483_647;
50
+ /** `workflow_steps.display_name`, in code points. */
51
+ export const LABEL_MAX_CHARS = 120;
52
+ /** `workflow_steps.output_summary`. */
53
+ export const OUTPUT_SUMMARY_MAX_CHARS = 1000;
54
+ /** `workflow_steps.error`. */
55
+ export const ERROR_MAX_CHARS = 1024;
56
+ /** Serialized `workflow_steps.detail`. */
57
+ export const DETAIL_MAX_BYTES = 16 * 1024;
58
+ /** Attempt rows kept on `detail.attempts`; older ones are counted, not listed. */
59
+ export const DETAIL_MAX_ATTEMPTS = 20;
60
+ /**
61
+ * The one completion reason the kernel uses for success. Cloud keys a step's
62
+ * status off exactly this value, so the live derivation and the final row
63
+ * agree about what "completed" means.
64
+ */
65
+ export const SUCCESS_COMPLETION_REASON = 'success';
66
+ /** The authored root step spans the whole flow; its children carry the steps. */
67
+ export const AUTHORED_ROOT_STEP = 'authored-root';
68
+ const IDENTIFIER = /^[A-Za-z0-9_.:/-]+$/u;
69
+ const IDENTIFIER_UNSAFE = /[^A-Za-z0-9_.:/-]+/gu;
70
+ function record(value) {
71
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
72
+ }
73
+ function int32(value, floor = 0) {
74
+ if (typeof value !== 'number' || !Number.isFinite(value))
75
+ return undefined;
76
+ const rounded = Math.round(value);
77
+ if (rounded < floor)
78
+ return undefined;
79
+ return Math.min(rounded, MAX_INT32);
80
+ }
81
+ /**
82
+ * Redact, then normalize, then clip — in that order. Clipping first could
83
+ * leave the head of a secret standing; normalizing first would let a
84
+ * multi-character replacement push the result back over the cap.
85
+ */
86
+ export function identifier(value, env, maxChars = IDENTIFIER_MAX_CHARS) {
87
+ if (typeof value !== 'string' || value.length === 0)
88
+ return undefined;
89
+ const clipped = redact(value, env).replace(IDENTIFIER_UNSAFE, '_').slice(0, Math.max(1, maxChars));
90
+ return IDENTIFIER.test(clipped) ? clipped : undefined;
91
+ }
92
+ /** Free text, redacted then bounded by code points. Empty becomes undefined. */
93
+ export function text(value, env, maxChars) {
94
+ if (typeof value !== 'string' || value.length === 0)
95
+ return undefined;
96
+ const cleaned = redact(value, env);
97
+ const bounded = [...cleaned].slice(0, maxChars).join('');
98
+ return bounded.length === 0 ? undefined : bounded;
99
+ }
100
+ /**
101
+ * A step label as `workflow_steps.display_name` accepts it: control characters
102
+ * become spaces, whitespace runs collapse, the result is trimmed and clipped.
103
+ */
104
+ export function label(value, env) {
105
+ if (typeof value !== 'string')
106
+ return undefined;
107
+ const normalized = redact(value, env)
108
+ .replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ')
109
+ .replace(/\s+/gu, ' ')
110
+ .trim();
111
+ if (normalized.length === 0)
112
+ return undefined;
113
+ return [...normalized].slice(0, LABEL_MAX_CHARS).join('').trimEnd();
114
+ }
115
+ function snapshotState(state) {
116
+ // `pending` and `runnable` are states, but not publishable ones: a step that
117
+ // has not begun is neither completed nor running.
118
+ return state === 'pending' || state === 'runnable' ? undefined : state;
119
+ }
120
+ /** Cloud's own vocabulary for a live step, derived rather than carried. */
121
+ export function snapshotStepStatus(step) {
122
+ if (step.state !== 'done')
123
+ return 'running';
124
+ return step.completionReason === SUCCESS_COMPLETION_REASON ? 'completed' : 'failed';
125
+ }
126
+ function snapshotStep(journalRunId, step, env) {
127
+ const state = snapshotState(step.state);
128
+ if (state === undefined)
129
+ return undefined;
130
+ const stepName = identifier(step.id, env);
131
+ const journal = identifier(journalRunId, env);
132
+ const stepType = identifier(step.type, env);
133
+ if (stepName === undefined || journal === undefined || stepType === undefined)
134
+ return undefined;
135
+ const transcript = step.last_attempt?.transcript ?? null;
136
+ const verification = step.last_attempt?.verification ?? null;
137
+ const gateName = verification === null ? undefined : identifier(verification.gate, env);
138
+ const gateVerdict = verification === null ? undefined : identifier(verification.verdict, env);
139
+ const paths = step.artifacts.paths
140
+ .slice(0, SNAPSHOT_ARTIFACTS_MAX)
141
+ .map(path => identifier(path, env, SNAPSHOT_ARTIFACT_MAX_CHARS))
142
+ .filter((path) => path !== undefined);
143
+ const completionReason = identifier(step.completion_reason ?? step.last_attempt?.completion_reason, env);
144
+ const cost = transcript?.total_cost_usd;
145
+ return {
146
+ stepName,
147
+ journalRunId: journal,
148
+ stepType,
149
+ state,
150
+ attempt: int32(step.attempt) ?? 0,
151
+ elapsedMs: int32(step.elapsed_ms) ?? 0,
152
+ ...(completionReason === undefined ? {} : { completionReason }),
153
+ ...(gateName === undefined || gateVerdict === undefined ? {} : { gate: { name: gateName, verdict: gateVerdict } }),
154
+ ...(identifier(transcript?.model, env) === undefined ? {} : { model: identifier(transcript?.model, env) }),
155
+ ...(int32(transcript?.num_turns) === undefined ? {} : { turns: int32(transcript?.num_turns) }),
156
+ ...(int32(transcript?.tool_calls) === undefined ? {} : { toolCalls: int32(transcript?.tool_calls) }),
157
+ ...(typeof cost === 'number' && Number.isFinite(cost) && cost >= 0 ? { costUsd: cost } : {}),
158
+ ...(step.artifacts.journaled ? { artifactCount: int32(step.artifacts.paths.length) ?? 0 } : {}),
159
+ ...(paths.length === 0 ? {} : { artifacts: paths }),
160
+ };
161
+ }
162
+ function isoAt(ms) {
163
+ if (typeof ms !== 'number' || !Number.isFinite(ms))
164
+ return '';
165
+ const at = new Date(ms);
166
+ return Number.isNaN(at.getTime()) ? '' : at.toISOString();
167
+ }
168
+ /**
169
+ * The bounded `workflow_steps.detail` for one step: the attempt's journaled
170
+ * transcript digest, plus the attempt roster. The digest is already redacted
171
+ * and bounded where the worker wrote it (`agent-transcript.ts`); it is
172
+ * re-bounded here because this process, not that one, is what Cloud's parser
173
+ * will judge.
174
+ */
175
+ function stepDetail(attempts, env) {
176
+ const last = attempts.at(-1);
177
+ const digest = record(record(last?.trajectoryTail)?.['transcript']);
178
+ const roster = attempts.slice(-DETAIL_MAX_ATTEMPTS).map(entry => ({
179
+ attempt: entry.attempt,
180
+ atMs: entry.atMs,
181
+ completionReason: identifier(entry.completionReason, env) ?? 'unknown',
182
+ ...(identifier(entry.disposition, env) === undefined ? {} : { disposition: identifier(entry.disposition, env) }),
183
+ ...(entry.transcriptBytes === undefined ? {} : { transcriptBytes: entry.transcriptBytes }),
184
+ }));
185
+ if (digest === undefined && roster.length <= 1)
186
+ return {};
187
+ // The digest carries a sandbox-free copy of the transcript's facts. `file`
188
+ // names a path on *this* machine, which is neither useful to a reader of the
189
+ // dashboard nor something to publish; the byte counts beside it are.
190
+ const file = record(digest?.['file']);
191
+ const detail = {
192
+ ...(digest === undefined ? {} : {
193
+ transcript: {
194
+ ...digest,
195
+ ...(file === undefined ? {} : {
196
+ file: Object.fromEntries(Object.entries(file).filter(([key]) => key !== 'path')),
197
+ }),
198
+ },
199
+ }),
200
+ ...(roster.length === 0 ? {} : { attempts: roster }),
201
+ ...(attempts.length > roster.length ? { attemptsOmitted: attempts.length - roster.length } : {}),
202
+ };
203
+ if (Buffer.byteLength(JSON.stringify(detail), 'utf8') <= DETAIL_MAX_BYTES)
204
+ return { detail };
205
+ // Over the cap: drop the transcript's free text and its tool roster — the
206
+ // largest fields by far — and say the detail was cut rather than dropping it
207
+ // whole, which would take the attempt history with it.
208
+ const transcript = record(detail['transcript']);
209
+ const reduced = {
210
+ ...(transcript === undefined ? {} : {
211
+ transcript: Object.fromEntries(Object.entries(transcript).filter(([key]) => key === 'attempt' || key === 'exit_code'
212
+ || key === 'file' || key === 'result')),
213
+ }),
214
+ ...(roster.length === 0 ? {} : { attempts: roster }),
215
+ };
216
+ if (Buffer.byteLength(JSON.stringify(reduced), 'utf8') <= DETAIL_MAX_BYTES) {
217
+ return { detail: reduced, truncated: true };
218
+ }
219
+ return { detail: { attempts: roster.slice(-1) }, truncated: true };
220
+ }
221
+ /**
222
+ * Every `step.completed` the journal holds, in order, by step id.
223
+ *
224
+ * `foldRunState` keeps only the *last* attempt, because that is what a status
225
+ * view shows. The final report's `detail.attempts` is the whole roster, and
226
+ * its token totals are the sum across attempts, so both need the raw entries.
227
+ */
228
+ function attemptsByStep(events) {
229
+ const byStep = new Map();
230
+ for (const event of events) {
231
+ if (event.entry_type !== 'step.completed' || event.step_id === null)
232
+ continue;
233
+ const payload = record(event.payload) ?? {};
234
+ const budget = record(payload['budget']) ?? {};
235
+ const digest = record(record(payload['trajectory_tail'])?.['transcript']);
236
+ const file = record(digest?.['file']);
237
+ const result = record(digest?.['result']);
238
+ const entries = byStep.get(event.step_id) ?? [];
239
+ entries.push({
240
+ attempt: event.attempt ?? entries.length + 1,
241
+ atMs: event.at_ms,
242
+ completionReason: typeof payload['completionReason'] === 'string' ? payload['completionReason'] : 'unknown',
243
+ disposition: typeof payload['disposition'] === 'string' ? payload['disposition'] : 'unknown',
244
+ trajectoryTail: payload['trajectory_tail'],
245
+ ...(int32(file?.['bytes_kept']) === undefined ? {} : { transcriptBytes: int32(file?.['bytes_kept']) }),
246
+ ...(typeof file?.['path'] === 'string' ? { transcriptPath: file['path'] } : {}),
247
+ ...(int32(budget['tokens_in']) === undefined ? {} : { tokensIn: int32(budget['tokens_in']) }),
248
+ ...(int32(budget['tokens_out']) === undefined ? {} : { tokensOut: int32(budget['tokens_out']) }),
249
+ ...(typeof result?.['total_cost_usd'] === 'number' && Number.isFinite(result['total_cost_usd'])
250
+ && result['total_cost_usd'] >= 0
251
+ ? { costUsd: result['total_cost_usd'] } : {}),
252
+ });
253
+ byStep.set(event.step_id, entries);
254
+ }
255
+ return byStep;
256
+ }
257
+ function finalStep(step, attempts, env) {
258
+ const stepName = identifier(step.id, env);
259
+ const stepType = identifier(step.type, env);
260
+ if (stepName === undefined || stepType === undefined)
261
+ return undefined;
262
+ const completionReason = step.completion_reason ?? step.last_attempt?.completion_reason ?? 'unknown';
263
+ const succeeded = completionReason === SUCCESS_COMPLETION_REASON;
264
+ const transcript = step.last_attempt?.transcript ?? null;
265
+ const startMs = step.started_at_ms;
266
+ const endMs = step.last_attempt?.ended_at_ms ?? null;
267
+ const duration = startMs !== null && endMs !== null ? Math.max(0, endMs - startMs) : (step.elapsed_ms ?? 0);
268
+ const tokensIn = attempts.reduce((total, entry) => total + (entry.tokensIn ?? 0), 0);
269
+ const tokensOut = attempts.reduce((total, entry) => total + (entry.tokensOut ?? 0), 0);
270
+ const failure = transcript?.failure ?? null;
271
+ // Summed across attempts, exactly as the tokens above are. Taking the last
272
+ // attempt's figure while summing its tokens was inconsistent in itself, and
273
+ // Cloud totals these rows for the run's spend — so a retried agent's earlier
274
+ // charges simply vanished from the run.
275
+ const spentUsd = attempts.reduce((total, entry) => total + (entry.costUsd ?? 0), 0);
276
+ const detail = stepDetail(attempts, env);
277
+ const verification = step.last_attempt?.verification ?? null;
278
+ // What the step said about itself. A gate's verdict detail is the nearest
279
+ // thing a deterministic step has to an agent's final message; an agent step
280
+ // has neither in the status view, so the completion reason stands alone
281
+ // rather than being invented.
282
+ const summary = text(verification?.detail, env, OUTPUT_SUMMARY_MAX_CHARS)
283
+ ?? `step ${succeeded ? 'completed' : 'ended'}: ${identifier(completionReason, env) ?? 'unknown'}`;
284
+ const model = identifier(transcript?.model, env);
285
+ const error = succeeded ? undefined : text(failure?.excerpt, env, ERROR_MAX_CHARS);
286
+ return {
287
+ stepName,
288
+ stepType,
289
+ // Cloud's legacy v1 columns. The kernel has no agent/preset/CLI identity
290
+ // per step, and an empty string is the honest answer the hosted v2
291
+ // executor gives too — never a guess that would render as a real name.
292
+ agent: '',
293
+ preset: '',
294
+ cli: '',
295
+ // Named after the uploaded transcript object once one is written, exactly
296
+ // as the sandbox does; empty until then, never a fabricated sandbox id.
297
+ sandboxId: '',
298
+ startTime: isoAt(startMs),
299
+ endTime: isoAt(endMs),
300
+ durationMs: int32(duration) ?? 0,
301
+ exitCode: succeeded ? 0 : 1,
302
+ outputSummary: summary,
303
+ status: succeeded ? 'completed' : 'failed',
304
+ completionReason: identifier(completionReason, env) ?? 'unknown',
305
+ retryCount: Math.max(0, attempts.length - 1),
306
+ ...(model === undefined ? {} : { model }),
307
+ ...(tokensIn > 0 ? { tokensInput: Math.min(tokensIn, MAX_INT32) } : {}),
308
+ ...(tokensOut > 0 ? { tokensOutput: Math.min(tokensOut, MAX_INT32) } : {}),
309
+ ...(spentUsd > 0 ? { costUsd: spentUsd } : {}),
310
+ ...(error === undefined ? {} : { error }),
311
+ ...(detail.detail === undefined ? {} : { detail: detail.detail }),
312
+ ...(detail.truncated === undefined ? {} : { detailTruncated: detail.truncated }),
313
+ };
314
+ }
315
+ /** Per-attempt transcript files this step left on disk, in attempt order. */
316
+ function transcriptRef(stepName, attempts) {
317
+ const files = attempts
318
+ .filter((entry) => entry.transcriptPath !== undefined)
319
+ .map(entry => ({ attempt: entry.attempt, path: entry.transcriptPath }));
320
+ return files.length === 0 ? undefined : { stepName, attempts: files };
321
+ }
322
+ /**
323
+ * Fold one journal into everything the mirror can say about it.
324
+ *
325
+ * The authored root is deliberately not published as a step: it spans the
326
+ * whole flow, so a snapshot carrying it would show one node called
327
+ * `authored-root` sitting at 100% for the run's entire duration beside the
328
+ * steps that actually did the work. Its journal is still read, for the step
329
+ * index that names the child journals and their graph edges.
330
+ */
331
+ export function mirrorJournal(runId, events, nowMs, env = process.env) {
332
+ const view = foldRunState(events, nowMs);
333
+ const attempts = attemptsByStep(events);
334
+ const steps = [];
335
+ const finals = [];
336
+ const transcripts = [];
337
+ for (const step of view.steps) {
338
+ if (step.id === AUTHORED_ROOT_STEP)
339
+ continue;
340
+ const live = snapshotStep(runId, step, env);
341
+ if (live !== undefined)
342
+ steps.push(live);
343
+ const stepAttempts = attempts.get(step.id) ?? [];
344
+ if (step.state === 'done') {
345
+ const row = finalStep(step, stepAttempts, env);
346
+ if (row !== undefined) {
347
+ finals.push(row);
348
+ const ref = transcriptRef(row.stepName, stepAttempts);
349
+ if (ref !== undefined)
350
+ transcripts.push(ref);
351
+ }
352
+ }
353
+ }
354
+ const index = authoredIndex(events, env);
355
+ // A declarative flow declares its edges in the spec, not in an authored-step
356
+ // stream — so a YAML run had no hints at all and drew every node
357
+ // unconnected. Read them from `run.spawned`, keyed the same way, and let the
358
+ // authored index win where both exist (an authored root's index is the
359
+ // richer record, and carries labels too).
360
+ const declared = declaredEdges(runId, events, env);
361
+ for (const [key, hint] of declared) {
362
+ if (!index.hints.has(key))
363
+ index.hints.set(key, hint);
364
+ }
365
+ return {
366
+ runId,
367
+ status: view.status,
368
+ terminal: view.status === 'completed' || view.status === 'failed' || view.status === 'cancelled',
369
+ steps,
370
+ finals,
371
+ transcripts,
372
+ children: index.children,
373
+ hints: index.hints,
374
+ };
375
+ }
376
+ /**
377
+ * An authored root's step index: which child journal runs each authored step,
378
+ * what the author called it, and what it came after.
379
+ *
380
+ * This is the only place those facts exist. A child journal's own view knows
381
+ * its kernel step ids and nothing about the authored graph above it, so
382
+ * without the root's index a mirrored authored run would show its steps with
383
+ * no names and no edges — which is exactly what the run graph draws from.
384
+ */
385
+ function authoredIndex(events, env) {
386
+ const messages = [];
387
+ for (const event of events) {
388
+ if (event.entry_type !== 'stream.appended')
389
+ continue;
390
+ const payload = record(event.payload);
391
+ if (payload?.['stream'] === AUTHORED_STEP_STREAM)
392
+ messages.push(payload['message']);
393
+ }
394
+ const children = [];
395
+ const hints = new Map();
396
+ for (const entry of foldAuthoredStepRecords(messages).values()) {
397
+ if (/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(entry.runId))
398
+ children.push(entry.runId);
399
+ const name = label(entry.label, env);
400
+ const after = entry.after === undefined
401
+ ? undefined
402
+ : [...entry.after]
403
+ .slice(0, DEPENDS_ON_MAX_ENTRIES)
404
+ .map(value => identifier(value, env))
405
+ .filter((value) => value !== undefined);
406
+ if (name === undefined && after === undefined)
407
+ continue;
408
+ hints.set(`${entry.runId}/${entry.step}`, {
409
+ ...(name === undefined ? {} : { label: name }),
410
+ ...(after === undefined ? {} : { after }),
411
+ });
412
+ }
413
+ return { children, hints };
414
+ }
415
+ /**
416
+ * The `depends_on` a declarative spec declares, as graph hints.
417
+ *
418
+ * `foldRunState` reads these to decide readiness but does not surface them on
419
+ * `StepView`, and deliberately: `flows status --json` is a pinned shape. So
420
+ * they are read here, straight off the `run.spawned` payload this fold already
421
+ * has in hand, rather than by widening a view other readers depend on.
422
+ */
423
+ function declaredEdges(runId, events, env) {
424
+ const hints = new Map();
425
+ const spawned = events.find(event => event.entry_type === 'run.spawned');
426
+ const steps = record(spawned?.payload)?.['spec'];
427
+ const declared = record(steps)?.['steps'];
428
+ if (!Array.isArray(declared))
429
+ return hints;
430
+ for (const entry of declared) {
431
+ const step = record(entry);
432
+ const id = identifier(step?.['id'], env);
433
+ if (id === undefined)
434
+ continue;
435
+ const raw = step?.['depends_on'] ?? step?.['dependsOn'];
436
+ if (!Array.isArray(raw))
437
+ continue;
438
+ const after = raw
439
+ .slice(0, DEPENDS_ON_MAX_ENTRIES)
440
+ .map(value => identifier(value, env))
441
+ .filter((value) => value !== undefined);
442
+ hints.set(`${runId}/${id}`, { after });
443
+ }
444
+ return hints;
445
+ }
446
+ /**
447
+ * Build a snapshot envelope that actually fits both bounds.
448
+ *
449
+ * The count cap applies unconditionally — 65 tiny steps are 65 steps. Only
450
+ * then does the byte cap bite: first the artifact *names* go (their count
451
+ * survives), then the `dependsOn` edges, then whole entries from the head of
452
+ * the display order, because the tail is the newest work and that is what a
453
+ * live view exists to show. A capped view announces itself as incomplete;
454
+ * silently showing fewer steps than ran is the one thing it must not do.
455
+ */
456
+ export function fitSnapshot(steps, envelope) {
457
+ let kept = [...steps];
458
+ let omitted = envelope.alreadyOmitted ?? 0;
459
+ let truncated = omitted > 0;
460
+ if (kept.length > SNAPSHOT_MAX_STEPS) {
461
+ omitted += kept.length - SNAPSHOT_MAX_STEPS;
462
+ kept = kept.slice(kept.length - SNAPSHOT_MAX_STEPS);
463
+ truncated = true;
464
+ }
465
+ const build = () => ({
466
+ sequence: envelope.sequence,
467
+ capturedAt: envelope.capturedAt,
468
+ ...(truncated ? { truncated: true } : {}),
469
+ ...(omitted > 0 ? { omittedStepCount: Math.min(omitted, MAX_INT32) } : {}),
470
+ steps: kept,
471
+ });
472
+ const bytes = () => Buffer.byteLength(JSON.stringify(build()), 'utf8');
473
+ if (bytes() <= SNAPSHOT_MAX_BYTES)
474
+ return build();
475
+ kept = kept.map(({ artifacts: _artifacts, ...step }) => step);
476
+ truncated = true;
477
+ if (bytes() <= SNAPSHOT_MAX_BYTES)
478
+ return build();
479
+ kept = kept.map(({ dependsOn: _dependsOn, ...step }) => step);
480
+ if (bytes() <= SNAPSHOT_MAX_BYTES)
481
+ return build();
482
+ while (kept.length > 1 && bytes() > SNAPSHOT_MAX_BYTES) {
483
+ kept = kept.slice(1);
484
+ omitted += 1;
485
+ }
486
+ return build();
487
+ }
488
+ /** Apply an authored root's graph hints to a step, bounded for the live view. */
489
+ export function withGraphHints(step, hints, journalRunId, maxDependsOn, knownSteps) {
490
+ const hint = hints.get(`${journalRunId}/${step.stepName}`);
491
+ if (hint === undefined)
492
+ return step;
493
+ // Only predecessors that are themselves steps of this report: an edge to a
494
+ // node the graph does not contain draws nothing and reads as data loss.
495
+ const after = hint.after
496
+ ?.filter(name => name !== step.stepName && knownSteps.has(name))
497
+ .slice(0, maxDependsOn);
498
+ return {
499
+ ...step,
500
+ ...(hint.label === undefined ? {} : { label: hint.label }),
501
+ ...(after === undefined ? {} : { dependsOn: after }),
502
+ };
503
+ }
504
+ //# sourceMappingURL=cloud-mirror-step.js.map