@relayflows/sdk 2.0.21 → 2.0.22

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 (97) hide show
  1. package/dist/agent-transcript.d.ts +186 -0
  2. package/dist/agent-transcript.d.ts.map +1 -0
  3. package/dist/agent-transcript.js +585 -0
  4. package/dist/agent-transcript.js.map +1 -0
  5. package/dist/cli/run.js +2 -1
  6. package/dist/cli/run.js.map +1 -1
  7. package/dist/cli/status.d.ts +34 -0
  8. package/dist/cli/status.d.ts.map +1 -0
  9. package/dist/cli/status.js +307 -0
  10. package/dist/cli/status.js.map +1 -0
  11. package/dist/cli/step-failure.js +31 -7
  12. package/dist/cli/step-failure.js.map +1 -1
  13. package/dist/cli-commands.d.ts +13 -0
  14. package/dist/cli-commands.d.ts.map +1 -1
  15. package/dist/cli-commands.js +11 -0
  16. package/dist/cli-commands.js.map +1 -1
  17. package/dist/cli.d.ts +2 -1
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +9 -0
  20. package/dist/cli.js.map +1 -1
  21. package/dist/failure-kinds.d.ts +15 -2
  22. package/dist/failure-kinds.d.ts.map +1 -1
  23. package/dist/failure-kinds.js +8 -0
  24. package/dist/failure-kinds.js.map +1 -1
  25. package/dist/journal-reader.d.ts +1 -1
  26. package/dist/journal-reader.d.ts.map +1 -1
  27. package/dist/journal-reader.js +3 -1
  28. package/dist/journal-reader.js.map +1 -1
  29. package/dist/llm-worker.d.ts.map +1 -1
  30. package/dist/llm-worker.js +12 -1
  31. package/dist/llm-worker.js.map +1 -1
  32. package/dist/permissions-preflight.d.ts +22 -0
  33. package/dist/permissions-preflight.d.ts.map +1 -0
  34. package/dist/permissions-preflight.js +49 -0
  35. package/dist/permissions-preflight.js.map +1 -0
  36. package/dist/preflight.d.ts.map +1 -1
  37. package/dist/preflight.js +6 -0
  38. package/dist/preflight.js.map +1 -1
  39. package/dist/pty-sidechannel.d.ts +7 -0
  40. package/dist/pty-sidechannel.d.ts.map +1 -1
  41. package/dist/pty-sidechannel.js.map +1 -1
  42. package/dist/redact.d.ts +16 -0
  43. package/dist/redact.d.ts.map +1 -0
  44. package/dist/redact.js +104 -0
  45. package/dist/redact.js.map +1 -0
  46. package/dist/run-state.d.ts +124 -0
  47. package/dist/run-state.d.ts.map +1 -0
  48. package/dist/run-state.js +368 -0
  49. package/dist/run-state.js.map +1 -0
  50. package/dist/spec.d.ts +16 -1
  51. package/dist/spec.d.ts.map +1 -1
  52. package/dist/spec.js.map +1 -1
  53. package/dist/step-env.d.ts +25 -0
  54. package/dist/step-env.d.ts.map +1 -0
  55. package/dist/step-env.js +34 -0
  56. package/dist/step-env.js.map +1 -0
  57. package/dist/transcript-tail.d.ts +54 -0
  58. package/dist/transcript-tail.d.ts.map +1 -0
  59. package/dist/transcript-tail.js +176 -0
  60. package/dist/transcript-tail.js.map +1 -0
  61. package/dist/worker-cli.d.ts +10 -0
  62. package/dist/worker-cli.d.ts.map +1 -1
  63. package/dist/worker-cli.js +158 -16
  64. package/dist/worker-cli.js.map +1 -1
  65. package/dist/worker-usage.d.ts +7 -2
  66. package/dist/worker-usage.d.ts.map +1 -1
  67. package/dist/worker-usage.js +21 -3
  68. package/dist/worker-usage.js.map +1 -1
  69. package/dist/worker.d.ts.map +1 -1
  70. package/dist/worker.js +31 -6
  71. package/dist/worker.js.map +1 -1
  72. package/dist/wrapper-runtime.d.ts +7 -1
  73. package/dist/wrapper-runtime.d.ts.map +1 -1
  74. package/dist/wrapper-runtime.js +7 -1
  75. package/dist/wrapper-runtime.js.map +1 -1
  76. package/package.json +2 -2
  77. package/src/agent-transcript.ts +651 -0
  78. package/src/cli/run.ts +2 -1
  79. package/src/cli/status.ts +329 -0
  80. package/src/cli/step-failure.ts +32 -7
  81. package/src/cli-commands.ts +11 -0
  82. package/src/cli.ts +8 -0
  83. package/src/failure-kinds.ts +15 -1
  84. package/src/journal-reader.ts +4 -2
  85. package/src/llm-worker.ts +12 -1
  86. package/src/permissions-preflight.ts +53 -0
  87. package/src/preflight.ts +6 -0
  88. package/src/pty-sidechannel.ts +7 -0
  89. package/src/redact.ts +106 -0
  90. package/src/run-state.ts +468 -0
  91. package/src/spec.ts +16 -1
  92. package/src/step-env.ts +47 -0
  93. package/src/transcript-tail.ts +193 -0
  94. package/src/worker-cli.ts +157 -17
  95. package/src/worker-usage.ts +26 -3
  96. package/src/worker.ts +32 -6
  97. package/src/wrapper-runtime.ts +7 -1
