@relayflows/sdk 2.0.30 → 2.0.31

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 (295) 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-root.d.ts +5 -0
  38. package/dist/authored-root.d.ts.map +1 -1
  39. package/dist/authored-root.js +20 -2
  40. package/dist/authored-root.js.map +1 -1
  41. package/dist/authored-step-output.d.ts +35 -10
  42. package/dist/authored-step-output.d.ts.map +1 -1
  43. package/dist/authored-step-output.js +108 -40
  44. package/dist/authored-step-output.js.map +1 -1
  45. package/dist/authored-verdict.d.ts +28 -0
  46. package/dist/authored-verdict.d.ts.map +1 -0
  47. package/dist/authored-verdict.js +79 -0
  48. package/dist/authored-verdict.js.map +1 -0
  49. package/dist/authored-worker-step.d.ts +5 -2
  50. package/dist/authored-worker-step.d.ts.map +1 -1
  51. package/dist/authored-worker-step.js +48 -11
  52. package/dist/authored-worker-step.js.map +1 -1
  53. package/dist/cli/check-worker-surface.d.ts +27 -0
  54. package/dist/cli/check-worker-surface.d.ts.map +1 -0
  55. package/dist/cli/check-worker-surface.js +63 -0
  56. package/dist/cli/check-worker-surface.js.map +1 -0
  57. package/dist/cli/check.d.ts +19 -2
  58. package/dist/cli/check.d.ts.map +1 -1
  59. package/dist/cli/check.js +12 -4
  60. package/dist/cli/check.js.map +1 -1
  61. package/dist/cli/cloud-format.d.ts +9 -0
  62. package/dist/cli/cloud-format.d.ts.map +1 -0
  63. package/dist/cli/cloud-format.js +77 -0
  64. package/dist/cli/cloud-format.js.map +1 -0
  65. package/dist/cli/cloud-live.d.ts +39 -0
  66. package/dist/cli/cloud-live.d.ts.map +1 -0
  67. package/dist/cli/cloud-live.js +325 -0
  68. package/dist/cli/cloud-live.js.map +1 -0
  69. package/dist/cli/cloud-read.d.ts +3 -7
  70. package/dist/cli/cloud-read.d.ts.map +1 -1
  71. package/dist/cli/cloud-read.js +14 -266
  72. package/dist/cli/cloud-read.js.map +1 -1
  73. package/dist/cli/cloud-refusal.d.ts +39 -0
  74. package/dist/cli/cloud-refusal.d.ts.map +1 -0
  75. package/dist/cli/cloud-refusal.js +95 -0
  76. package/dist/cli/cloud-refusal.js.map +1 -0
  77. package/dist/cli/cloud-status-view.d.ts +7 -0
  78. package/dist/cli/cloud-status-view.d.ts.map +1 -0
  79. package/dist/cli/cloud-status-view.js +214 -0
  80. package/dist/cli/cloud-status-view.js.map +1 -0
  81. package/dist/cli/direct-run.d.ts.map +1 -1
  82. package/dist/cli/direct-run.js +16 -2
  83. package/dist/cli/direct-run.js.map +1 -1
  84. package/dist/cli/hn-monitor.d.ts +0 -13
  85. package/dist/cli/hn-monitor.d.ts.map +1 -1
  86. package/dist/cli/hn-monitor.js +2 -1
  87. package/dist/cli/hn-monitor.js.map +1 -1
  88. package/dist/cli/local-agent-remedy.d.ts +80 -0
  89. package/dist/cli/local-agent-remedy.d.ts.map +1 -0
  90. package/dist/cli/local-agent-remedy.js +116 -0
  91. package/dist/cli/local-agent-remedy.js.map +1 -0
  92. package/dist/cli/observer-session.d.ts +41 -0
  93. package/dist/cli/observer-session.d.ts.map +1 -0
  94. package/dist/cli/observer-session.js +78 -0
  95. package/dist/cli/observer-session.js.map +1 -0
  96. package/dist/cli/run.d.ts +30 -2
  97. package/dist/cli/run.d.ts.map +1 -1
  98. package/dist/cli/run.js +186 -24
  99. package/dist/cli/run.js.map +1 -1
  100. package/dist/cli/status.d.ts +9 -0
  101. package/dist/cli/status.d.ts.map +1 -1
  102. package/dist/cli/status.js +31 -2
  103. package/dist/cli/status.js.map +1 -1
  104. package/dist/cli/step-evidence.d.ts +90 -0
  105. package/dist/cli/step-evidence.d.ts.map +1 -0
  106. package/dist/cli/step-evidence.js +259 -0
  107. package/dist/cli/step-evidence.js.map +1 -0
  108. package/dist/cli/step-failure.d.ts +14 -4
  109. package/dist/cli/step-failure.d.ts.map +1 -1
  110. package/dist/cli/step-failure.js +41 -76
  111. package/dist/cli/step-failure.js.map +1 -1
  112. package/dist/cli-commands.d.ts +6 -0
  113. package/dist/cli-commands.d.ts.map +1 -1
  114. package/dist/cli-commands.js +2 -0
  115. package/dist/cli-commands.js.map +1 -1
  116. package/dist/cli.d.ts +10 -0
  117. package/dist/cli.d.ts.map +1 -1
  118. package/dist/cli.js +53 -42
  119. package/dist/cli.js.map +1 -1
  120. package/dist/cloud-read.d.ts +15 -0
  121. package/dist/cloud-read.d.ts.map +1 -1
  122. package/dist/cloud-read.js +20 -1
  123. package/dist/cloud-read.js.map +1 -1
  124. package/dist/cloud-run-record.d.ts +27 -0
  125. package/dist/cloud-run-record.d.ts.map +1 -0
  126. package/dist/cloud-run-record.js +56 -0
  127. package/dist/cloud-run-record.js.map +1 -0
  128. package/dist/cloud-run.d.ts +2 -9
  129. package/dist/cloud-run.d.ts.map +1 -1
  130. package/dist/cloud-run.js +3 -20
  131. package/dist/cloud-run.js.map +1 -1
  132. package/dist/communication/local.d.ts.map +1 -1
  133. package/dist/communication/local.js +2 -1
  134. package/dist/communication/local.js.map +1 -1
  135. package/dist/communication/worker.d.ts +1 -1
  136. package/dist/communication/worker.d.ts.map +1 -1
  137. package/dist/communication/worker.js +13 -5
  138. package/dist/communication/worker.js.map +1 -1
  139. package/dist/compile.d.ts.map +1 -1
  140. package/dist/compile.js +28 -6
  141. package/dist/compile.js.map +1 -1
  142. package/dist/direct-input.d.ts.map +1 -1
  143. package/dist/direct-input.js +21 -1
  144. package/dist/direct-input.js.map +1 -1
  145. package/dist/failure-kinds.d.ts +96 -6
  146. package/dist/failure-kinds.d.ts.map +1 -1
  147. package/dist/failure-kinds.js +29 -2
  148. package/dist/failure-kinds.js.map +1 -1
  149. package/dist/flow-requirements.d.ts.map +1 -1
  150. package/dist/flow-requirements.js +24 -9
  151. package/dist/flow-requirements.js.map +1 -1
  152. package/dist/gate-contract.d.ts +7 -0
  153. package/dist/gate-contract.d.ts.map +1 -1
  154. package/dist/gate-contract.js +6 -1
  155. package/dist/gate-contract.js.map +1 -1
  156. package/dist/helper-preflight.d.ts.map +1 -1
  157. package/dist/helper-preflight.js +10 -3
  158. package/dist/helper-preflight.js.map +1 -1
  159. package/dist/helper-reference.d.ts +25 -0
  160. package/dist/helper-reference.d.ts.map +1 -0
  161. package/dist/helper-reference.js +129 -0
  162. package/dist/helper-reference.js.map +1 -0
  163. package/dist/index.d.ts +1 -1
  164. package/dist/index.d.ts.map +1 -1
  165. package/dist/index.js.map +1 -1
  166. package/dist/journal-client.d.ts +3 -1
  167. package/dist/journal-client.d.ts.map +1 -1
  168. package/dist/journal-client.js +17 -2
  169. package/dist/journal-client.js.map +1 -1
  170. package/dist/journal-projection.d.ts +16 -0
  171. package/dist/journal-projection.d.ts.map +1 -0
  172. package/dist/journal-projection.js +108 -0
  173. package/dist/journal-projection.js.map +1 -0
  174. package/dist/llm-worker.js +1 -1
  175. package/dist/llm-worker.js.map +1 -1
  176. package/dist/local-agent.d.ts +1 -1
  177. package/dist/local-agent.d.ts.map +1 -1
  178. package/dist/local-agent.js +4 -3
  179. package/dist/local-agent.js.map +1 -1
  180. package/dist/named-gate-lowering.js +35 -5
  181. package/dist/named-gate-lowering.js.map +1 -1
  182. package/dist/named-gate-preflight.d.ts +27 -0
  183. package/dist/named-gate-preflight.d.ts.map +1 -0
  184. package/dist/named-gate-preflight.js +47 -0
  185. package/dist/named-gate-preflight.js.map +1 -0
  186. package/dist/named-gates.d.ts +1 -1
  187. package/dist/named-gates.d.ts.map +1 -1
  188. package/dist/named-gates.js +3 -0
  189. package/dist/named-gates.js.map +1 -1
  190. package/dist/observer-link.d.ts +7 -0
  191. package/dist/observer-link.d.ts.map +1 -1
  192. package/dist/observer-link.js +3 -1
  193. package/dist/observer-link.js.map +1 -1
  194. package/dist/preflight.d.ts.map +1 -1
  195. package/dist/preflight.js +7 -0
  196. package/dist/preflight.js.map +1 -1
  197. package/dist/protocol.d.ts +2 -0
  198. package/dist/protocol.d.ts.map +1 -1
  199. package/dist/redact.d.ts +42 -0
  200. package/dist/redact.d.ts.map +1 -1
  201. package/dist/redact.js +128 -0
  202. package/dist/redact.js.map +1 -1
  203. package/dist/run-projection.d.ts +83 -0
  204. package/dist/run-projection.d.ts.map +1 -0
  205. package/dist/run-projection.js +199 -0
  206. package/dist/run-projection.js.map +1 -0
  207. package/dist/shell-word.d.ts +19 -0
  208. package/dist/shell-word.d.ts.map +1 -0
  209. package/dist/shell-word.js +23 -0
  210. package/dist/shell-word.js.map +1 -0
  211. package/dist/spec.d.ts +52 -3
  212. package/dist/spec.d.ts.map +1 -1
  213. package/dist/spec.js.map +1 -1
  214. package/dist/step-fields.d.ts +1 -1
  215. package/dist/step-fields.js +1 -1
  216. package/dist/step-fields.js.map +1 -1
  217. package/dist/steps-green.d.ts +27 -0
  218. package/dist/steps-green.d.ts.map +1 -0
  219. package/dist/steps-green.js +164 -0
  220. package/dist/steps-green.js.map +1 -0
  221. package/dist/validate.d.ts.map +1 -1
  222. package/dist/validate.js +39 -8
  223. package/dist/validate.js.map +1 -1
  224. package/dist/worker-lease.d.ts +8 -1
  225. package/dist/worker-lease.d.ts.map +1 -1
  226. package/dist/worker-lease.js +34 -4
  227. package/dist/worker-lease.js.map +1 -1
  228. package/dist/worker.d.ts +8 -0
  229. package/dist/worker.d.ts.map +1 -1
  230. package/dist/worker.js +17 -9
  231. package/dist/worker.js.map +1 -1
  232. package/package.json +3 -7
  233. package/src/agent-artifacts.ts +2 -10
  234. package/src/agent-cwd.ts +139 -0
  235. package/src/artifact-scan-policy.ts +51 -0
  236. package/src/authored-completion-record.ts +119 -0
  237. package/src/authored-completion.ts +203 -0
  238. package/src/authored-flow-error.ts +13 -1
  239. package/src/authored-flow-executor.ts +91 -58
  240. package/src/authored-human.ts +1 -4
  241. package/src/authored-node-entry.ts +4 -1
  242. package/src/authored-node-runner.ts +96 -22
  243. package/src/authored-root.ts +20 -2
  244. package/src/authored-step-output.ts +139 -42
  245. package/src/authored-verdict.ts +87 -0
  246. package/src/authored-worker-step.ts +60 -12
  247. package/src/cli/check-worker-surface.ts +66 -0
  248. package/src/cli/check.ts +35 -4
  249. package/src/cli/cloud-format.ts +82 -0
  250. package/src/cli/cloud-live.ts +366 -0
  251. package/src/cli/cloud-read.ts +13 -282
  252. package/src/cli/cloud-refusal.ts +113 -0
  253. package/src/cli/cloud-status-view.ts +213 -0
  254. package/src/cli/direct-run.ts +19 -2
  255. package/src/cli/hn-monitor.ts +2 -1
  256. package/src/cli/local-agent-remedy.ts +160 -0
  257. package/src/cli/observer-session.ts +107 -0
  258. package/src/cli/run.ts +233 -28
  259. package/src/cli/status.ts +59 -3
  260. package/src/cli/step-evidence.ts +310 -0
  261. package/src/cli/step-failure.ts +57 -81
  262. package/src/cli-commands.ts +2 -0
  263. package/src/cli.ts +64 -44
  264. package/src/cloud-read.ts +25 -1
  265. package/src/cloud-run-record.ts +64 -0
  266. package/src/cloud-run.ts +5 -24
  267. package/src/communication/local.ts +2 -1
  268. package/src/communication/worker.ts +13 -5
  269. package/src/compile.ts +28 -6
  270. package/src/direct-input.ts +22 -1
  271. package/src/failure-kinds.ts +104 -2
  272. package/src/flow-requirements.ts +24 -9
  273. package/src/gate-contract.ts +13 -1
  274. package/src/helper-preflight.ts +10 -3
  275. package/src/helper-reference.ts +130 -0
  276. package/src/index.ts +2 -0
  277. package/src/journal-client.ts +19 -2
  278. package/src/journal-projection.ts +106 -0
  279. package/src/llm-worker.ts +1 -1
  280. package/src/local-agent.ts +4 -2
  281. package/src/named-gate-lowering.ts +35 -5
  282. package/src/named-gate-preflight.ts +47 -0
  283. package/src/named-gates.ts +3 -0
  284. package/src/observer-link.ts +10 -1
  285. package/src/preflight.ts +7 -0
  286. package/src/protocol.ts +2 -0
  287. package/src/redact.ts +111 -0
  288. package/src/run-projection.ts +247 -0
  289. package/src/shell-word.ts +24 -0
  290. package/src/spec.ts +54 -3
  291. package/src/step-fields.ts +1 -1
  292. package/src/steps-green.ts +168 -0
  293. package/src/validate.ts +35 -8
  294. package/src/worker-lease.ts +35 -5
  295. package/src/worker.ts +27 -11
