@relayflows/sdk 2.0.31 → 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 (76) hide show
  1. package/dist/authored-preflight.d.ts +4 -0
  2. package/dist/authored-preflight.d.ts.map +1 -0
  3. package/dist/authored-preflight.js +50 -0
  4. package/dist/authored-preflight.js.map +1 -0
  5. package/dist/authored-worker-step.d.ts.map +1 -1
  6. package/dist/authored-worker-step.js +3 -2
  7. package/dist/authored-worker-step.js.map +1 -1
  8. package/dist/cli/check.d.ts +10 -2
  9. package/dist/cli/check.d.ts.map +1 -1
  10. package/dist/cli/check.js +16 -137
  11. package/dist/cli/check.js.map +1 -1
  12. package/dist/cli/cli-probe.d.ts +20 -0
  13. package/dist/cli/cli-probe.d.ts.map +1 -0
  14. package/dist/cli/cli-probe.js +166 -0
  15. package/dist/cli/cli-probe.js.map +1 -0
  16. package/dist/cli/cloud-mirror-session.d.ts +97 -0
  17. package/dist/cli/cloud-mirror-session.d.ts.map +1 -0
  18. package/dist/cli/cloud-mirror-session.js +264 -0
  19. package/dist/cli/cloud-mirror-session.js.map +1 -0
  20. package/dist/cli-commands.d.ts +6 -0
  21. package/dist/cli-commands.d.ts.map +1 -1
  22. package/dist/cli-commands.js +1 -0
  23. package/dist/cli-commands.js.map +1 -1
  24. package/dist/cli.d.ts +7 -0
  25. package/dist/cli.d.ts.map +1 -1
  26. package/dist/cli.js +84 -18
  27. package/dist/cli.js.map +1 -1
  28. package/dist/cloud-deploy.d.ts +1 -1
  29. package/dist/cloud-deploy.d.ts.map +1 -1
  30. package/dist/cloud-deploy.js +24 -8
  31. package/dist/cloud-deploy.js.map +1 -1
  32. package/dist/cloud-mirror-ledger.d.ts +40 -0
  33. package/dist/cloud-mirror-ledger.d.ts.map +1 -0
  34. package/dist/cloud-mirror-ledger.js +142 -0
  35. package/dist/cloud-mirror-ledger.js.map +1 -0
  36. package/dist/cloud-mirror-step.d.ts +168 -0
  37. package/dist/cloud-mirror-step.d.ts.map +1 -0
  38. package/dist/cloud-mirror-step.js +504 -0
  39. package/dist/cloud-mirror-step.js.map +1 -0
  40. package/dist/cloud-mirror-transport.d.ts +94 -0
  41. package/dist/cloud-mirror-transport.d.ts.map +1 -0
  42. package/dist/cloud-mirror-transport.js +163 -0
  43. package/dist/cloud-mirror-transport.js.map +1 -0
  44. package/dist/cloud-mirror.d.ts +132 -0
  45. package/dist/cloud-mirror.d.ts.map +1 -0
  46. package/dist/cloud-mirror.js +556 -0
  47. package/dist/cloud-mirror.js.map +1 -0
  48. package/dist/hosted-extension-runtime.js +1 -1
  49. package/dist/package-version.d.ts +10 -0
  50. package/dist/package-version.d.ts.map +1 -0
  51. package/dist/package-version.js +22 -0
  52. package/dist/package-version.js.map +1 -0
  53. package/dist/preflight.d.ts +14 -0
  54. package/dist/preflight.d.ts.map +1 -1
  55. package/dist/preflight.js +18 -3
  56. package/dist/preflight.js.map +1 -1
  57. package/dist/relay-cli.d.ts.map +1 -1
  58. package/dist/relay-cli.js +1 -21
  59. package/dist/relay-cli.js.map +1 -1
  60. package/package.json +2 -2
  61. package/src/authored-preflight.ts +46 -0
  62. package/src/authored-worker-step.ts +4 -3
  63. package/src/cli/check.ts +25 -163
  64. package/src/cli/cli-probe.ts +194 -0
  65. package/src/cli/cloud-mirror-session.ts +329 -0
  66. package/src/cli-commands.ts +1 -0
  67. package/src/cli.ts +94 -19
  68. package/src/cloud-deploy.ts +26 -8
  69. package/src/cloud-mirror-ledger.ts +161 -0
  70. package/src/cloud-mirror-step.ts +618 -0
  71. package/src/cloud-mirror-transport.ts +261 -0
  72. package/src/cloud-mirror.ts +633 -0
  73. package/src/hosted-extension-runtime.ts +1 -1
  74. package/src/package-version.ts +23 -0
  75. package/src/preflight.ts +31 -7
  76. package/src/relay-cli.ts +1 -24