@@ -0,0 +1,193 @@
1
+ // Bounded transcript tails: the last 64 KiB of an agent attempt's stdout and
2
+ // stderr, on disk beside its `pty.sock`.
3
+ //
4
+ // Nothing else holds the transcript. The worker buffers it in memory and
5
+ // publishes it live to the sidechannel; a failed agent attempt's output is
6
+ // nulled in the journal (machine.rs), leaving at most 2,000 chars of gate
7
+ // `detail`. So "why did my last attempt end" was unanswerable from disk.
8
+ //
9
+ // These files are evidence, not the record: best-effort, bounded, rewritten
10
+ // in place, never a reason for a step to fail. The journal remains truth.
11
+ // The file is raw; `flows status` redacts on read, which is the same trust
12
+ // boundary as `pty.sock` today (same OS user, mode 0600).
13
+
14
+ import { mkdir, open, readFile, rename } from 'node:fs/promises';
15
+ import { dirname, join } from 'node:path';
16
+ import { ptySocketPath } from './pty-sidechannel.js';
17
+ import { redact } from './redact.js';
18
+ import type { StepTails, TailSource, TranscriptTail } from './cli/status.js';
19
+ import type { StepView } from './run-state.js';
20
+
21
+ export const TAIL_CAPACITY_BYTES = 64 * 1024;
22
+ /** At most four rewrites a second, however fast the agent talks. */
23
+ export const TAIL_FLUSH_INTERVAL_MS = 250;
24
+ /**
25
+ * How long a spawn's completion will wait for the final tail flush. Transcript
26
+ * evidence is best-effort, so a stalled filesystem must cost the step this
27
+ * much and no more — past it the invocation settles and the close runs on.
28
+ */
29
+ export const TAIL_CLOSE_TIMEOUT_MS = 2_000;
30
+
31
+ export type TailStream = 'stdout' | 'stderr';
32
+
33
+ export interface TailIdentity {
34
+ dataDir: string;
35
+ runId: string;
36
+ stepId: string;
37
+ attempt: number;
38
+ }
39
+
40
+ /** The first line of every tail file, so a stale file is never mistaken for this attempt's. */
41
+ export interface TailHeader {
42
+ v: 1;
43
+ run_id: string;
44
+ step_id: string;
45
+ attempt: number;
46
+ started_at_ms: number;
47
+ }
48
+
49
+ export function transcriptTailPath(identity: TailIdentity, stream: TailStream): string {
50
+ if (!Number.isSafeInteger(identity.attempt) || identity.attempt < 0) throw new Error('Invalid transcript tail attempt');
51
+ return join(dirname(ptySocketPath(identity)), `attempt-${identity.attempt}.${stream}.tail`);
52
+ }
53
+
54
+ export interface TranscriptTailWriter {
55
+ append(chunk: Buffer): void;
56
+ /** Flush what is pending and stop. Resolves once the last write has settled, success or not. */
57
+ close(): Promise<void>;
58
+ }
59
+
60
+ /**
61
+ * A ring of the last {@link TAIL_CAPACITY_BYTES} bytes, flushed to
62
+ * `attempt-<n>.<stream>.tail` at most every {@link TAIL_FLUSH_INTERVAL_MS}.
63
+ * A write failure is reported once as a process warning and then ignored:
64
+ * the attempt continues, and `flows status` will say no transcript is on disk.
65
+ */
66
+ export function openTranscriptTail(
67
+ identity: TailIdentity,
68
+ stream: TailStream,
69
+ startedAtMs = Date.now(),
70
+ warn: (message: string) => void = (message) => process.emitWarning(message),
71
+ ): TranscriptTailWriter {
72
+ const path = transcriptTailPath(identity, stream);
73
+ const header = JSON.stringify({ v: 1, run_id: identity.runId, step_id: identity.stepId, attempt: identity.attempt, started_at_ms: startedAtMs } satisfies TailHeader);
74
+ const ring: Buffer[] = [];
75
+ let ringBytes = 0;
76
+ let dirty = false;
77
+ let closed = false;
78
+ let failed = false;
79
+ let timer: NodeJS.Timeout | undefined;
80
+ let inFlight: Promise<void> = Promise.resolve();
81
+
82
+ const flush = (): Promise<void> => {
83
+ if (!dirty || failed) return inFlight;
84
+ dirty = false;
85
+ const body = Buffer.concat([Buffer.from(`${header}\n`), ...ring]);
86
+ inFlight = inFlight.then(async () => {
87
+ // Write beside, then rename over: a reader never sees a torn file.
88
+ const staging = `${path}.tmp`;
89
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
90
+ const file = await open(staging, 'w', 0o600);
91
+ try { await file.writeFile(body); } finally { await file.close(); }
92
+ await rename(staging, path);
93
+ }).catch((error: unknown) => {
94
+ if (failed) return;
95
+ failed = true;
96
+ warn(`Transcript tail for ${identity.runId}/${identity.stepId} attempt ${identity.attempt} (${stream}) could not be written; the step continues without it: ${error instanceof Error ? error.message : String(error)}`);
97
+ });
98
+ return inFlight;
99
+ };
100
+
101
+ return {
102
+ append(chunk) {
103
+ if (closed || failed || chunk.length === 0) return;
104
+ if (chunk.length >= TAIL_CAPACITY_BYTES) {
105
+ ring.splice(0, ring.length, Buffer.from(chunk.subarray(chunk.length - TAIL_CAPACITY_BYTES)));
106
+ ringBytes = TAIL_CAPACITY_BYTES;
107
+ } else {
108
+ ring.push(Buffer.from(chunk));
109
+ ringBytes += chunk.length;
110
+ while (ringBytes > TAIL_CAPACITY_BYTES) {
111
+ const excess = ringBytes - TAIL_CAPACITY_BYTES;
112
+ const head = ring[0]!;
113
+ if (head.length <= excess) { ring.shift(); ringBytes -= head.length; } else { ring[0] = head.subarray(excess); ringBytes -= excess; }
114
+ }
115
+ }
116
+ dirty = true;
117
+ if (timer === undefined) {
118
+ timer = setTimeout(() => { timer = undefined; void flush(); }, TAIL_FLUSH_INTERVAL_MS);
119
+ timer.unref();
120
+ }
121
+ },
122
+ async close() {
123
+ if (closed) return;
124
+ closed = true;
125
+ if (timer !== undefined) { clearTimeout(timer); timer = undefined; }
126
+ await flush();
127
+ },
128
+ };
129
+ }
130
+
131
+ /** A tail file parsed and checked against the attempt it claims to be. */
132
+ export interface ReadTail {
133
+ header: TailHeader;
134
+ /** Bytes of transcript on disk, after the header line. */
135
+ bytes: number;
136
+ text: string;
137
+ }
138
+
139
+ /**
140
+ * Read one tail file. `undefined` when absent, unparseable, or written for a
141
+ * different attempt — or for this attempt number but before the journal says
142
+ * the attempt began, which is a file left by an earlier life of this data dir.
143
+ */
144
+ export async function readTranscriptTail(
145
+ identity: TailIdentity,
146
+ stream: TailStream,
147
+ attemptStartedAtMs: number | null,
148
+ ): Promise<ReadTail | undefined> {
149
+ let raw: Buffer;
150
+ try {
151
+ raw = await readFile(transcriptTailPath(identity, stream));
152
+ } catch (error) {
153
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
154
+ throw error;
155
+ }
156
+ const newline = raw.indexOf(10);
157
+ if (newline < 0) return undefined;
158
+ let header: unknown;
159
+ try { header = JSON.parse(raw.subarray(0, newline).toString('utf8')); } catch { return undefined; }
160
+ if (header === null || typeof header !== 'object') return undefined;
161
+ const claimed = header as Partial<TailHeader>;
162
+ if (claimed.v !== 1 || claimed.run_id !== identity.runId || claimed.step_id !== identity.stepId
163
+ || claimed.attempt !== identity.attempt || typeof claimed.started_at_ms !== 'number') return undefined;
164
+ if (attemptStartedAtMs !== null && claimed.started_at_ms < attemptStartedAtMs) return undefined;
165
+ const body = raw.subarray(newline + 1);
166
+ return { header: claimed as TailHeader, bytes: body.length, text: body.toString('utf8') };
167
+ }
168
+
169
+ /**
170
+ * Redact the whole tail before splitting it. A direct agent inherits the
171
+ * worker's environment, so it can print a multiline secret; splitting first
172
+ * meant no line held the whole value and `replaceAll` matched none of them.
173
+ */
174
+ function lastLines(text: string, count: number, env: NodeJS.ProcessEnv): string[] {
175
+ const lines = redact(text, env).split('\n');
176
+ if (lines.at(-1) === '') lines.pop();
177
+ return lines.slice(Math.max(0, lines.length - count));
178
+ }
179
+
180
+ /** The {@link TailSource} `flows status` uses: this step's latest attempt, redacted. */
181
+ export function transcriptTailSource(env: NodeJS.ProcessEnv = process.env): TailSource {
182
+ return {
183
+ async read(dataDir: string, runId: string, step: StepView, lines: number): Promise<StepTails> {
184
+ if (step.type !== 'agent' || step.attempt === 0) return null;
185
+ const identity = { dataDir, runId, stepId: step.id, attempt: step.attempt };
186
+ const tail = async (stream: TailStream): Promise<TranscriptTail | null> => {
187
+ const read = await readTranscriptTail(identity, stream, step.started_at_ms);
188
+ return read === undefined ? null : { attempt: step.attempt, bytes: read.bytes, lines: lastLines(read.text, lines, env) };
189
+ };
190
+ return { stdout: await tail('stdout'), stderr: await tail('stderr') };
191
+ },
192
+ };
193
+ }
package/src/worker-cli.ts CHANGED
@@ -1,7 +1,9 @@
1
+ import { realpathSync } from 'node:fs';
1
2
  import { resolve } from 'node:path';