package/src/cli/check.ts CHANGED
@@ -6,6 +6,7 @@ import { dirname, isAbsolute, join, parse as parsePath, resolve } from 'node:pat
6
6
  import { spawnSync } from 'node:child_process';
7
7
  import { parse as parseYaml } from 'yaml';
8
8
  import { CompileError, compileSpec, kernelToAuthoring } from '../compile.js';
9
+ import { agentWorkerDiagnostics } from './check-worker-surface.js';
9
10
  import { helperReady } from '../yaml-helper-effect.js';
10
11
  import { flowRequirements, type FlowRequirements } from '../flow-requirements.js';
11
12
  import {
@@ -117,6 +118,24 @@ export interface CheckExecution {
117
118
  flow?: FlowSpec;
118
119
  }
119
120
 
121
+ /**
122
+ * Facts about the *caller*, not about the spec, that change which diagnostics
123
+ * apply. Preflight stays a pure function of the spec plus environment probes;
124
+ * anything that depends on how the flow is about to be invoked opts in here.
125
+ */
126
+ export interface CheckInvocation {
127
+ /**
128
+ * Report `agent_worker_unresolved` when the spec has `agent` steps.
129
+ *
130
+ * Only `flows check` sets this. `flows run` attaches its own worker under
131
+ * `--local-agent` and knows the answer, `flows build` and `flows deploy`
132
+ * check a spec that will run elsewhere, and an SDK caller that reaches
133
+ * `checkAuthoredFlow` directly is generally running a worker already —
134
+ * warning any of them would be noise about a question they have answered.
135
+ */
136
+ warnUnresolvedAgentWorker?: boolean;
137
+ }
138
+
120
139
  export class CheckFailure extends Error {
121
140
  constructor(readonly kind: CheckFailureKind, message: string) {
122
141
  super(message);
@@ -124,7 +143,7 @@ export class CheckFailure extends Error {
124
143
  }
125
144
 
126
145
  /** Validate and preflight one working-tree spec without starting a run. */
127
- export function checkFlow(path: string): CheckExecution {
146
+ export function checkFlow(path: string, invocation: CheckInvocation = {}): CheckExecution {
128
147
  const absolutePath = resolve(path);
129
148
  try {
130
149
  const source = readFlowSource(absolutePath);
@@ -134,7 +153,7 @@ export function checkFlow(path: string): CheckExecution {
134
153
  : [];
135
154
  let execution: CheckExecution;
136
155
  try {
137
- execution = checkAuthoredFlow(readFlow(source, absolutePath), path);
156
+ execution = checkAuthoredFlow(readFlow(source, absolutePath), path, undefined, invocation);
138
157
  } catch (error) {
139
158
  if (!(error instanceof CheckFailure)) throw error;
140
159
  execution = { report: inputFailureReport(error, path) };
@@ -164,7 +183,12 @@ function safeRequirements(authoring: FlowSpec, projectCli: string | undefined):
164
183
  }
165
184
 
166
185
  /** Preflight a validated authored flow through the same path as YAML/JSON. */
167
- export function checkAuthoredFlow(authoring: FlowSpec, path: string, projectConfig?: ProjectConfig): CheckExecution {
186
+ export function checkAuthoredFlow(
187
+ authoring: FlowSpec,
188
+ path: string,
189
+ projectConfig?: ProjectConfig,
190
+ invocation: CheckInvocation = {},
191
+ ): CheckExecution {
168
192
  const absolutePath = resolve(path);
169
193
  try {
170
194
  const config = projectConfig ?? readProjectConfig(dirname(absolutePath));
@@ -195,6 +219,13 @@ export function checkAuthoredFlow(authoring: FlowSpec, path: string, projectConf
195
219
  result.diagnostics.push({ severity: 'warning', kind: 'budget_unmetered',
196
220
  message: 'Managed communication sessions do not report token or dollar usage. Budget ceilings cannot bound their spend; communication.timeoutMs bounds their duration.' });
197
221
  }
222
+ // Reported whatever preflight concluded. An environment refusal (a missing
223
+ // CLI, an unknown model) is fixed and rerun; the worker question is still
224
+ // open on the next pass, and staying silent about it here is what made an
225
+ // author meet it one dead run at a time.
226
+ const workerSurface = invocation.warnUnresolvedAgentWorker === true
227
+ ? agentWorkerDiagnostics(authoring)
228
+ : [];
198
229
  return {
199
230
  report: {
200
231
  ok: result.ok,
@@ -202,7 +233,7 @@ export function checkAuthoredFlow(authoring: FlowSpec, path: string, projectConf
202
233
  ...(config.path !== undefined ? { projectConfigPath: config.path } : {}),
203
234
  gates: result.gates,
204
235
  resolutions: result.resolutions,
205
- diagnostics: result.diagnostics,
236
+ diagnostics: [...result.diagnostics, ...workerSurface],
206
237
  requirements: safeRequirements(authoring, config.cli),
207
238
  },
208
239
  ...(result.ok && flow !== undefined ? { flow } : {}),
@@ -0,0 +1,82 @@
1
+ // The cells every hosted-run page is built from.
2
+ //
3
+ // Moved out of `cli/cloud-read.ts` verbatim when the live views (`--watch`,
4
+ // `--follow`) needed the same formatting: the run list, the status page and
5
+ // the watched page must render a count, a cost and an instant identically, or
6
+ // a reader would have to learn which verb they were looking at first.
7
+ //
8
+ // Depends on nothing in `cli/` but `formatDuration`, so every other Cloud CLI
9
+ // module can import it without an import cycle.
10
+
11
+ import { formatDuration } from './status.js';
12
+
13
+ export function thousands(value: number): string {
14
+ return String(value).replace(/\B(?=(\d{3})+(?!\d))/gu, ',');
15
+ }
16
+
17
+ export function dollars(value: number): string {
18
+ return `$${value.toFixed(6).replace(/0+$/u, '').replace(/\.$/u, '')}`;
19
+ }
20
+
21
+ /** Agent- and flow-authored names cannot inject terminal control sequences. */
22
+ export function safe(text: string): string {
23
+ return text.replace(/[\u0000-\u001F\u007F-\u009F]/gu, '?');
24
+ }
25
+
26
+ /**
27
+ * Render a run's `error` as readable lines rather than one control-char smear.
28
+ *
29
+ * Cloud stores the runner's terminal output in this field, newlines and all, so
30
+ * passing it through `safe()` alone turns a 200-line tail into a single line of
31
+ * `?` separators. Long runs are dominated by lease renewals — one line every
32
+ * 10s for the life of every agent step, differing only in the deadline — which
33
+ * are worth counting, not reading.
34
+ *
35
+ * Collapsing is deliberately narrow: two adjacent lines merge only when they
36
+ * are character-for-character identical once a trailing integer is masked. A
37
+ * shared prefix is NOT line identity — runner lines put the step name, reason
38
+ * or message after a long fixed prefix, so collapsing on a prefix would hide
39
+ * distinct diagnostics behind a similarity count. The final line never
40
+ * collapses into an earlier one, because that is where the failure is.
41
+ */
42
+ const TRAILING_NUMBER = /\d+(?=\D{0,2}$)/u;
43
+
44
+ export function errorLines(text: string, indent: string): string[] {
45
+ const raw = text.split(/\r\n|\r|\n/u).map((line) => line.trimEnd()).filter((line) => line !== '');
46
+ if (raw.length === 0) return [];
47
+
48
+ const key = (line: string): string => line.replace(TRAILING_NUMBER, '#');
49
+ const collapsed: { line: string; count: number }[] = [];
50
+ raw.forEach((line, index) => {
51
+ const previous = collapsed.at(-1);
52
+ const isLast = index === raw.length - 1;
53
+ if (previous !== undefined && !isLast && key(previous.line) === key(line)) previous.count += 1;
54
+ else collapsed.push({ line, count: 1 });
55
+ });
56
+
57
+ const rendered = collapsed.map(({ line, count }) =>
58
+ count === 1 ? safe(line) : `${safe(line)} (${count} times, differing only in a number)`);
59
+
60
+ const HEAD = 2;
61
+ const TAIL = 12;
62
+ if (rendered.length <= HEAD + TAIL + 1) return rendered.map((line) => `${indent}${line}`);
63
+ const elided = rendered.length - HEAD - TAIL;
64
+ return [
65
+ ...rendered.slice(0, HEAD),
66
+ `… ${elided} more line${elided === 1 ? '' : 's'} (full text: --json)`,
67
+ ...rendered.slice(-TAIL),
68
+ ].map((line) => `${indent}${line}`);
69
+ }
70
+
71
+ /** ISO-8601 to the second: a list column, not a timestamp to do arithmetic on. */
72
+ export function instant(value: string | null): string {
73
+ if (value === null) return 'unknown';
74
+ const parsed = Date.parse(value);
75
+ return Number.isFinite(parsed) ? new Date(parsed).toISOString().replace(/\.\d{3}Z$/u, 'Z') : 'unknown';
76
+ }
77
+
78
+ export function ago(value: string | null, now: number): string {
79
+ if (value === null) return 'unknown';
80
+ const parsed = Date.parse(value);
81
+ return Number.isFinite(parsed) ? `${formatDuration(now - parsed)} ago` : 'unknown';
82
+ }
@@ -0,0 +1,366 @@
1
+ // `flows status --cloud --watch` and `flows logs <run> --follow`: the two
2
+ // hosted reads that keep reading.
3
+ //
4
+ // The one-shot verbs (cli/cloud-read.ts) answer "what did that run do". These
5
+ // two answer "what is it doing", by asking again until the run is over. Three
6
+ // properties separate them from a loop around the one-shot reads:
7
+ //
8
+ // 1. **The exit code is the run's.** A finished page is not evidence that the
9
+ // run succeeded; `getCloudRunDetailLive` validates the same record
10
+ // `flows run --wait` blocks on, so `--watch` and `--follow` exit 0 only on
11
+ // an attested `completed`/`success`, 1 on an attested failure or a
12
+ // cancellation, and refuse a terminal record that attests neither.
13
+ // 2. **A frame is whole or absent.** The page is rendered, then the abort is
14
+ // checked, then the whole page leaves in one `io.stdout` call. A Ctrl-C
15
+ // mid-poll ends the command with a refusal and no half-drawn screen.
16
+ // 3. **Nothing is invented while waiting.** A failed poll leaves the previous
17
+ // page and the consumed log exactly where they were; it never clears the
18
+ // screen to show an error, and never re-prints a line it has shown.
19
+ //
20
+ // Cancellation is the caller's: `runCli` hands these functions the signal it
21
+ // owns for the verb's duration, and nothing here installs a process handler.
22
+ // Aborting stops the observation, not the hosted run — the refusal says so.
23
+
24
+ import { canonicalize } from '../canonical.js';
25
+ import {
26
+ getCloudRunDetailLive, getCloudRunLog, getCloudRunSteps,
27
+ type CloudRunDetail, type CloudRunLog, type CloudStep,
28
+ } from '../cloud-read.js';
29
+ import { isCloudRunActive, type CloudRunState } from '../cloud-run-record.js';
30
+ import { endsWithOpenCredentialHeader, openCredentialStart, openSecretStart, redact } from '../redact.js';
31
+ import { thousands } from './cloud-format.js';
32
+ import { fail, isTransientRead, refusalFor, RUN_ID_REQUIRED, type CloudReadOptions } from './cloud-refusal.js';
33
+ import { renderCloudStatus, scrubRun, scrubSteps } from './cloud-status-view.js';
34
+ import { sleepInterruptible } from './interruptible-sleep.js';
35
+ import type { CliIo } from '../cli.js';
36
+
37
+ /** The cadence `waitForCloudFlowRun` polls at; not a user flag on either verb. */
38
+ const DEFAULT_POLL_INTERVAL_MS = 2_000;
39
+ const MAX_BACKOFF_MS = 30_000;
40
+
41
+ export interface CloudLiveOptions extends CloudReadOptions {
42
+ /** Milliseconds between polls. Injected by tests; 1..60000, as the waiter accepts. */
43
+ pollIntervalMs?: number;
44
+ /** Injected by tests so no suite sleeps; production uses the abortable sleep. */
45
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
46
+ }
47
+
48
+ /** Clears the screen only for a terminal; a redirected page must stay text. */
49
+ function clearSequence(io: CliIo): string {
50
+ return io.tty === true ? '\u001b[2J\u001b[H' : '';
51
+ }
52
+
53
+ /** The same delay schedule as `waitForCloudFlowRun`: ×2 per failure, capped. */
54
+ function delayFor(failures: number, interval: number): number {
55
+ return failures === 0 ? interval : Math.min(interval * 2 ** (failures - 1), MAX_BACKOFF_MS);
56
+ }
57
+
58
+ /** The hosted `flows run --wait` mapping: only an attested success is 0. */
59
+ function exitFor(state: CloudRunState): 0 | 1 {
60
+ return state.status === 'completed' ? 0 : 1;
61
+ }
62
+
63
+ function aborted(verb: 'watching' | 'following', runId: string, json: boolean, io: CliIo): 1 {
64
+ fail({
65
+ code: 'observation_aborted', exit: 1,
66
+ message: `Stopped ${verb} run ${runId}; the hosted run has not been cancelled.`,
67
+ }, json, io);
68
+ return 1;
69
+ }
70
+
71
+ /**
72
+ * Has the caller cancelled?
73
+ *
74
+ * A function rather than `signal?.aborted` at each site on purpose: `aborted`
75
+ * is a readonly property, so an inline check narrows the signal's type for the
76
+ * rest of the block and the compiler then calls every later check dead — which
77
+ * is exactly backwards for a value that changes under an await.
78
+ */
79
+ function isAborted(signal: AbortSignal | undefined): boolean {
80
+ return signal !== undefined && signal.aborted;
81
+ }
82
+
83
+ function invalidInterval(interval: number): boolean {
84
+ return !Number.isSafeInteger(interval) || interval < 1 || interval > 60_000;
85
+ }
86
+
87
+ // -------------------------------------------------- flows status --cloud --watch
88
+
89
+ /**
90
+ * Redraw the hosted status page until the run is terminal, then leave the
91
+ * final page up and exit with the run's outcome.
92
+ *
93
+ * The detail and the step rows are two requests against two projections, so
94
+ * the page is a pair of reads and not an atomic snapshot: a step row can lag
95
+ * the header it is drawn under by one poll. That is a property of the API, and
96
+ * this view reports what each read said rather than reconciling them.
97
+ */
98
+ export async function runCloudStatusWatch(
99
+ args: { runId?: string; json: boolean },
100
+ io: CliIo,
101
+ options: CloudLiveOptions = {},
102
+ ): Promise<0 | 1 | 2> {
103
+ const env = options.env ?? process.env;
104
+ const clock = options.now ?? Date.now;
105
+ const signal = options.signal;
106
+ const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
107
+ const sleep = options.sleep ?? sleepInterruptible;
108
+ if (args.runId === undefined || args.runId.length === 0) return fail(RUN_ID_REQUIRED, args.json, io);
109
+ const runId = args.runId;
110
+ if (invalidInterval(interval)) {
111
+ return fail({ code: 'cloud_configuration', exit: 2, message: 'pollIntervalMs must be an integer from 1 to 60000.' },
112
+ args.json, io);
113
+ }
114
+
115
+ let failures = 0;
116
+ for (;;) {
117
+ if (isAborted(signal)) return aborted('watching', runId, args.json, io);
118
+ let live: { detail: CloudRunDetail; state: CloudRunState };
119
+ let steps: CloudStep[];
120
+ try {
121
+ live = await getCloudRunDetailLive(runId, options);
122
+ if (isAborted(signal)) return aborted('watching', runId, args.json, io);
123
+ steps = await getCloudRunSteps(runId, options);
124
+ } catch (error) {
125
+ if (isAborted(signal)) return aborted('watching', runId, args.json, io);
126
+ if (!isTransientRead(error)) return fail(refusalFor(error, `run ${runId}`, env), args.json, io);
127
+ // The previous page stays exactly as it was: a poll that did not
128
+ // complete is not news about the run.
129
+ failures = Math.min(failures + 1, 16);
130
+ await sleep(delayFor(failures, interval), signal);
131
+ continue;
132
+ }
133
+ failures = 0;
134
+
135
+ const run = scrubRun(live.detail, env);
136
+ const scrubbed = scrubSteps(steps, env);
137
+ const terminal = !isCloudRunActive(live.state.status);
138
+ // Rendered before the abort check and emitted after it, in one call: an
139
+ // interrupt between two lines of a frame would leave a torn page.
140
+ const page = args.json ? '' : `${clearSequence(io)}${renderCloudStatus(run, scrubbed, clock()).join('\n')}`;
141
+ if (isAborted(signal)) return aborted('watching', runId, args.json, io);
142
+ if (!args.json) io.stdout(page);
143
+ if (terminal) {
144
+ if (args.json) io.stdout(canonicalize({ v: 1, ok: true, run, steps: scrubbed, now_ms: clock() }));
145
+ return exitFor(live.state);
146
+ }
147
+ await sleep(interval, signal);
148
+ }
149
+ }
150
+
151
+ // ------------------------------------------------------ flows logs --follow
152
+
153
+ /**
154
+ * What has been shown of the runner log, and where the rest starts.
155
+ *
156
+ * Bookkeeping is kept on the log exactly as Cloud served it, before redaction:
157
+ * the un-released remainder is redacted as one block on every poll, so a
158
+ * secret is matched against the whole text it spans — several lines of a PEM,
159
+ * or halves that arrived in two different polls — rather than against one line
160
+ * at a time, which no multi-line value can ever match.
161
+ */
162
+ interface LogFollowState {
163
+ /** The whole log as last served, held to prove the next read extends it. */
164
+ consumed: string;
165
+ /** How much of `consumed` has been printed; the rest is still redactable. */
166
+ released: number;
167
+ emitted: boolean;
168
+ }
169
+
170
+ /**
171
+ * Print `text` as lines.
172
+ *
173
+ * Splitting is on `\n` only, and one trailing `\r` per line is dropped: a
174
+ * CRLF log printed with its carriage returns intact makes a terminal overwrite
175
+ * each line it just drew. A final newline ends the last line rather than
176
+ * starting an empty one. Blank lines and repeated identical lines are
177
+ * preserved — they are the log.
178
+ */
179
+ function writeLines(text: string, state: LogFollowState, io: CliIo): void {
180
+ const lines = text.split('\n');
181
+ if (lines.at(-1) === '') lines.pop();
182
+ for (const line of lines) {
183
+ io.stdout(line.replace(/\r$/u, ''));
184
+ state.emitted = true;
185
+ }
186
+ }
187
+
188
+ /** The last line boundary at or before `at`: 0, or the index after a newline. */
189
+ function lineBoundaryAtOrBefore(text: string, at: number): number {
190
+ return at <= 0 ? 0 : text.lastIndexOf('\n', at - 1) + 1;
191
+ }
192
+
193
+ /**
194
+ * Release every line the log has settled on, redacted as one block.
195
+ *
196
+ * Four things hold a line back. `openSecretStart` marks where a secret value
197
+ * has begun and not ended, so nothing at or past it can be shown until the
198
+ * next poll completes it. `openCredentialStart` marks a trailing credential
199
+ * header — `authorization:`, `Bearer`, a callback-token name, or an
200
+ * unterminated credential JSON field — whose value may only arrive on a later
201
+ * poll; releasing the header first would leave the value without the context
202
+ * the redactor needs. A block is never ended on a bare credential header even
203
+ * when more text follows, because the redactor folds the header's newline
204
+ * into its own match — the block-prefix check cannot see that the header's
205
+ * value lives on the next line. And a candidate block is released only when
206
+ * redacting it alone gives the same text as the front of the whole redacted
207
+ * remainder: if the cut fell inside something the redactor would have caught —
208
+ * the second line of a private key — the two disagree, and the cut moves back
209
+ * a line and is tried again.
210
+ *
211
+ * A poll that can release nothing prints nothing; the bytes are not lost, they
212
+ * are held until a later poll or the drain flush can redact them whole.
213
+ */
214
+ function releaseLines(state: LogFollowState, io: CliIo, env: NodeJS.ProcessEnv): void {
215
+ const raw = state.consumed;
216
+ if (state.released >= raw.length) return;
217
+ const remainder = redact(raw.slice(state.released), env);
218
+ let cut = lineBoundaryAtOrBefore(raw, Math.min(openSecretStart(raw, env), openCredentialStart(raw)));
219
+ while (cut > state.released) {
220
+ if (endsWithOpenCredentialHeader(raw.slice(state.released, cut))) {
221
+ // A bare credential header as the released block's last line strands
222
+ // the value that starts on the next line — redact needs them together.
223
+ // Shrink until the header is inside the held remainder; it releases
224
+ // with its value line once that line is complete.
225
+ cut = lineBoundaryAtOrBefore(raw, cut - 1);
226
+ continue;
227
+ }
228
+ const block = redact(raw.slice(state.released, cut), env);
229
+ if (remainder.startsWith(block)) {
230
+ writeLines(block, state, io);
231
+ state.released = cut;
232
+ return;
233
+ }
234
+ cut = lineBoundaryAtOrBefore(raw, cut - 1);
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Has Cloud finished publishing this log?
240
+ *
241
+ * Three facts, all required. The run being over does not mean the last bytes
242
+ * have been written; `done` alone does not mean the run is over (the route can
243
+ * report a completed *upload* of a log the run is still adding to); and a
244
+ * `done` envelope that carries fewer bytes than it advertises has not served
245
+ * the tail. Stopping on any one of them alone would truncate the output, which
246
+ * is the one thing a follow must not do.
247
+ */
248
+ function logDrained(log: CloudRunLog, terminal: boolean, content: string): boolean {
249
+ return terminal && log.done && Buffer.byteLength(content, 'utf8') >= log.total_size;
250
+ }
251
+
252
+ /**
253
+ * Append the hosted runner log until the run is terminal and its log is drained.
254
+ *
255
+ * The route serves the log from an offset, but this client does not page it:
256
+ * the offsets are byte counts and the content is a JavaScript string, and
257
+ * subtracting one from the other silently loses text the moment a log contains
258
+ * a non-ASCII character — which the runner's own transition lines do. Until
259
+ * the byte-range contract can be checked against the server, each poll reads
260
+ * the whole log and prints the part that is new, refusing outright if what it
261
+ * already showed is no longer a prefix of what Cloud serves. That costs a full
262
+ * read per poll and holds the log in memory; it cannot duplicate or drop a line.
263
+ */
264
+ export async function runCloudLogsFollow(
265
+ args: { runId: string; step: string | undefined; json: boolean },
266
+ io: CliIo,
267
+ options: CloudLiveOptions = {},
268
+ ): Promise<0 | 1 | 2> {
269
+ const env = options.env ?? process.env;
270
+ const signal = options.signal;
271
+ const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
272
+ const sleep = options.sleep ?? sleepInterruptible;
273
+ const runId = args.runId;
274
+ // Refused before any request: a step transcript is not an append-only stream
275
+ // this verb can follow. A retry replaces it, and the rendered form is built
276
+ // from the whole JSONL — attempt markers, session header, result footer —
277
+ // rather than a line at a time.
278
+ if (args.step !== undefined) {
279
+ return fail({
280
+ code: 'invalid_invocation', exit: 2,
281
+ message: '`flows logs --follow` follows the runner log, which is append-only; it cannot follow a step '
282
+ + 'transcript. Follow the run with `flows logs <run-id> --follow`, or read the step transcript once '
283
+ + 'with `flows logs <run-id> --step <name>`.',
284
+ }, args.json, io);
285
+ }
286
+ if (invalidInterval(interval)) {
287
+ return fail({ code: 'cloud_configuration', exit: 2, message: 'pollIntervalMs must be an integer from 1 to 60000.' },
288
+ args.json, io);
289
+ }
290
+
291
+ const state: LogFollowState = { consumed: '', released: 0, emitted: false };
292
+ let header = false;
293
+ let failures = 0;
294
+ // A snapshot that satisfies every drain fact can still predate terminality:
295
+ // `done` can describe an upload finished while the run kept writing, and the
296
+ // log route can keep serving that snapshot past the terminal transition.
297
+ // The read that ends the follow has to postdate the terminal observation —
298
+ // which on the first sighting it cannot — so a terminal run always gets one
299
+ // more poll before its log counts as drained.
300
+ let terminalObserved = false;
301
+ for (;;) {
302
+ if (isAborted(signal)) return aborted('following', runId, args.json, io);
303
+ let outcome: CloudRunState;
304
+ let log: CloudRunLog;
305
+ try {
306
+ // The run record first: a log read that follows a terminal status can
307
+ // only be missing bytes Cloud had not published yet, never bytes written
308
+ // after the check.
309
+ const live = await getCloudRunDetailLive(runId, options);
310
+ if (isAborted(signal)) return aborted('following', runId, args.json, io);
311
+ log = await getCloudRunLog(runId, undefined, options);
312
+ outcome = live.state;
313
+ } catch (error) {
314
+ if (isAborted(signal)) return aborted('following', runId, args.json, io);
315
+ if (!isTransientRead(error)) return fail(refusalFor(error, `run ${runId}`, env), args.json, io);
316
+ failures = Math.min(failures + 1, 16);
317
+ await sleep(delayFor(failures, interval), signal);
318
+ continue;
319
+ }
320
+ failures = 0;
321
+ if (isAborted(signal)) return aborted('following', runId, args.json, io);
322
+
323
+ if (!log.content.startsWith(state.consumed)) {
324
+ return fail({
325
+ code: 'cloud_log_rewritten', exit: 1,
326
+ message: `Cloud's runner log for run ${runId} no longer begins with the ${thousands(state.consumed.length)} `
327
+ + 'characters already shown, so following it would skip or repeat output. Read it whole with '
328
+ + `\`flows logs ${runId}\`.`,
329
+ }, args.json, io);
330
+ }
331
+ state.consumed = log.content;
332
+ const terminal = !isCloudRunActive(outcome.status);
333
+ const drained = terminalObserved && logDrained(log, terminal, log.content);
334
+ terminalObserved ||= terminal;
335
+
336
+ if (!args.json) {
337
+ if (!header) {
338
+ io.stdout(`LOG ${runId} runner following ${thousands(log.total_size)} bytes so far`);
339
+ header = true;
340
+ }
341
+ releaseLines(state, io, env);
342
+ }
343
+ if (!drained) {
344
+ await sleep(interval, signal);
345
+ continue;
346
+ }
347
+ // Drained: the last line may have no newline, and this is the only moment
348
+ // at which printing it cannot cut a line in half.
349
+ if (args.json) {
350
+ io.stdout(canonicalize({
351
+ v: 1, ok: true, run_id: runId, step: null,
352
+ bytes: log.offset, total_bytes: log.total_size, done: log.done,
353
+ content: redact(log.content, env),
354
+ }));
355
+ return exitFor(outcome);
356
+ }
357
+ if (state.released < state.consumed.length) {
358
+ writeLines(redact(state.consumed.slice(state.released), env), state, io);
359
+ state.released = state.consumed.length;
360
+ }
361
+ if (!state.emitted) io.stdout(' (empty)');
362
+ io.stdout(`${outcome.status.toUpperCase()} ${runId} completionReason: `
363
+ + `${'completionReason' in outcome ? outcome.completionReason : 'unavailable'}`);
364
+ return exitFor(outcome);
365
+ }
366
+ }