@@ -0,0 +1,194 @@
1
+ import { accessSync, constants } from 'node:fs';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+ import { execFile, spawnSync } from 'node:child_process';
4
+ import { agentEnvironment, brokerEnvironment } from '../communication/environment.js';
5
+ import { adapterIdentification, authenticationProbe, cliAdapterKind, displayInvocation,
6
+ modelReadinessProbe, type CliInvocation } from '../cli-adapter.js';
7
+ import { MODEL_ENV } from '../worker-cli.js';
8
+ import { CliProbeError, type CliProbeResult } from '../preflight.js';
9
+
10
+ interface ProbeRequest {
11
+ executable: string;
12
+ directory: string;
13
+ invocation: CliInvocation;
14
+ environment: NodeJS.ProcessEnv;
15
+ }
16
+ interface ProbeOutput { status: number | null; stdout: string; stderr: string }
17
+
18
+ /** One decision sequence; checking uses synchronous I/O, live flows yield the loop. */
19
+ export function probeCli(...args: Parameters<typeof probeSequence>): CliProbeResult {
20
+ return driveSync(probeSequence(...args));
21
+ }
22
+
23
+ export async function probeCliAsync(...args: Parameters<typeof probeSequence>): Promise<CliProbeResult> {
24
+ const sequence = probeSequence(...args);
25
+ let next = sequence.next();
26
+ while (!next.done) next = sequence.next(await runProbeAsync(next.value));
27
+ return next.value;
28
+ }
29
+
30
+ export function resolveExecutable(command: string, directory: string): string | undefined {
31
+ return driveSync(executableSequence(command, directory));
32
+ }
33
+
34
+ function driveSync<T>(sequence: Generator<ProbeRequest, T, ProbeOutput>): T {
35
+ let next = sequence.next();
36
+ while (!next.done) {
37
+ const request = next.value;
38
+ const result = spawnSync(request.executable, request.invocation.args, {
39
+ ...probeOptions(request),
40
+ // Preserve the old synchronous probe contract: provider CLIs must not
41
+ // inherit a readable stdin that can block auth/identify probes.
42
+ stdio: ['ignore', 'pipe', 'pipe'],
43
+ });
44
+ const failure = classifySpawnFailure(result.error, result.signal, request.invocation.timeoutMs);
45
+ if (failure !== undefined) throw failure;
46
+ next = sequence.next({ status: result.status, stdout: result.stdout ?? '', stderr: result.stderr ?? '' });
47
+ }
48
+ return next.value;
49
+ }
50
+
51
+ function probeOptions({ directory, invocation, environment }: ProbeRequest) {
52
+ const env = { ...environment };
53
+ delete env[MODEL_ENV];
54
+ if (invocation.modelEnv !== undefined) env[MODEL_ENV] = invocation.modelEnv;
55
+ return { cwd: directory, encoding: 'utf8' as const, timeout: invocation.timeoutMs,
56
+ maxBuffer: 1024 * 1024, env };
57
+ }
58
+
59
+ function runProbeAsync(request: ProbeRequest): Promise<ProbeOutput> {
60
+ return new Promise((resolve, reject) => {
61
+ const child = execFile(request.executable, request.invocation.args, probeOptions(request),
62
+ (error, stdout, stderr) => {
63
+ // Numeric exit codes are probe results; launch, timeout, signal and buffer
64
+ // errors are failures to collect a fact, just as in the synchronous driver.
65
+ if (error?.killed && typeof error.code !== 'string') return reject(new CliProbeError(`timeout:${request.invocation.timeoutMs}ms`));
66
+ const failure = classifySpawnFailure(
67
+ error !== null && typeof error.code !== 'number' && error.signal == null ? error : undefined,
68
+ error?.signal ?? null, request.invocation.timeoutMs);
69
+ if (failure !== undefined) return reject(failure);
70
+ resolve({ status: error === null ? 0 : typeof error.code === 'number' ? error.code : null,
71
+ stdout, stderr });
72
+ });
73
+ child.stdin?.end();
74
+ });
75
+ }
76
+
77
+ function* probeSequence(
78
+ cli: string,
79
+ directory: string,
80
+ model?: string,
81
+ execution?: 'managed',
82
+ ): Generator<ProbeRequest, CliProbeResult, ProbeOutput> {
83
+ const executable = yield* executableSequence(cli, directory);
84
+ if (executable === undefined) return { exists: false, authenticated: false };
85
+ const kind = cliAdapterKind(executable);
86
+ // Relay owns interactive CLI launch/injection. Its generic PTY path is not
87
+ // the headless wrapper protocol; do not demand that protocol from Gemini,
88
+ // Cursor, OpenCode, or other interactive tools. Never invent an auth pass.
89
+ if (execution === 'managed' && kind === 'relayflows-wrapper-v1') {
90
+ return { exists: true, supported: true, authenticated: 'unverified' };
91
+ }
92
+ const environment = execution === 'managed'
93
+ ? { ...brokerEnvironment(process.env), ...agentEnvironment(executable) } : process.env;
94
+ const probe = (invocation: CliInvocation): ProbeRequest => ({ executable, directory, invocation, environment });
95
+ const identification = adapterIdentification(kind);
96
+ const identified = yield probe(identification.invocation);
97
+ if (
98
+ identified.status !== 0
99
+ || (identification.expectedStdout !== undefined
100
+ && identified.stdout.trim() !== identification.expectedStdout)
101
+ ) {
102
+ return { exists: true, supported: false, authenticated: false };
103
+ }
104
+ const auth = authenticationProbe(kind);
105
+ const authCommand = displayInvocation(cli, auth);
106
+ if (model === undefined) {
107
+ return {
108
+ exists: true,
109
+ supported: true,
110
+ authenticated: (yield probe(auth)).status === 0,
111
+ authCommand,
112
+ };
113
+ }
114
+
115
+ const scoped = modelReadinessProbe(kind, model);
116
+ const modelCommand = displayInvocation(cli, scoped);
117
+ // A successful real provider round trip (or identified wrapper probe)
118
+ // proves both auth and exact-model access. On failure, run the adapter's
119
+ // actual auth command solely to classify auth vs model access truthfully.
120
+ if ((yield probe(scoped)).status === 0) {
121
+ return {
122
+ exists: true,
123
+ supported: true,
124
+ authenticated: true,
125
+ modelAvailable: true,
126
+ authCommand,
127
+ modelCommand,
128
+ };
129
+ }
130
+ const authProbe = yield probe(auth);
131
+ const authenticated = authProbe.status === 0;
132
+ return {
133
+ exists: true,
134
+ supported: true,
135
+ authenticated,
136
+ modelAvailable: false,
137
+ authCommand,
138
+ modelCommand,
139
+ // Only on failure: on success there is nothing to explain, and the output
140
+ // is the most identity-bearing thing this function touches.
141
+ ...(authenticated
142
+ ? {}
143
+ : {
144
+ authExitCode: authProbe.status,
145
+ authFailureDetail: redactProbeOutput(
146
+ `${authProbe.stderr}${authProbe.stdout}`,
147
+ ).trim().slice(0, 500),
148
+ }),
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Redact anything that looks like a credential or an account identifier.
154
+ *
155
+ * `auth status` output is diagnostic, but it is also the one place an account
156
+ * email, org id or token fragment can appear. The point of surfacing it is to
157
+ * say WHY a probe failed, which survives redaction; leaking an identity into a
158
+ * refusal message that gets pasted into issues does not.
159
+ */
160
+ function redactProbeOutput(text: string): string {
161
+ return text
162
+ .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, '<redacted-email>')
163
+ .replace(/\b(sk|pk|oat|rt)[-_][A-Za-z0-9._-]{8,}/gi, '<redacted-token>')
164
+ .replace(/\b[A-Fa-f0-9]{32,}\b/g, '<redacted-hex>');
165
+ }
166
+
167
+ function* executableSequence(command: string, directory: string): Generator<ProbeRequest, string | undefined, ProbeOutput> {
168
+ if (command.includes('/') || isAbsolute(command)) {
169
+ const path = isAbsolute(command) ? command : resolve(directory, command);
170
+ try {
171
+ accessSync(path, constants.X_OK);
172
+ return path;
173
+ } catch {
174
+ return undefined;
175
+ }
176
+ }
177
+ const result = yield { executable: 'which', directory: process.cwd(),
178
+ invocation: { args: [command], timeoutMs: 5_000 }, environment: process.env };
179
+ return result.status === 0 ? result.stdout.trim() : undefined;
180
+ }
181
+
182
+ function classifySpawnFailure(
183
+ error: Error | undefined,
184
+ signal: NodeJS.Signals | null,
185
+ timeoutMs: number,
186
+ ): CliProbeError | undefined {
187
+ if (error !== undefined) {
188
+ const detail = (error as NodeJS.ErrnoException).code === 'ETIMEDOUT'
189
+ ? `timeout:${timeoutMs}ms` as const
190
+ : 'spawn_failed' as const;
191
+ return new CliProbeError(detail);
192
+ }
193
+ return signal === null ? undefined : new CliProbeError(`signal:${signal}`);
194
+ }
@@ -0,0 +1,329 @@
1
+ // The Cloud half of `flows run` / `flows resume`: also put this local run on
2
+ // the Cloud dashboard.
3
+ //
4
+ // Opt-in, and deliberately the only opt-in thing on this path.
5
+ //
6
+ // A local run is already watchable by default: `observer-session.ts` beside
7
+ // this one projects the run into its own channel and prints a read-only link,
8
+ // off a workspace key, for free. That is the right default — it is a step
9
+ // projection, it costs nothing, and a run that never joins a workspace is not
10
+ // a defect (RFC-0001 settled decision 7).
11
+ //
12
+ // The dashboard is the richer, hosted view of the same run: the flow source,
13
+ // every step's transcript, the run graph, the logs, and the run sitting in the
14
+ // same history as the hosted ones. It is also the one that *stores* all of
15
+ // that. So it is asked for — `--cloud-mirror`, or `FLOWS_CLOUD_MIRROR=1` for a
16
+ // shell — and never turned on by a login happening to be present. Mirroring
17
+ // someone's local runs because they once signed in is not a default anyone
18
+ // consented to.
19
+ //
20
+ // Best-effort once it is on, like the observer: a registration failure is one
21
+ // labeled stderr line, and nothing here can change a run's exit code or its
22
+ // journal. But it is a *louder* line than it used to be, because the run asked
23
+ // for this and did not get it.
24
+
25
+ import { readFile } from 'node:fs/promises';
26
+ import type { CliIo } from '../cli.js';
27
+ import { canonicalize } from '../canonical.js';
28
+ import { cloudConnection, CloudFlowError } from '../cloud-http.js';
29
+ import { recordMirroredRun, readMirroredRun } from '../cloud-mirror-ledger.js';
30
+ import { createRunMirror, readJournalEvents, type RunMirror } from '../cloud-mirror.js';
31
+ import { MirrorClient, registerLocalRun, type MirrorRunSource } from '../cloud-mirror-transport.js';
32
+ import { parseDigestReference } from '../bundle-transport.js';
33
+ import { isAuthoredFlowPath, parseDirectInput } from '../direct-input.js';
34
+ import type { ProgressEvent } from '../progress.js';
35
+ import type { RunReport } from './run.js';
36
+
37
+ /** `FLOWS_CLOUD_MIRROR=1|true|on` turns the mirror on for a whole shell. */
38
+ export const MIRROR_ENV = 'FLOWS_CLOUD_MIRROR';
39
+
40
+ /** What the mirror knows about this run on Cloud, once it is registered. */
41
+ export interface CloudMirrorReceipt {
42
+ /** Cloud's run id — the argument `flows status --cloud` and `flows logs` take. */
43
+ cloudRunId: string;
44
+ dashboardUrl: string;
45
+ }
46
+
47
+ export interface CloudMirrorSession {
48
+ /** The root run is admitted: the mirror can start reading its journal. */
49
+ onRunStarted(run: { runId: string }): void;
50
+ /**
51
+ * The registration, once it lands. Resolves to nothing when the mirror is
52
+ * off, was refused, or the run never started.
53
+ *
54
+ * Awaiting it is what lets `--json` carry the same handle the terminal line
55
+ * carries: registration is one request made when the run is admitted, so by
56
+ * the time a run has a report it has long since settled — and a consumer of
57
+ * a machine-readable report can wait for a request that has already
58
+ * happened.
59
+ */
60
+ receipt(): Promise<CloudMirrorReceipt | undefined>;
61
+ /** A journaled entry; the first one names the run for a declarative flow. */
62
+ onJournalEntry(entry: { run_id: string }): void;
63
+ /** Step transitions, pushed as lifecycle events the run page's stream shows. */
64
+ onProgress(event: ProgressEvent): void;
65
+ /** Publish the final report and the terminal status. Never rejects. */
66
+ finish(report: RunReport): Promise<void>;
67
+ }
68
+
69
+ export interface CloudMirrorDeps {
70
+ register?: typeof registerLocalRun;
71
+ createMirror?: typeof createRunMirror;
72
+ }
73
+
74
+ export interface CloudMirrorRequest {
75
+ /**
76
+ * The flow's source and input, exactly as `flows run --cloud` would send
77
+ * them. Resolved lazily, once the run id exists: a `resume` has no flow
78
+ * path at all and has to read what ran out of the journal.
79
+ */
80
+ source: (runId: string) => Promise<MirrorRunSource>;
81
+ dataDir: string;
82
+ /** Lines the CLI has printed for this run, uploaded as the run's `runner.log`. */
83
+ log: () => readonly string[];
84
+ /** How the dashboard was asked for, so a refusal can name the right switch. */
85
+ requested: 'flag' | 'env';
86
+ }
87
+
88
+ /**
89
+ * Whether this shell asked for the dashboard.
90
+ *
91
+ * Only an affirmative turns it on. Anything else — unset, empty, `0`, or a
92
+ * value nobody meant as a switch — leaves the run local, because the cost of
93
+ * reading a stray value as consent is someone's runs being uploaded.
94
+ */
95
+ export function cloudMirrorRequested(env: NodeJS.ProcessEnv): boolean {
96
+ const value = env[MIRROR_ENV]?.trim().toLowerCase();
97
+ return value === '1' || value === 'true' || value === 'on' || value === 'yes';
98
+ }
99
+
100
+ /**
101
+ * Open the session. Registration is deferred until the run id exists, so a
102
+ * refused flow never reaches Cloud at all: `flows run` on a spec that does not
103
+ * compile creates no dashboard row, the same as today.
104
+ */
105
+ export function createCloudMirrorSession(
106
+ request: CloudMirrorRequest,
107
+ io: CliIo,
108
+ env: NodeJS.ProcessEnv = process.env,
109
+ deps: CloudMirrorDeps = {},
110
+ ): CloudMirrorSession {
111
+ const register = deps.register ?? registerLocalRun;
112
+ const createMirror = deps.createMirror ?? createRunMirror;
113
+ let opening: Promise<RunMirror | undefined> | undefined;
114
+ let receipt: CloudMirrorReceipt | undefined;
115
+
116
+ const open = (runId: string): Promise<RunMirror | undefined> => opening ??= request.source(runId)
117
+ .then(register)
118
+ .then(registration => {
119
+ const mirror = createMirror({
120
+ client: new MirrorClient(registration),
121
+ dataDir: request.dataDir,
122
+ env,
123
+ diagnostic: message => io.stderr(`[cloud] ${message}`),
124
+ });
125
+ receipt = { cloudRunId: registration.runId, dashboardUrl: registration.runUrl };
126
+ // So a later `flows resume` of this same journal can name this attempt
127
+ // as its predecessor. The credential is deliberately not written; a
128
+ // resume mints its own.
129
+ void recordMirroredRun(request.dataDir, runId, {
130
+ cloudRunId: registration.runId, apiUrl: registration.apiUrl,
131
+ });
132
+ // The page, and the command that follows the same run from a terminal.
133
+ // The id is Cloud's, not the journal's, and nothing else in this
134
+ // invocation prints it — without it a reader has to pick it out of the
135
+ // URL to use any of the hosted read verbs.
136
+ io.stderr(`Dashboard: ${mirror.runUrl} · flows status --cloud --watch ${registration.runId}`);
137
+ mirror.start(runId);
138
+ return mirror;
139
+ })
140
+ .catch((error: unknown) => {
141
+ io.stderr(`[cloud] ${mirrorRefusal(error, request.requested)}`);
142
+ return undefined;
143
+ });
144
+
145
+ return {
146
+ onRunStarted(run) {
147
+ void open(run.runId);
148
+ },
149
+ onJournalEntry(entry) {
150
+ void open(entry.run_id);
151
+ },
152
+ async receipt() {
153
+ if (opening === undefined) return undefined;
154
+ await opening;
155
+ return receipt;
156
+ },
157
+ onProgress(event) {
158
+ // Fire-and-forget, and only for transitions: a `step.running` tick
159
+ // arrives every second and would say nothing the snapshot does not.
160
+ if (opening === undefined) return;
161
+ if (event.type !== 'step.started' && event.type !== 'step.completed') return;
162
+ void opening.then(mirror => mirror?.event({
163
+ eventType: `relayflow.${event.type}`,
164
+ stepName: event.stepId,
165
+ payload: { stepType: event.stepType },
166
+ }));
167
+ },
168
+ async finish(report) {
169
+ const mirror = opening === undefined ? undefined : await opening;
170
+ if (mirror === undefined) return;
171
+ await mirror.finish({
172
+ status: report.completionReason === 'canceled'
173
+ ? 'cancelled'
174
+ : report.ok ? 'completed' : 'failed',
175
+ result: completionReport(report),
176
+ ...(report.completionReason === undefined ? {} : { completionReason: report.completionReason }),
177
+ ...(terminalError(report) === undefined ? {} : { error: terminalError(report)! }),
178
+ log: request.log(),
179
+ });
180
+ },
181
+ };
182
+ }
183
+
184
+ /**
185
+ * What `flows run` mirrors: the flow file's exact bytes, and — for an authored
186
+ * flow — the input it was invoked with.
187
+ *
188
+ * The same source `flows run --cloud` would submit, so a run mirrored from a
189
+ * terminal and the same run launched hosted are recorded identically. It is
190
+ * read here rather than taken from the compiled spec because the compiled
191
+ * form is not what the author wrote, and the run page shows source.
192
+ */
193
+ export function mirrorSourceFromPath(
194
+ path: string,
195
+ inputArgument: string | undefined,
196
+ dataDir: string,
197
+ ): (runId: string) => Promise<MirrorRunSource> {
198
+ const fromJournal = mirrorSourceFromJournal(dataDir);
199
+ return async (runId) => {
200
+ // `flows run <flow>@sha256:<digest>` names a bundle, not a file on this
201
+ // disk: the runner fetches it before executing. Reading the argument as a
202
+ // path there refused the registration and left a perfectly good run off
203
+ // the dashboard, so fall back to what the journal recorded — the same
204
+ // source a resume mirrors.
205
+ if (parseDigestReference(path)) return fromJournal(runId);
206
+ const workflow = await readFile(path, 'utf8');
207
+ if (!isAuthoredFlowPath(path)) return { workflow, fileType: 'yaml' };
208
+ return { workflow, fileType: 'ts', inputs: parseDirectInput(inputArgument) };
209
+ };
210
+ }
211
+
212
+ /**
213
+ * What `flows resume` mirrors: the kernel spec the journal recorded at
214
+ * `run.spawned`, canonicalized.
215
+ *
216
+ * A resume names a run id, not a file — the flow it continues may have been
217
+ * edited or deleted since. The journal is the record of what actually ran, so
218
+ * that is what the mirror publishes, as canonical JSON (a YAML subset, the
219
+ * same representation `runInCloud` sends for a declarative flow).
220
+ *
221
+ * Each resume registers its own Cloud run, and that is deliberate rather than
222
+ * a shortcut: a mirrored run goes terminal on Cloud when the CLI exits, and
223
+ * Cloud refuses to move a terminal run back to `running`. Cloud's own v2
224
+ * resume is likewise a new attempt row, so one dashboard row per invocation is
225
+ * the shape the control plane already has — and it costs no credential stored
226
+ * on disk between invocations.
227
+ */
228
+ export function mirrorSourceFromJournal(dataDir: string): (runId: string) => Promise<MirrorRunSource> {
229
+ return async (runId) => {
230
+ // The predecessor, if this journal has been mirrored before. Read against
231
+ // the deployment this invocation will actually register with, so a run
232
+ // mirrored to staging never claims to continue an id that means something
233
+ // else in production.
234
+ const resumedFromRunId = await readMirroredRun(dataDir, runId, cloudConnection({}).baseUrl)
235
+ .catch(() => undefined);
236
+ // Through the retrying reader: a resume reads this journal while the
237
+ // daemon is writing to it, and a single `journal_busy` used to abandon
238
+ // the registration and leave the resumed run off the dashboard entirely.
239
+ for (const event of await readJournalEvents(runId, dataDir)) {
240
+ if (event.entry_type !== 'run.spawned') continue;
241
+ const payload = event.payload as { spec?: unknown } | null;
242
+ if (payload?.spec === undefined) break;
243
+ return {
244
+ workflow: canonicalize(payload.spec),
245
+ fileType: 'yaml',
246
+ ...(resumedFromRunId === undefined ? {} : { resumedFromRunId }),
247
+ };
248
+ }
249
+ throw new CloudFlowError('invalid_input',
250
+ `Run "${runId}" journals no spec to mirror; the run is unaffected.`);
251
+ };
252
+ }
253
+
254
+ /** Diagnostics one completion report carries; the rest are counted. */
255
+ const MAX_REPORT_DIAGNOSTICS = 20;
256
+ /** One diagnostic message, in code points. */
257
+ const MAX_DIAGNOSTIC_CHARS = 2_000;
258
+
259
+ /**
260
+ * The run's completion report, as the terminal callback stores it.
261
+ *
262
+ * Cloud reconciles a v2 run's reported status against this document: a
263
+ * `completed` callback whose report does not carry `ok`, `status`,
264
+ * `completionReason` and `runId` together is recorded as `failed`. That guard
265
+ * exists so a sandbox whose bootstrap exits cleanly cannot report a run that
266
+ * died at step 1 as green — and it cuts the other way too, so a mirror that
267
+ * omits the report turns a finished local run red. Those four fields are the
268
+ * contract; everything else here is what a reader of the run page gets for
269
+ * free, since the run list extracts `completionReason` from the same document.
270
+ *
271
+ * Diagnostics are bounded and their messages clipped. They are the one part of
272
+ * a report that is unbounded free text, and this document is stored whole.
273
+ */
274
+ function completionReport(report: RunReport): Record<string, unknown> {
275
+ const diagnostics = report.diagnostics.slice(0, MAX_REPORT_DIAGNOSTICS).map(entry => ({
276
+ severity: 'severity' in entry ? entry.severity : 'refusal',
277
+ kind: entry.kind,
278
+ message: [...entry.message].slice(0, MAX_DIAGNOSTIC_CHARS).join(''),
279
+ }));
280
+ return {
281
+ ok: report.ok,
282
+ command: report.command,
283
+ ...(report.runId === undefined ? {} : { runId: report.runId }),
284
+ ...(report.rootRunId === undefined ? {} : { rootRunId: report.rootRunId }),
285
+ ...(report.status === undefined ? {} : { status: report.status }),
286
+ ...(report.completionReason === undefined ? {} : { completionReason: report.completionReason }),
287
+ ...(report.completionDetail === undefined ? {} : { completionDetail: report.completionDetail }),
288
+ ...(report.completedSteps === undefined ? {} : { completedSteps: report.completedSteps }),
289
+ ...(report.parkedStep === undefined ? {} : { parkedStep: report.parkedStep }),
290
+ ...(report.parkCause === undefined ? {} : { parkCause: report.parkCause }),
291
+ ...(report.next === undefined ? {} : { next: report.next }),
292
+ ...(diagnostics.length === 0 ? {} : { diagnostics }),
293
+ ...(report.diagnostics.length > diagnostics.length
294
+ ? { diagnosticsOmitted: report.diagnostics.length - diagnostics.length }
295
+ : {}),
296
+ };
297
+ }
298
+
299
+ /**
300
+ * Why the dashboard is not getting this run, in one line a reader can act on.
301
+ *
302
+ * Every one of these is a request that was not honoured — the run asked for
303
+ * the dashboard and is not on it — so none of them read as an aside. The
304
+ * missing-login case is the common one and names the two commands that fix
305
+ * it: sign in, or stop asking.
306
+ */
307
+ function mirrorRefusal(error: unknown, requested: 'flag' | 'env'): string {
308
+ const asked = requested === 'flag' ? '--cloud-mirror' : `${MIRROR_ENV}=1`;
309
+ if (error instanceof CloudFlowError && error.code === 'configuration') {
310
+ return error.reason === 'auth_missing'
311
+ ? `${asked} asked for the Cloud dashboard, but there is no Cloud login, so this run stays local. `
312
+ + `Sign in with \`agent-relay cloud login\`, or drop ${asked}.`
313
+ : `${asked} asked for the Cloud dashboard, but this run stays local: ${error.message}`;
314
+ }
315
+ if (error instanceof CloudFlowError && error.status === 404) {
316
+ return `${asked} asked for the Cloud dashboard, but this deployment does not accept local runs; `
317
+ + 'the run itself is unaffected.';
318
+ }
319
+ return `${asked} asked for the Cloud dashboard, but this run could not be registered (${
320
+ error instanceof Error ? error.message : String(error)}); the run itself is unaffected.`;
321
+ }
322
+
323
+ /** The run's own failure text, bounded by the mirror's transport, or nothing. */
324
+ function terminalError(report: RunReport): string | undefined {
325
+ if (report.ok) return undefined;
326
+ const diagnostic = report.diagnostics.find(entry =>
327
+ 'severity' in entry && (entry.severity === 'failure' || entry.severity === 'refusal'));
328
+ return diagnostic?.message;
329
+ }
@@ -96,6 +96,7 @@ const LOCAL_EXECUTION_OPTIONS = [
96
96
  },
97
97
  { flags: '--no-spawn', description: 'Require a running relayflowd rather than starting one' },
98
98
  { flags: '--no-observer-link', description: 'Do not mint an observer link for this run' },
99
+ { flags: '--cloud-mirror', description: 'Also put this run on the Cloud dashboard (also FLOWS_CLOUD_MIRROR=1)' },
99
100
  {
100
101
  flags: '--allow-human-influenced',
101
102
  description: 'Proceed even though the run carries human-influenced state',