2
3
  import { diffWorkspaceFiles, snapshotWorkspaceFiles } from './agent-artifacts.js';
3
4
  import { claudeResultOutcome, decodeProviderResult, decodeWrapperResult, requirePricedUsage } from './worker-usage.js';
4
5
  import { openSidechannel, type SidechannelContext } from './pty-sidechannel.js';
6
+ import { openTranscriptWriter, transcriptPath, type TranscriptDigest, type TranscriptFile, type TranscriptWriter } from './agent-transcript.js';
5
7
  import { spawn } from 'node:child_process';
6
8
  import { StringDecoder } from 'node:string_decoder';
7
9
  import { childStop } from './child-stop.js';
@@ -19,6 +21,9 @@ import {
19
21
  type WrapperSessionLimits,
20
22
  } from './wrapper-session.js';
21
23
  import { wrapperEnvironment } from './wrapper-runtime.js';
24
+ import { redactRelayError } from './redact.js';
25
+ import { applyStepEnvironment } from './step-env.js';
26
+ import { TAIL_CLOSE_TIMEOUT_MS, openTranscriptTail, transcriptTailPath, type TranscriptTailWriter } from './transcript-tail.js';
22
27
  import {
23
28
  runAgentRelayTask,
24
29
  AgentRelayTransportError,
@@ -52,6 +57,15 @@ export interface WorkerCliResult {
52
57
  * agent runs on another host.
53
58
  */
54
59
  artifacts?: string[];
60
+ /**
61
+ * The attempt's transcript digest (`agent-transcript.ts`): provider result
62
+ * metadata, tool calls summarized, final text, failure excerpt, and — when
63
+ * the spawn had a sidechannel context with an attempt — the pointer to the
64
+ * redacted, capped `stream-json` file. Journaled in `trajectory_tail`, never
65
+ * in `output`. Present for Claude/Codex executions; absent for wrappers and
66
+ * the relay transport, which stream no provider frames through this process.
67
+ */
68
+ transcript?: TranscriptDigest;
55
69
  }
56
70
 
57
71
  /**
@@ -95,23 +109,44 @@ export async function runAgentCli(
95
109
  // workspace to change. Executions sharing a working directory are
96
110
  // serialized around their snapshot-spawn-snapshot interval, so one agent's
97
111
  // writes are never attributed to a concurrent one in the same directory.
112
+ //
113
+ // This process writes its own evidence during that interval — the attempt's
114
+ // transcript file and the two `flows status --tail` tails — and when the data
115
+ // dir sits under the cwd (a local `--data-dir` inside the project) they all
116
+ // land inside the scanned tree. None of them is agent-authored content, so
117
+ // every one is dropped from the diff by path. Missing any of them reports
118
+ // our own bookkeeping back to the kernel as the step's artifacts.
98
119
  const artifactRoot = mode === 'agent' ? resolve(cwd ?? process.cwd()) : undefined;
99
120
  return artifactRoot === undefined
100
121
  ? execute()
101
122
  : serializedByDirectory(artifactRoot, async () => {
102
123
  const before = await snapshotWorkspaceFiles(artifactRoot);
103
124
  const result = await execute();
104
- return { ...result, artifacts: diffWorkspaceFiles(before, await snapshotWorkspaceFiles(artifactRoot)) };
125
+ const ours = new Set<string>();
126
+ for (const path of ownEvidencePaths(sidechannel)) {
127
+ const real = realPath(path);
128
+ if (real !== undefined) ours.add(real);
129
+ }
130
+ const artifacts = diffWorkspaceFiles(before, await snapshotWorkspaceFiles(artifactRoot))
131
+ .filter(path => {
132
+ const real = realPath(resolve(artifactRoot, path));
133
+ return real === undefined || !ours.has(real);
134
+ });
135
+ return { ...result, artifacts };
105
136
  });
106
137
 
107
138
  async function execute(): Promise<WorkerCliResult> {
108
139
  if (kind === 'relayflows-wrapper-v1') {
140
+ // The closed allowlist admits no ambient RELAYFLOW_* value; the four
141
+ // discovery names are set from this dispatch, exactly as for a direct spawn.
142
+ const wrapperEnv = wrapperEnvironment(process.env);
143
+ applyStepEnvironment(wrapperEnv, sidechannel);
109
144
  return requirePricedUsage(decodeWrapperResult(await runWrapperSession(
110
145
  cli,
111
146
  instruction,
112
147
  wakeContext,
113
148
  effectiveModel,
114
- wrapperEnvironment(process.env),
149
+ wrapperEnv,
115
150
  wrapperLimits,
116
151
  signal,
117
152
  cwd,
@@ -121,6 +156,9 @@ export async function runAgentCli(
121
156
  const env: NodeJS.ProcessEnv = { ...process.env };
122
157
  delete env[WAKE_CONTEXT_ENV];
123
158
  delete env[MODEL_ENV];
159
+ // Where this attempt's journal is, so the agent can run `flows status` on
160
+ // itself. Only a worker with a data dir knows; an ad-hoc spawn exports nothing.
161
+ applyStepEnvironment(env, sidechannel);
124
162
  const invocation = mode === 'llm' ? llmExecution(kind, instruction, effectiveModel) : agentExecution(kind, instruction, effectiveModel);
125
163
 
126
164
  if (wakeContext !== undefined) {
@@ -142,10 +180,65 @@ export async function runAgentCli(
142
180
  const args = [...invocation.args];
143
181
  args.splice(args.length - 1, 0, ...(kind === 'claude' ? ['--output-format', 'stream-json', '--verbose'] : ['--json']));
144
182
  const completion = kind === 'claude' ? claudeResultOutcome : undefined;
145
- return requirePricedUsage(decodeProviderResult(await spawnInvocation(cli, { ...invocation, args }, env, signal, sidechannel, cwd, completion), kind), effectiveModel);
183
+ return requirePricedUsage(decodeProviderResult(await spawnInvocation(cli, { ...invocation, args }, env, signal, sidechannel, cwd, completion), kind, env), effectiveModel);
184
+ }
185
+ }
186
+
187
+ function openTails(context: SidechannelContext): { stdout: TranscriptTailWriter; stderr: TranscriptTailWriter } | undefined {
188
+ // Same rule as the per-attempt transcript file: no attempt, no tails.
189
+ const attempt = context.attempt;
190
+ if (attempt === undefined) return undefined;
191
+ const identity = { dataDir: context.dataDir, runId: context.runId, stepId: context.stepId, attempt };
192
+ try {
193
+ return { stdout: openTranscriptTail(identity, 'stdout'), stderr: openTranscriptTail(identity, 'stderr') };
194
+ } catch {
195
+ // An id the path cannot carry; the sidechannel declined it the same way.
196
+ return undefined;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Every path this process may write under the workspace during an attempt, so
202
+ * the artifact diff can drop all of them.
203
+ *
204
+ * Derived from the attempt identity — the same input `openTranscriptWriter` and
205
+ * `openTails` use to decide where to write — and never from the result. The
206
+ * transcript pointer on the result is optional: `finish` drops it when the
207
+ * close outruns `TAIL_CLOSE_TIMEOUT_MS` and `discardTranscript` drops it on
208
+ * abort, and on both paths the file is already on disk. An exclusion built from
209
+ * that pointer therefore lost the transcript exactly when the close was slow,
210
+ * which is the moment the file is most likely to still be there.
211
+ *
212
+ * Empty when there is no sidechannel or no attempt to name, which is exactly
213
+ * when nothing is written.
214
+ */
215
+ function ownEvidencePaths(context: SidechannelContext | undefined): string[] {
216
+ const attempt = context?.attempt;
217
+ if (context === undefined || attempt === undefined) return [];
218
+ const identity = { dataDir: context.dataDir, runId: context.runId, stepId: context.stepId, attempt };
219
+ try {
220
+ // For each tail, both the finished file and the `.tmp` the writer stages
221
+ // and renames over (`transcript-tail.ts`): a close that timed out or a
222
+ // flush that failed can leave the staging file behind, and it is no more
223
+ // agent-authored than the file it was going to become.
224
+ const paths = [transcriptPath(identity, attempt)];
225
+ for (const stream of ['stdout', 'stderr'] as const) {
226
+ const tail = transcriptTailPath(identity, stream);
227
+ paths.push(tail, `${tail}.tmp`);
228
+ }
229
+ return paths;
230
+ } catch {
231
+ // An id the path cannot carry; nothing was written under it either.
232
+ return [];
146
233
  }
147
234
  }
148
235
 
236
+ /** Symlink-free form of a path, or the path itself when it cannot be resolved. */
237
+ function realPath(path: string | undefined): string | undefined {
238
+ if (path === undefined) return undefined;
239
+ try { return realpathSync(path); } catch { return path; }
240
+ }
241
+
149
242
  /** One agent at a time per canonical working directory, for the artifact interval. */
150
243
  const directoryQueues = new Map<string, Promise<unknown>>();
151
244
  function serializedByDirectory<T>(directory: string, task: () => Promise<T>): Promise<T> {
@@ -191,14 +284,6 @@ async function runViaAgentRelay(
191
284
  }
192
285
  }
193
286
 
194
- function redactRelayError(message: string): string {
195
- for (const key of ['RELAY_AGENT_TOKEN', 'RELAY_API_KEY']) {
196
- const secret = process.env[key];
197
- if (secret) message = message.replaceAll(secret, '[redacted]');
198
- }
199
- return message.replace(/\b(?:at|rk|nt|ot|br|arr)_(?:live_)?[A-Za-z0-9_-]+/g, '[redacted]');
200
- }
201
-
202
287
  /**
203
288
  * How long a CLI that has reported its final result may take to exit. Claude
204
289
  * Code in print mode waits, after its result, for every background task it
@@ -220,11 +305,27 @@ async function spawnInvocation(
220
305
  let writeInput: (bytes: Buffer) => Promise<boolean> = async () => false;
221
306
  let canDrive = () => false;
222
307
  let driven = false;
308
+ // The transcript file lives beside the PTY socket and is named by attempt.
309
+ // Its absence (no data dir, no attempt, unwritable dir) costs the step
310
+ // nothing: the digest is built from the buffered frames regardless. Opened
311
+ // BEFORE the sidechannel: once `onReady` has fired, a drive peer's HELLO may
312
+ // arrive at any time, and nothing may sit between that and the spawn that
313
+ // arms `canDrive`.
314
+ const writer: TranscriptWriter | undefined = sidechannel?.attempt === undefined ? undefined
315
+ : await openTranscriptWriter(transcriptPath(sidechannel, sidechannel.attempt), env);
223
316
  const channel = sidechannel === undefined ? undefined : await openSidechannel({
224
317
  ...sidechannel,
225
318
  onDrive() { driven = true; sidechannel.onDrive(); },
226
319
  }, bytes => writeInput(bytes), () => canDrive());
227
- if (signal?.aborted) { channel?.close(); signal.throwIfAborted(); }
320
+ // Tee the transcript into bounded tail files beside the socket. Evidence
321
+ // for `flows status --tail`, never the record; a failure here is a warning.
322
+ const tails = sidechannel === undefined ? undefined : openTails(sidechannel);
323
+ if (signal?.aborted) {
324
+ channel?.close();
325
+ void writer?.close();
326
+ void tails?.stdout.close(); void tails?.stderr.close();
327
+ signal.throwIfAborted();
328
+ }
228
329
  return new Promise((resolve) => {
229
330
  // Always a group of its own off Windows, so every stop — and
230
331
  // `reapOnExit` — reaches the whole agent tree, lease-bound or not.
@@ -257,7 +358,7 @@ async function spawnInvocation(
257
358
  let graceTimer: NodeJS.Timeout | undefined;
258
359
  const decoder = new StringDecoder('utf8');
259
360
  let partialLine = '';
260
- const finish = (result: WorkerCliResult): void => {
361
+ const finish = (result: WorkerCliResult, discardTranscript = false): void => {
261
362
  if (settled) return;
262
363
  settled = true;
263
364
  if (inputTimer !== undefined) clearTimeout(inputTimer);
@@ -265,11 +366,42 @@ async function spawnInvocation(
265
366
  if (timer !== undefined) clearTimeout(timer);
266
367
  if (graceTimer !== undefined) clearTimeout(graceTimer);
267
368
  signal?.removeEventListener('abort', onAbort);
268
- resolve(result);
369
+ if (writer === undefined && tails === undefined) { resolve(result); return; }
370
+ if (writer !== undefined) {
371
+ const rest = partialLine + decoder.end();
372
+ if (rest.length > 0) writer.write(rest);
373
+ }
374
+ // Two independent pieces of evidence close here: the per-attempt
375
+ // transcript, whose descriptor rides back on the result as the digest's
376
+ // file pointer, and the `flows status --tail` tails, which nothing reads
377
+ // from the result.
378
+ //
379
+ // Neither may hold a step open. A stalled write would leave
380
+ // `runAgentCli` unresolved forever, and every later abort or timeout is
381
+ // already a no-op once `settled` is true — so the whole close is raced
382
+ // against a bounded deadline and the result stands either way. Past the
383
+ // deadline the transcript pointer is dropped rather than waited for: a
384
+ // completion without a pointer is recoverable, a step that never
385
+ // completes is not.
386
+ // The writer's result is recorded the moment it lands, not read out of
387
+ // the combined race: the two closes are independent, and a stalled tail
388
+ // must not throw away a transcript that finished and is on disk.
389
+ let transcriptFile: TranscriptFile | undefined;
390
+ const closedWriter = writer === undefined
391
+ ? Promise.resolve()
392
+ : writer.close().then((file) => { transcriptFile = file; }, () => {});
393
+ const closedTails = tails === undefined
394
+ ? Promise.resolve()
395
+ : Promise.all([tails.stdout.close(), tails.stderr.close()]).then(() => undefined, () => undefined);
396
+ const deadline = new Promise<void>((done) => setTimeout(done, TAIL_CLOSE_TIMEOUT_MS).unref?.());
397
+ void Promise.race([Promise.all([closedWriter, closedTails]), deadline]).then(() => {
398
+ resolve(discardTranscript || transcriptFile === undefined
399
+ ? result : { ...result, transcript: { file: transcriptFile } });
400
+ }, () => resolve(result));
269
401
  };
270
402
  const onAbort = (): void => {
271
403
  stop.kill();
272
- finish({ exit_code: null, stdout_tail: '', stderr_tail: 'Agent execution aborted: lease ownership lost.' });
404
+ finish({ exit_code: null, stdout_tail: '', stderr_tail: 'Agent execution aborted: lease ownership lost.' }, true);
273
405
  };
274
406
  /**
275
407
  * Same invariant as `wrapper-session.ts`: `'close'` and `'error'` are
@@ -306,15 +438,23 @@ async function spawnInvocation(
306
438
  child.stdout.on('data', (chunk: Buffer) => {
307
439
  stdout.push(chunk);
308
440
  channel?.publish(chunk);
309
- if (completion === undefined || graceTimer !== undefined) return;
441
+ // The tails take raw bytes, so they are fed before any line splitting
442
+ // and regardless of what the writer or the detector still wants.
443
+ tails?.stdout.append(chunk);
444
+ // Lines are split whenever a writer or a completion detector wants
445
+ // them; the detector stops looking once a result has been seen, the
446
+ // writer keeps every line to the end.
447
+ if (writer === undefined && (completion === undefined || graceTimer !== undefined)) return;
310
448
  const lines = (partialLine + decoder.write(chunk)).split('\n');
311
449
  partialLine = lines.pop() ?? '';
312
450
  for (const line of lines) {
451
+ writer?.write(line);
452
+ if (completion === undefined || graceTimer !== undefined) continue;
313
453
  const outcome = completion(line);
314
454
  if (outcome !== undefined) onResult(outcome);
315
455
  }
316
456
  });
317
- child.stderr.on('data', (chunk: Buffer) => { stderr.push(chunk); channel?.publish(chunk); });
457
+ child.stderr.on('data', (chunk: Buffer) => { stderr.push(chunk); channel?.publish(chunk); tails?.stderr.append(chunk); });
318
458
  child.once('error', (error) => finishOnChildExit({
319
459
  exit_code: null,
320
460
  stdout_tail: Buffer.concat(stdout).toString('utf8'),
@@ -1,12 +1,21 @@
1
1
  import type { WorkerCliResult } from './worker-cli.js';
2
2
  import { MODEL_PRICING } from './model-pricing.js';
3
+ import { FAILURE_EXCERPT_MAX_BYTES, buildTranscriptDigest, redactText, utf8Tail } from './agent-transcript.js';
3
4
 
4
5
  type RecordValue = Record<string, unknown>;
5
6
  const record = (value: unknown): value is RecordValue => typeof value === 'object' && value !== null && !Array.isArray(value);
6
7
  const count = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
7
8
 
9
+ /**
10
+ * A completion this decoder refuses. The refusal is appended to stderr, and a
11
+ * digest already built from the frames gets it as its failure — otherwise the
12
+ * digest would still describe the attempt as the provider reported it.
13
+ */
8
14
  function invalid(result: WorkerCliResult, detail: string): WorkerCliResult {
9
- return { ...result, exit_code: null, stderr_tail: `${result.stderr_tail}\n${detail}`.trim() };
15
+ const stderr_tail = `${result.stderr_tail}\n${detail}`.trim();
16
+ const transcript = result.transcript === undefined ? undefined : { ...result.transcript,
17
+ failure: { kind: 'stderr' as const, excerpt: utf8Tail(redactText(stderr_tail), FAILURE_EXCERPT_MAX_BYTES) } };
18
+ return { ...result, exit_code: null, stderr_tail, ...(transcript === undefined ? {} : { transcript }) };
10
19
  }
11
20
 
12
21
  function usageResult(result: WorkerCliResult, usage: unknown, output: unknown): WorkerCliResult {
@@ -18,12 +27,26 @@ function usageResult(result: WorkerCliResult, usage: unknown, output: unknown):
18
27
  tokens_input: usage.input_tokens, tokens_output: usage.output_tokens };
19
28
  }
20
29
 
21
- /** Provider envelopes are execution metadata, never the authored output. */
22
- export function decodeProviderResult(result: WorkerCliResult, kind: 'claude' | 'codex'): WorkerCliResult {
30
+ /**
31
+ * Provider envelopes are execution metadata, never the authored output. The
32
+ * same frames also yield the transcript digest (`agent-transcript.ts`): the
33
+ * metered `tokens_input/output` stay the budget source, and the provider's own
34
+ * cost, model, tool calls and failure ride beside them in `transcript`.
35
+ */
36
+ export function decodeProviderResult(
37
+ result: WorkerCliResult,
38
+ kind: 'claude' | 'codex',
39
+ env: NodeJS.ProcessEnv = process.env,
40
+ ): WorkerCliResult {
23
41
  const frames: RecordValue[] = [];
24
42
  for (const line of result.stdout_tail.split('\n')) {
25
43
  try { const frame: unknown = JSON.parse(line); if (record(frame)) frames.push(frame); } catch { /* Plain text remains output. */ }
26
44
  }
45
+ const decoded = decodeUsage(result, frames, kind);
46
+ return { ...decoded, transcript: { ...result.transcript, ...buildTranscriptDigest(frames, kind, decoded, env) } };
47
+ }
48
+
49
+ function decodeUsage(result: WorkerCliResult, frames: RecordValue[], kind: 'claude' | 'codex'): WorkerCliResult {
27
50
  const terminal = [...frames].reverse().find(f => kind === 'claude' ? f.type === 'result' : f.type === 'turn.completed');
28
51
  if (terminal === undefined) return result;
29
52
  const text = kind === 'claude' ? terminal.result : frames
package/src/worker.ts CHANGED
@@ -10,6 +10,7 @@ import { withWorkerLease } from './worker-lease.js';
10
10
  import { workerInstruction } from './worker-input.js';
11
11
  import { helperCall } from './yaml-helpers.js';
12
12
  import { completeHelperDispatch } from './yaml-helper-effect.js';
13
+ import { ARTIFACT_PATHS_MAX, boundTranscriptDigest, type TranscriptDigest } from './agent-transcript.js';
13
14
 
14
15
  export { MODEL_ENV, WAKE_CONTEXT_ENV } from './worker-cli.js';
15
16
 
@@ -110,7 +111,7 @@ export class AgentWorker extends EventEmitter {
110
111
  const completed: WorkerCliResult = await withWorkerLease(this.client, dispatch, signal =>
111
112
  typeof spec.cli === 'string' && typeof spec.instruction === 'string'
112
113
  ? runAgentCli(spec.cli, workerInstruction(spec.instruction, dispatch), dispatch.wake_context, effectiveModel, undefined, signal, 'agent', this.options.dataDir === undefined ? undefined : {
113
- dataDir: this.options.dataDir, runId: dispatch.run_id, stepId: dispatch.step_id,
114
+ dataDir: this.options.dataDir, runId: dispatch.run_id, stepId: dispatch.step_id, attempt: dispatch.attempt,
114
115
  onReady: this.options.onPtyReady, onDrive: () => { humanIntervention = true; },
115
116
  }, typeof spec.cwd === 'string' ? spec.cwd : undefined,
116
117
  spec.transport === 'relay' ? 'relay' : 'direct',
@@ -142,8 +143,20 @@ export class AgentWorker extends EventEmitter {
142
143
  // or `summary` never asked for. An agent that answers with a JSON object
143
144
  // therefore journals no artifacts; gate such a step on a deterministic
144
145
  // check instead. The relay transport reports none (the agent ran elsewhere).
146
+ //
147
+ // `transcript` is not part of the wrapper either: it is evidence about the
148
+ // attempt, journaled in `trajectory_tail` below on success and failure
149
+ // alike, where the kernel already accepts and bounds it (16 KiB).
150
+ const { transcript, ...wrapper } = result;
145
151
  const output = result.relay_task?.status === 'completed' && result.exit_code === 0
146
- ? result.relay_task.output : parseJsonOutput(result.stdout_tail) ?? result;
152
+ ? result.relay_task.output : parseJsonOutput(result.stdout_tail) ?? wrapper;
153
+ const trajectoryTail = {
154
+ ...(result.relay_task === undefined ? {} : { relay_task: {
155
+ invocation_id: result.relay_task.invocation_id, status: result.relay_task.status,
156
+ task_execution: result.relay_task.task_execution, error: result.relay_task.error,
157
+ } }),
158
+ ...(transcript === undefined ? {} : { transcript: transcriptDigest(transcript, dispatch.attempt, result) }),
159
+ };
147
160
 
148
161
  await this.client.stepComplete(
149
162
  dispatch.run_id,
@@ -153,10 +166,7 @@ export class AgentWorker extends EventEmitter {
153
166
  completionReason,
154
167
  {
155
168
  output,
156
- ...(result.relay_task === undefined ? {} : { trajectory_tail: { relay_task: {
157
- invocation_id: result.relay_task.invocation_id, status: result.relay_task.status,
158
- task_execution: result.relay_task.task_execution, error: result.relay_task.error,
159
- } } }),
169
+ ...(Object.keys(trajectoryTail).length === 0 ? {} : { trajectory_tail: trajectoryTail }),
160
170
  ...(humanIntervention ? { human_intervention: true } : {}),
161
171
  ...(usage !== undefined ? { usage } : {}),
162
172
  started_pins: dispatch.pins,
@@ -166,6 +176,22 @@ export class AgentWorker extends EventEmitter {
166
176
  }
167
177
  }
168
178
 
179
+ /**
180
+ * The digest as journaled: the attempt and exit code (dropped from `output` on
181
+ * the JSON path by design) and the artifact paths folded in, then bounded to
182
+ * `TRANSCRIPT_DIGEST_MAX_BYTES` with every cut stated on the digest itself.
183
+ */
184
+ function transcriptDigest(transcript: TranscriptDigest, attempt: number, result: WorkerCliResult): TranscriptDigest {
185
+ return boundTranscriptDigest({
186
+ attempt,
187
+ exit_code: result.exit_code,
188
+ ...transcript,
189
+ ...(result.artifacts === undefined ? {} : { artifacts: {
190
+ count: result.artifacts.length, paths: result.artifacts.slice(0, ARTIFACT_PATHS_MAX),
191
+ } }),
192
+ });
193
+ }
194
+
169
195
  /**
170
196
  * Return an object-shaped JSON payload parsed from `stdout`, or
171
197
  * `null` when stdout is empty, non-JSON, or JSON-of-a-scalar/array.
@@ -25,7 +25,13 @@ export interface WrapperIdentity {
25
25
  fingerprint: string;
26
26
  }
27
27
 
28
- /** Build a wrapper environment from a closed list; ambient credentials never cross. */
28
+ /**
29
+ * Build a wrapper environment from a closed list; ambient credentials never
30
+ * cross. The step discovery names (`RELAYFLOW_DATA_DIR`, `RELAYFLOW_RUN_ID`,
31
+ * `RELAYFLOW_STEP_ID`, `RELAYFLOW_ATTEMPT`) are deliberately not on the list:
32
+ * an ambient value is a parent step's identity, not this one's, so the worker
33
+ * sets them from the dispatch after this filter (step-env.ts).
34
+ */
29
35
  export function wrapperEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
30
36
  const env: NodeJS.ProcessEnv = {};
31
37
  for (const name of WRAPPER_ENV_ALLOWLIST) {