@cat-factory/executor-harness 1.96.0 → 1.98.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/agent-runner.d.ts +14 -1
- package/dist/agent-runner.js +84 -28
- package/dist/bootstrap-mode.js +1 -0
- package/dist/coding-agent.d.ts +2 -1
- package/dist/embed.d.ts +2 -1
- package/dist/embed.js +2 -1
- package/dist/failure.d.ts +19 -1
- package/dist/failure.js +40 -0
- package/dist/git.d.ts +6 -0
- package/dist/git.js +16 -9
- package/dist/inline.d.ts +6 -0
- package/dist/inline.js +6 -0
- package/dist/job.d.ts +2 -1
- package/dist/jsonl-stream.d.ts +70 -0
- package/dist/jsonl-stream.js +149 -0
- package/dist/pi-reduction.d.ts +136 -0
- package/dist/pi-reduction.js +303 -0
- package/dist/pi-workspace.d.ts +2 -1
- package/dist/pi-workspace.js +6 -1
- package/dist/pi.d.ts +8 -81
- package/dist/pi.js +124 -310
- package/dist/runner.d.ts +31 -0
- package/dist/runner.js +50 -3
- package/dist/structured-output.js +2 -1
- package/dist/tool-silence.d.ts +74 -0
- package/dist/tool-silence.js +99 -0
- package/package.json +4 -4
- package/src/agent-runner.ts +100 -30
- package/src/agent.ts +1 -1
- package/src/bootstrap-mode.ts +2 -1
- package/src/coding-agent.ts +2 -1
- package/src/embed.ts +8 -5
- package/src/failure.ts +36 -9
- package/src/git.ts +17 -9
- package/src/inline.ts +6 -0
- package/src/job.ts +2 -1
- package/src/jsonl-stream.ts +149 -0
- package/src/pi-reduction.ts +359 -0
- package/src/pi-workspace.ts +7 -3
- package/src/pi.ts +144 -349
- package/src/runner.ts +91 -4
- package/src/structured-output.ts +2 -1
- package/src/tool-silence.ts +125 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// BOUNDED reading of an agent CLI's child streams: LF-framing its JSONL stdout, and holding a
|
|
2
|
+
// capped tail of raw output for diagnostics.
|
|
3
|
+
//
|
|
4
|
+
// WHY THIS MODULE EXISTS — the harness's two watchdog timers and its `/health` + `/jobs` poll
|
|
5
|
+
// endpoints share ONE Node event loop with the stream-parsing hot path, so the advertised "a
|
|
6
|
+
// container can never run forever" guarantee only holds while that loop stays live (stuck-run
|
|
7
|
+
// audit F6). Both CLI readers (`runPi`, `runSubscriptionAgent`) had grown the same unbounded
|
|
8
|
+
// framing loop: a record with no terminating newline accumulated without limit, so a runaway
|
|
9
|
+
// producer could drive the buffer until a single `JSON.parse` (or the allocation behind it)
|
|
10
|
+
// stalled the loop past the abort timers and the poll handlers alike. The container then stops
|
|
11
|
+
// answering polls while its own watchdogs never fire — the exact wedge the timers exist to
|
|
12
|
+
// prevent, with only the engine-side poll-failure tolerance and the reaper left underneath.
|
|
13
|
+
//
|
|
14
|
+
// One definition of "how much of a child's output we are willing to hold" therefore serves both
|
|
15
|
+
// harnesses, for the same reason `ProgressGuard` does: two copies of a bound are two bounds.
|
|
16
|
+
/**
|
|
17
|
+
* Longest single JSONL record either CLI may emit before the reader stops buffering it.
|
|
18
|
+
*
|
|
19
|
+
* Deliberately far above the largest LEGITIMATE record — the terminal `agent_end`, which carries
|
|
20
|
+
* the run's whole message transcript including tool results — because dropping that one costs the
|
|
21
|
+
* run its summary and stats. The cap is not a size policy, it is the ceiling that keeps a
|
|
22
|
+
* runaway producer from growing the buffer until parsing it wedges the event loop, so it only
|
|
23
|
+
* has to be low enough that one parse of it stays well inside the poll cadence.
|
|
24
|
+
*/
|
|
25
|
+
export const MAX_JSONL_LINE_CHARS = 32 * 1024 * 1024;
|
|
26
|
+
/**
|
|
27
|
+
* A fixed-size tail of a text stream, for output kept ONLY to quote back on a failure.
|
|
28
|
+
*
|
|
29
|
+
* Retaining a whole run's stdout to slice the last 2 KB off it at close is the memory half of
|
|
30
|
+
* F6: a chatty agent's output is unbounded, and the container OOMing is another way for a job to
|
|
31
|
+
* stop answering polls with no watchdog having fired. The tail is trimmed lazily — only once it
|
|
32
|
+
* has grown past twice the bound — so a run that streams thousands of chunks pays an amortized
|
|
33
|
+
* O(1) copy per chunk rather than an O(maxChars) slice on every one of them.
|
|
34
|
+
*/
|
|
35
|
+
export class BoundedTail {
|
|
36
|
+
maxChars;
|
|
37
|
+
text = '';
|
|
38
|
+
total = 0;
|
|
39
|
+
constructor(maxChars) {
|
|
40
|
+
this.maxChars = maxChars;
|
|
41
|
+
}
|
|
42
|
+
push(chunk) {
|
|
43
|
+
this.text += chunk;
|
|
44
|
+
this.total += chunk.length;
|
|
45
|
+
if (this.text.length > this.maxChars * 2)
|
|
46
|
+
this.text = this.text.slice(-this.maxChars);
|
|
47
|
+
}
|
|
48
|
+
/** The last `maxChars` characters seen. */
|
|
49
|
+
toString() {
|
|
50
|
+
return this.text.length > this.maxChars ? this.text.slice(-this.maxChars) : this.text;
|
|
51
|
+
}
|
|
52
|
+
/** Everything ever pushed, whether or not it is still retained. */
|
|
53
|
+
get totalChars() {
|
|
54
|
+
return this.total;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Characters dropped off the FRONT because the tail is bounded; 0 while everything still fits.
|
|
58
|
+
*
|
|
59
|
+
* A caller that renders the tail to a human owes them this: a bounded tail is the opposite of a
|
|
60
|
+
* prefix, so a reader who assumes one concludes the producer stopped where the text begins.
|
|
61
|
+
* Diagnostic quotes (a stderr tail) need no such note — being a tail is what they are for.
|
|
62
|
+
*/
|
|
63
|
+
get droppedChars() {
|
|
64
|
+
return this.total - this.toString().length;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Frames a child's LF-delimited JSONL stdout into complete records, bounding what it will buffer
|
|
69
|
+
* for any one of them.
|
|
70
|
+
*
|
|
71
|
+
* `onLine` is invoked per complete record with `final: false`, and once more from {@link flush}
|
|
72
|
+
* with `final: true` for a trailing record that arrived without its newline (a clean exit can
|
|
73
|
+
* leave the last event unterminated). `final` is what lets a caller deliver the record's
|
|
74
|
+
* progress/telemetry signal while suppressing any decision that would KILL the run: the process
|
|
75
|
+
* has already exited, so a guard tripping on that last buffered record would turn a clean exit
|
|
76
|
+
* into a spurious failure.
|
|
77
|
+
*
|
|
78
|
+
* A record that outgrows {@link MAX_JSONL_LINE_CHARS} is DROPPED, not truncated: a partial JSON
|
|
79
|
+
* document is not a record, and handing the parser half of one would report it as corrupt output
|
|
80
|
+
* rather than as the bound firing. The reader then resynchronises on the next newline, so the
|
|
81
|
+
* oversized record costs its own signal and nothing after it. Callers report {@link droppedLines}
|
|
82
|
+
* at close (never per line) so the loss is diagnosable instead of silent.
|
|
83
|
+
*/
|
|
84
|
+
export class JsonlLineReader {
|
|
85
|
+
onLine;
|
|
86
|
+
maxLineChars;
|
|
87
|
+
buffer = '';
|
|
88
|
+
/** True while discarding the tail of a record that already blew the cap. */
|
|
89
|
+
skipping = false;
|
|
90
|
+
dropped = 0;
|
|
91
|
+
constructor(onLine, maxLineChars = MAX_JSONL_LINE_CHARS) {
|
|
92
|
+
this.onLine = onLine;
|
|
93
|
+
this.maxLineChars = maxLineChars;
|
|
94
|
+
}
|
|
95
|
+
/** Feed one stdout chunk, emitting every complete record it finishes. */
|
|
96
|
+
push(text) {
|
|
97
|
+
// Framing scans the incoming CHUNK, never the accumulated buffer. `buffer += chunk` is a
|
|
98
|
+
// cheap rope in V8 and `.length` reads off it in constant time, but ANY search over it
|
|
99
|
+
// flattens the rope — so scanning the buffer once per chunk costs O(record) per chunk, i.e.
|
|
100
|
+
// quadratic in a runaway record, paid on the very event loop this class exists to keep
|
|
101
|
+
// answering polls. Measured, a 32 MB unterminated record cost ~6s of solid blocking that
|
|
102
|
+
// way: the cap bounded the memory and handed back the stall in its place.
|
|
103
|
+
let rest = text;
|
|
104
|
+
for (;;) {
|
|
105
|
+
const nl = rest.indexOf('\n');
|
|
106
|
+
if (nl === -1)
|
|
107
|
+
break;
|
|
108
|
+
if (this.skipping) {
|
|
109
|
+
// The newline that ends an oversized record ends the skip with it: everything buffered
|
|
110
|
+
// for that record is already gone, and what follows is a fresh one.
|
|
111
|
+
this.skipping = false;
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
// The only place the buffer is materialised, and only for a record that COMPLETED —
|
|
115
|
+
// which the branch below has already kept under the cap.
|
|
116
|
+
const raw = this.buffer + rest.slice(0, nl);
|
|
117
|
+
this.buffer = '';
|
|
118
|
+
// The cap is on the RECORD, not on the leftover buffer: a record that arrived whole
|
|
119
|
+
// inside one chunk was never buffered across pushes, and dropping it only when it
|
|
120
|
+
// straddles a chunk boundary would make the bound depend on how the OS split the reads.
|
|
121
|
+
if (raw.length > this.maxLineChars)
|
|
122
|
+
this.dropped++;
|
|
123
|
+
else
|
|
124
|
+
this.onLine(raw.trim(), false);
|
|
125
|
+
}
|
|
126
|
+
rest = rest.slice(nl + 1);
|
|
127
|
+
}
|
|
128
|
+
if (this.skipping)
|
|
129
|
+
return;
|
|
130
|
+
this.buffer += rest;
|
|
131
|
+
if (this.buffer.length > this.maxLineChars) {
|
|
132
|
+
this.buffer = '';
|
|
133
|
+
// Count the record once, however many chunks it goes on to spill.
|
|
134
|
+
this.dropped++;
|
|
135
|
+
this.skipping = true;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Emit any trailing unterminated record (see the class doc); call once, after the child exits. */
|
|
139
|
+
flush() {
|
|
140
|
+
const line = this.buffer.trim();
|
|
141
|
+
this.buffer = '';
|
|
142
|
+
if (line && !this.skipping)
|
|
143
|
+
this.onLine(line, true);
|
|
144
|
+
}
|
|
145
|
+
/** Records dropped for exceeding the line cap; 0 on every ordinary run. */
|
|
146
|
+
get droppedLines() {
|
|
147
|
+
return this.dropped;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-completion output-token ceiling Pi requests (its model-entry `maxTokens`).
|
|
3
|
+
* Generous on purpose: a reasoning model (e.g. GLM-5.2) spends tokens on its
|
|
4
|
+
* `<think>` trace before the answer + tool calls, so a tight cap truncates it
|
|
5
|
+
* mid-reasoning and the agent never commits edits. It is a ceiling, not a target
|
|
6
|
+
* — unused output tokens are not billed and Workers AI clamps the request to the
|
|
7
|
+
* model's real max — so erring high is safe. Raised to 32k after a spec-writer run
|
|
8
|
+
* truncated an intermediate tool call at the old 16k cap; the document itself
|
|
9
|
+
* stopped well under it, so this is headroom for larger specs/diffs, with
|
|
10
|
+
* {@link runDiagnostics} flagging the rare case where even 32k is not enough.
|
|
11
|
+
*/
|
|
12
|
+
export declare const PI_MAX_OUTPUT_TOKENS = 32768;
|
|
13
|
+
export declare function isObject(value: unknown): value is Record<string, unknown>;
|
|
14
|
+
/**
|
|
15
|
+
* What the agent actually did this run, independent of any file changes. Used to
|
|
16
|
+
* tell a genuine no-op (the agent never reached the model / never acted) apart
|
|
17
|
+
* from a real run, so a bootstrap that produced nothing is failed rather than
|
|
18
|
+
* pushed as an empty repo. `toolCalls === 0 && assistantChars === 0` is the
|
|
19
|
+
* signature of a run where Pi never made a successful model call.
|
|
20
|
+
*/
|
|
21
|
+
export interface PiRunStats {
|
|
22
|
+
/** Tool calls the assistant emitted across the transcript (0 ⇒ it never acted). */
|
|
23
|
+
toolCalls: number;
|
|
24
|
+
/** Total characters of assistant text (0 ⇒ the model produced nothing). */
|
|
25
|
+
assistantChars: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Output-quality signals lifted from the agent's transcript, so the harness can fail
|
|
29
|
+
* LOUDLY on a malformed run instead of silently handing a half-baked artifact to the
|
|
30
|
+
* structured-output repair (which would manufacture a doc from garbage — the trap
|
|
31
|
+
* behind the spec-writer ⇄ companion rework loop). Two distinct invalid states, both
|
|
32
|
+
* seen in production from `kimi-k2.7-code`:
|
|
33
|
+
* - a completion that hit the output ceiling (its answer/tool call was cut off), and
|
|
34
|
+
* - a FINAL turn that carried no text at all (an empty `content: []` despite spending
|
|
35
|
+
* output tokens), so there is no answer to parse.
|
|
36
|
+
*/
|
|
37
|
+
export interface RunDiagnostics {
|
|
38
|
+
/** Some completion ended at the output-token ceiling — its content was cut off. */
|
|
39
|
+
truncated: boolean;
|
|
40
|
+
/** The agent's FINAL completion hit the ceiling: its ANSWER (not a mid-run step) was cut off. */
|
|
41
|
+
finalTruncated: boolean;
|
|
42
|
+
/** The agent's final turn carried no text content (e.g. an empty `content: []`). */
|
|
43
|
+
finalAnswerEmpty: boolean;
|
|
44
|
+
}
|
|
45
|
+
/** What a Pi run's event stream reduces to (the run's product, before any process-level detail). */
|
|
46
|
+
export interface PiRunReduction {
|
|
47
|
+
summary: string;
|
|
48
|
+
stats: PiRunStats;
|
|
49
|
+
diagnostics: RunDiagnostics;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Folds a Pi event stream into {@link PiRunReduction} plus the run's terminal-failure signal.
|
|
53
|
+
*
|
|
54
|
+
* Feed every parsed record to {@link observe} in stream order, then read the answers at close.
|
|
55
|
+
* What it keeps, and why that is all of it:
|
|
56
|
+
* - the LAST `agent_end` / `auto_retry_end` record, which is exactly what a scan-from-the-end
|
|
57
|
+
* for the terminal signal would have stopped on;
|
|
58
|
+
* - the LAST `agent_end` transcript, the canonical source for the summary, the stats and the
|
|
59
|
+
* diagnostics alike (all three scanned back to the same record);
|
|
60
|
+
* - running counters and a bounded text tail, which are the FALLBACKS those three use when a
|
|
61
|
+
* run emitted no terminal transcript at all.
|
|
62
|
+
*/
|
|
63
|
+
export declare class PiRunReducer {
|
|
64
|
+
/** The last terminal record seen (`agent_end` or `auto_retry_end`), whichever came last. */
|
|
65
|
+
private terminal;
|
|
66
|
+
/** Messages of the last `agent_end` that carried a transcript. */
|
|
67
|
+
private transcript;
|
|
68
|
+
private streamedToolCalls;
|
|
69
|
+
private streamedToolResults;
|
|
70
|
+
private streamedAssistantChars;
|
|
71
|
+
private readonly streamedText;
|
|
72
|
+
/** Fold one parsed record. */
|
|
73
|
+
observe(event: Record<string, unknown>): void;
|
|
74
|
+
/**
|
|
75
|
+
* Whether the run emitted a terminal record at all. False means {@link terminalError} answered
|
|
76
|
+
* from nothing rather than from a clean ending, which a caller deciding whether the run
|
|
77
|
+
* SUCCEEDED has to tell apart (see `runPi`'s exit-0 path).
|
|
78
|
+
*/
|
|
79
|
+
get sawTerminalRecord(): boolean;
|
|
80
|
+
/**
|
|
81
|
+
* The terminal-failure message when the run ended in a hard error (the model was unreachable /
|
|
82
|
+
* refused, and Pi exhausted its auto-retries), else undefined. Only the FINAL outcome counts: a
|
|
83
|
+
* mid-run hiccup the agent recovered from leaves a clean terminal `agent_end`.
|
|
84
|
+
*/
|
|
85
|
+
terminalError(): string | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* The run's product. `stdoutTail` backs the last-resort summary for a run whose output matched
|
|
88
|
+
* nothing structured, and a TAIL is all that fallback ever wanted: it slices the final 2 KB.
|
|
89
|
+
*/
|
|
90
|
+
reduce(stdoutTail: string, cap?: number): PiRunReduction;
|
|
91
|
+
/**
|
|
92
|
+
* Preferred: the last assistant message of the terminal transcript. Falls back to the streamed
|
|
93
|
+
* assistant text, then to a raw tail, so a schema tweak never loses output.
|
|
94
|
+
*/
|
|
95
|
+
private summary;
|
|
96
|
+
/**
|
|
97
|
+
* Count what the agent actually did. Prefers the terminal transcript (assistant `toolCall`
|
|
98
|
+
* parts + text); falls back to the streamed `tool_execution_end` / `message_end` counters, so a
|
|
99
|
+
* no-op is never mistaken for a real run because of a schema tweak.
|
|
100
|
+
*/
|
|
101
|
+
private stats;
|
|
102
|
+
/**
|
|
103
|
+
* Output-quality signals over the terminal transcript: whether any completion hit the output
|
|
104
|
+
* ceiling (its content was cut off), whether the FINAL completion did, and whether that final
|
|
105
|
+
* turn carried no text at all. Defaults to all-false with no terminal transcript (a no-op run
|
|
106
|
+
* is already caught by `agentNeverActed`).
|
|
107
|
+
*
|
|
108
|
+
* `cap` is the per-completion ceiling Pi requested ({@link PI_MAX_OUTPUT_TOKENS}); truncation is
|
|
109
|
+
* detected by an assistant message whose `usage.output` reached it, which is reliable even when
|
|
110
|
+
* the model reports a non-`length` stop reason (Workers AI labelled a cut-off tool call
|
|
111
|
+
* `tool_calls`, not `length`).
|
|
112
|
+
*/
|
|
113
|
+
private diagnostics;
|
|
114
|
+
}
|
|
115
|
+
/** Parse Pi's LF-framed JSONL stdout into its event records, skipping noise. */
|
|
116
|
+
export declare function parsePiEvents(stdout: string): Record<string, unknown>[];
|
|
117
|
+
/** {@link PiRunReducer.terminalError} over Pi's raw `--mode json` stdout. */
|
|
118
|
+
export declare function terminalRunError(stdout: string): string | undefined;
|
|
119
|
+
/** {@link PiRunReducer.terminalError} over records already parsed from the stream. */
|
|
120
|
+
export declare function terminalErrorFromEvents(events: Record<string, unknown>[]): string | undefined;
|
|
121
|
+
/** {@link PiRunReducer.reduce} over Pi's raw `--mode json` stdout. */
|
|
122
|
+
export declare function summarizePiRun(stdout: string): PiRunReduction;
|
|
123
|
+
/** {@link PiRunReducer.reduce} over records already parsed from the stream. */
|
|
124
|
+
export declare function summarizeFromEvents(events: Record<string, unknown>[], stdoutTail: string): PiRunReduction;
|
|
125
|
+
/** {@link RunDiagnostics} over records already parsed from the stream. */
|
|
126
|
+
export declare function diagnosticsFromEvents(events: Record<string, unknown>[], cap?: number): RunDiagnostics;
|
|
127
|
+
/** {@link RunDiagnostics} over Pi's raw `--mode json` stdout. */
|
|
128
|
+
export declare function runDiagnostics(stdout: string, cap?: number): RunDiagnostics;
|
|
129
|
+
/**
|
|
130
|
+
* Extract the assistant's final summary from Pi's JSON-lines output. Pi emits a terminal
|
|
131
|
+
* `agent_end` event whose `messages` is the full transcript, so the last assistant message there
|
|
132
|
+
* is the canonical answer (see {@link PiRunReducer.reduce} for the fallbacks).
|
|
133
|
+
*/
|
|
134
|
+
export declare function parsePiOutput(stdout: string): string;
|
|
135
|
+
/** Join the text parts of a Pi message whose content is a string or parts array. */
|
|
136
|
+
export declare function messageText(message: unknown): string;
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { BoundedTail } from './jsonl-stream.js';
|
|
2
|
+
// Reducing a Pi `--mode json` event stream to what the run PRODUCED: the assistant's answer, what
|
|
3
|
+
// it actually did, its output-quality signals, and whether it ended in a hard error.
|
|
4
|
+
//
|
|
5
|
+
// WHY THIS IS ITS OWN MODULE — every one of these answers used to be computed by scanning a
|
|
6
|
+
// retained array of every record the run emitted, and `runPi` held that array for the whole run
|
|
7
|
+
// (stuck-run audit F6). Bounding the JSONL FRAMING while retaining an unbounded number of parsed
|
|
8
|
+
// records only moves the heap-exhaustion mode: a parsed object is typically larger than the raw
|
|
9
|
+
// text it replaced, and a container that OOMs is another way for a job to stop answering polls
|
|
10
|
+
// with no watchdog having fired.
|
|
11
|
+
//
|
|
12
|
+
// So the reduction FOLDS instead. {@link PiRunReducer} observes each record as it streams and
|
|
13
|
+
// retains only what the close-of-run answers actually need: the terminal record, the one
|
|
14
|
+
// transcript they read, running counters, and a bounded tail of streamed assistant text. Its
|
|
15
|
+
// memory is O(largest single record), not O(records).
|
|
16
|
+
//
|
|
17
|
+
// The array-shaped entry points below (used by offline tooling over a captured stdout) are
|
|
18
|
+
// DEFINED in terms of the same reducer rather than keeping their own scans, so the live path and
|
|
19
|
+
// the offline one cannot drift into disagreeing about what a run produced.
|
|
20
|
+
/**
|
|
21
|
+
* Per-completion output-token ceiling Pi requests (its model-entry `maxTokens`).
|
|
22
|
+
* Generous on purpose: a reasoning model (e.g. GLM-5.2) spends tokens on its
|
|
23
|
+
* `<think>` trace before the answer + tool calls, so a tight cap truncates it
|
|
24
|
+
* mid-reasoning and the agent never commits edits. It is a ceiling, not a target
|
|
25
|
+
* — unused output tokens are not billed and Workers AI clamps the request to the
|
|
26
|
+
* model's real max — so erring high is safe. Raised to 32k after a spec-writer run
|
|
27
|
+
* truncated an intermediate tool call at the old 16k cap; the document itself
|
|
28
|
+
* stopped well under it, so this is headroom for larger specs/diffs, with
|
|
29
|
+
* {@link runDiagnostics} flagging the rare case where even 32k is not enough.
|
|
30
|
+
*/
|
|
31
|
+
export const PI_MAX_OUTPUT_TOKENS = 32_768;
|
|
32
|
+
/**
|
|
33
|
+
* How much streamed assistant text the fallback summary holds when a run emitted no terminal
|
|
34
|
+
* transcript. Far above any real answer, because this is a bound on a runaway producer rather
|
|
35
|
+
* than a size policy — and what it drops is REPORTED (see {@link PiRunReducer.reduce}), since a
|
|
36
|
+
* tail read as a whole answer would look like a model that stopped mid-sentence.
|
|
37
|
+
*/
|
|
38
|
+
const FALLBACK_SUMMARY_CHARS = 256 * 1024;
|
|
39
|
+
export function isObject(value) {
|
|
40
|
+
return typeof value === 'object' && value !== null;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Folds a Pi event stream into {@link PiRunReduction} plus the run's terminal-failure signal.
|
|
44
|
+
*
|
|
45
|
+
* Feed every parsed record to {@link observe} in stream order, then read the answers at close.
|
|
46
|
+
* What it keeps, and why that is all of it:
|
|
47
|
+
* - the LAST `agent_end` / `auto_retry_end` record, which is exactly what a scan-from-the-end
|
|
48
|
+
* for the terminal signal would have stopped on;
|
|
49
|
+
* - the LAST `agent_end` transcript, the canonical source for the summary, the stats and the
|
|
50
|
+
* diagnostics alike (all three scanned back to the same record);
|
|
51
|
+
* - running counters and a bounded text tail, which are the FALLBACKS those three use when a
|
|
52
|
+
* run emitted no terminal transcript at all.
|
|
53
|
+
*/
|
|
54
|
+
export class PiRunReducer {
|
|
55
|
+
/** The last terminal record seen (`agent_end` or `auto_retry_end`), whichever came last. */
|
|
56
|
+
terminal;
|
|
57
|
+
/** Messages of the last `agent_end` that carried a transcript. */
|
|
58
|
+
transcript;
|
|
59
|
+
streamedToolCalls = 0;
|
|
60
|
+
streamedToolResults = 0;
|
|
61
|
+
streamedAssistantChars = 0;
|
|
62
|
+
streamedText = new BoundedTail(FALLBACK_SUMMARY_CHARS);
|
|
63
|
+
/** Fold one parsed record. */
|
|
64
|
+
observe(event) {
|
|
65
|
+
const type = event.type;
|
|
66
|
+
if (type === 'agent_end' || type === 'auto_retry_end') {
|
|
67
|
+
this.terminal = event;
|
|
68
|
+
if (type === 'agent_end' && Array.isArray(event.messages)) {
|
|
69
|
+
this.transcript = event.messages;
|
|
70
|
+
}
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (type === 'tool_execution_end') {
|
|
74
|
+
this.streamedToolCalls++;
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (type === 'message_end' && isObject(event.message)) {
|
|
78
|
+
const message = event.message;
|
|
79
|
+
if (message.role === 'assistant') {
|
|
80
|
+
const text = messageText(message);
|
|
81
|
+
this.streamedAssistantChars += text.length;
|
|
82
|
+
if (text)
|
|
83
|
+
this.streamedText.push(this.streamedText.totalChars ? `\n${text}` : text);
|
|
84
|
+
}
|
|
85
|
+
else if (message.role === 'toolResult') {
|
|
86
|
+
this.streamedToolResults++;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Whether the run emitted a terminal record at all. False means {@link terminalError} answered
|
|
92
|
+
* from nothing rather than from a clean ending, which a caller deciding whether the run
|
|
93
|
+
* SUCCEEDED has to tell apart (see `runPi`'s exit-0 path).
|
|
94
|
+
*/
|
|
95
|
+
get sawTerminalRecord() {
|
|
96
|
+
return this.terminal !== undefined;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The terminal-failure message when the run ended in a hard error (the model was unreachable /
|
|
100
|
+
* refused, and Pi exhausted its auto-retries), else undefined. Only the FINAL outcome counts: a
|
|
101
|
+
* mid-run hiccup the agent recovered from leaves a clean terminal `agent_end`.
|
|
102
|
+
*/
|
|
103
|
+
terminalError() {
|
|
104
|
+
const e = this.terminal;
|
|
105
|
+
if (!e)
|
|
106
|
+
return undefined;
|
|
107
|
+
if (e.type === 'auto_retry_end') {
|
|
108
|
+
if (e.success === false) {
|
|
109
|
+
return typeof e.finalError === 'string'
|
|
110
|
+
? e.finalError
|
|
111
|
+
: 'the agent failed after exhausting its retries';
|
|
112
|
+
}
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
return e.stopReason === 'error' && typeof e.errorMessage === 'string'
|
|
116
|
+
? e.errorMessage
|
|
117
|
+
: undefined;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The run's product. `stdoutTail` backs the last-resort summary for a run whose output matched
|
|
121
|
+
* nothing structured, and a TAIL is all that fallback ever wanted: it slices the final 2 KB.
|
|
122
|
+
*/
|
|
123
|
+
reduce(stdoutTail, cap = PI_MAX_OUTPUT_TOKENS) {
|
|
124
|
+
return {
|
|
125
|
+
summary: this.summary(stdoutTail),
|
|
126
|
+
stats: this.stats(),
|
|
127
|
+
diagnostics: this.diagnostics(cap),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Preferred: the last assistant message of the terminal transcript. Falls back to the streamed
|
|
132
|
+
* assistant text, then to a raw tail, so a schema tweak never loses output.
|
|
133
|
+
*/
|
|
134
|
+
summary(stdoutTail) {
|
|
135
|
+
if (this.transcript) {
|
|
136
|
+
const text = lastAssistantText(this.transcript);
|
|
137
|
+
if (text)
|
|
138
|
+
return text;
|
|
139
|
+
}
|
|
140
|
+
const streamed = this.streamedText.toString().trim();
|
|
141
|
+
if (streamed) {
|
|
142
|
+
const dropped = this.streamedText.droppedChars;
|
|
143
|
+
// Say so when this is a tail rather than the whole answer: a reader who took it for a
|
|
144
|
+
// prefix would conclude the model stopped where the text begins.
|
|
145
|
+
return dropped > 0
|
|
146
|
+
? `[earlier assistant output omitted: ${dropped} characters]\n${streamed}`
|
|
147
|
+
: streamed;
|
|
148
|
+
}
|
|
149
|
+
return stdoutTail.trim().slice(-2000);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Count what the agent actually did. Prefers the terminal transcript (assistant `toolCall`
|
|
153
|
+
* parts + text); falls back to the streamed `tool_execution_end` / `message_end` counters, so a
|
|
154
|
+
* no-op is never mistaken for a real run because of a schema tweak.
|
|
155
|
+
*/
|
|
156
|
+
stats() {
|
|
157
|
+
if (this.transcript)
|
|
158
|
+
return statsFromMessages(this.transcript);
|
|
159
|
+
return {
|
|
160
|
+
// The same call can surface as both a `tool_execution_end` and a toolResult `message_end`;
|
|
161
|
+
// prefer the former and only fall back to toolResult counts.
|
|
162
|
+
toolCalls: this.streamedToolCalls || this.streamedToolResults,
|
|
163
|
+
assistantChars: this.streamedAssistantChars,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Output-quality signals over the terminal transcript: whether any completion hit the output
|
|
168
|
+
* ceiling (its content was cut off), whether the FINAL completion did, and whether that final
|
|
169
|
+
* turn carried no text at all. Defaults to all-false with no terminal transcript (a no-op run
|
|
170
|
+
* is already caught by `agentNeverActed`).
|
|
171
|
+
*
|
|
172
|
+
* `cap` is the per-completion ceiling Pi requested ({@link PI_MAX_OUTPUT_TOKENS}); truncation is
|
|
173
|
+
* detected by an assistant message whose `usage.output` reached it, which is reliable even when
|
|
174
|
+
* the model reports a non-`length` stop reason (Workers AI labelled a cut-off tool call
|
|
175
|
+
* `tool_calls`, not `length`).
|
|
176
|
+
*/
|
|
177
|
+
diagnostics(cap) {
|
|
178
|
+
if (!this.transcript) {
|
|
179
|
+
return { truncated: false, finalTruncated: false, finalAnswerEmpty: false };
|
|
180
|
+
}
|
|
181
|
+
const assistants = this.transcript.filter((m) => isObject(m) && m.role === 'assistant');
|
|
182
|
+
const last = assistants.at(-1);
|
|
183
|
+
return {
|
|
184
|
+
truncated: assistants.some((m) => assistantOutputTokens(m) >= cap),
|
|
185
|
+
finalTruncated: last ? assistantOutputTokens(last) >= cap : false,
|
|
186
|
+
finalAnswerEmpty: last ? messageText(last) === '' : false,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** Fold an already-parsed event array through a fresh {@link PiRunReducer}. */
|
|
191
|
+
function reducerOver(events) {
|
|
192
|
+
const reducer = new PiRunReducer();
|
|
193
|
+
for (const event of events)
|
|
194
|
+
reducer.observe(event);
|
|
195
|
+
return reducer;
|
|
196
|
+
}
|
|
197
|
+
/** Parse Pi's LF-framed JSONL stdout into its event records, skipping noise. */
|
|
198
|
+
export function parsePiEvents(stdout) {
|
|
199
|
+
const events = [];
|
|
200
|
+
for (const line of stdout.split('\n')) {
|
|
201
|
+
const trimmed = line.trim();
|
|
202
|
+
if (!trimmed.startsWith('{'))
|
|
203
|
+
continue;
|
|
204
|
+
try {
|
|
205
|
+
events.push(JSON.parse(trimmed));
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
// Skip a corrupted/truncated record; the surrounding stream is still usable.
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return events;
|
|
212
|
+
}
|
|
213
|
+
/** {@link PiRunReducer.terminalError} over Pi's raw `--mode json` stdout. */
|
|
214
|
+
export function terminalRunError(stdout) {
|
|
215
|
+
return terminalErrorFromEvents(parsePiEvents(stdout));
|
|
216
|
+
}
|
|
217
|
+
/** {@link PiRunReducer.terminalError} over records already parsed from the stream. */
|
|
218
|
+
export function terminalErrorFromEvents(events) {
|
|
219
|
+
return reducerOver(events).terminalError();
|
|
220
|
+
}
|
|
221
|
+
/** {@link PiRunReducer.reduce} over Pi's raw `--mode json` stdout. */
|
|
222
|
+
export function summarizePiRun(stdout) {
|
|
223
|
+
return summarizeFromEvents(parsePiEvents(stdout), stdout);
|
|
224
|
+
}
|
|
225
|
+
/** {@link PiRunReducer.reduce} over records already parsed from the stream. */
|
|
226
|
+
export function summarizeFromEvents(events, stdoutTail) {
|
|
227
|
+
return reducerOver(events).reduce(stdoutTail);
|
|
228
|
+
}
|
|
229
|
+
/** {@link RunDiagnostics} over records already parsed from the stream. */
|
|
230
|
+
export function diagnosticsFromEvents(events, cap = PI_MAX_OUTPUT_TOKENS) {
|
|
231
|
+
return reducerOver(events).reduce('', cap).diagnostics;
|
|
232
|
+
}
|
|
233
|
+
/** {@link RunDiagnostics} over Pi's raw `--mode json` stdout. */
|
|
234
|
+
export function runDiagnostics(stdout, cap = PI_MAX_OUTPUT_TOKENS) {
|
|
235
|
+
return diagnosticsFromEvents(parsePiEvents(stdout), cap);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Extract the assistant's final summary from Pi's JSON-lines output. Pi emits a terminal
|
|
239
|
+
* `agent_end` event whose `messages` is the full transcript, so the last assistant message there
|
|
240
|
+
* is the canonical answer (see {@link PiRunReducer.reduce} for the fallbacks).
|
|
241
|
+
*/
|
|
242
|
+
export function parsePiOutput(stdout) {
|
|
243
|
+
return summarizePiRun(stdout).summary;
|
|
244
|
+
}
|
|
245
|
+
/** `usage.output` (completion tokens) reported on a Pi assistant message, or 0. */
|
|
246
|
+
function assistantOutputTokens(message) {
|
|
247
|
+
const usage = message.usage;
|
|
248
|
+
if (!isObject(usage))
|
|
249
|
+
return 0;
|
|
250
|
+
const output = usage.output;
|
|
251
|
+
return typeof output === 'number' ? output : 0;
|
|
252
|
+
}
|
|
253
|
+
/** {@link PiRunStats} from a transcript: assistant `toolCall` parts + text length. */
|
|
254
|
+
function statsFromMessages(messages) {
|
|
255
|
+
let toolCalls = 0;
|
|
256
|
+
let assistantChars = 0;
|
|
257
|
+
for (const m of messages) {
|
|
258
|
+
if (!isObject(m) || m.role !== 'assistant')
|
|
259
|
+
continue;
|
|
260
|
+
const content = m.content;
|
|
261
|
+
if (typeof content === 'string') {
|
|
262
|
+
assistantChars += content.trim().length;
|
|
263
|
+
}
|
|
264
|
+
else if (Array.isArray(content)) {
|
|
265
|
+
for (const part of content) {
|
|
266
|
+
if (!isObject(part))
|
|
267
|
+
continue;
|
|
268
|
+
if (part.type === 'toolCall')
|
|
269
|
+
toolCalls++;
|
|
270
|
+
else if (typeof part.text === 'string')
|
|
271
|
+
assistantChars += part.text.length;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return { toolCalls, assistantChars };
|
|
276
|
+
}
|
|
277
|
+
/** The text of the last assistant message in a transcript, or '' if none. */
|
|
278
|
+
function lastAssistantText(messages) {
|
|
279
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
280
|
+
const m = messages[i];
|
|
281
|
+
if (isObject(m) && m.role === 'assistant') {
|
|
282
|
+
const text = messageText(m);
|
|
283
|
+
if (text)
|
|
284
|
+
return text;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return '';
|
|
288
|
+
}
|
|
289
|
+
/** Join the text parts of a Pi message whose content is a string or parts array. */
|
|
290
|
+
export function messageText(message) {
|
|
291
|
+
if (!isObject(message))
|
|
292
|
+
return '';
|
|
293
|
+
const content = message.content;
|
|
294
|
+
if (typeof content === 'string')
|
|
295
|
+
return content.trim();
|
|
296
|
+
if (Array.isArray(content)) {
|
|
297
|
+
return content
|
|
298
|
+
.map((part) => (isObject(part) && typeof part.text === 'string' ? part.text : ''))
|
|
299
|
+
.join('')
|
|
300
|
+
.trim();
|
|
301
|
+
}
|
|
302
|
+
return '';
|
|
303
|
+
}
|
package/dist/pi-workspace.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { RepoSpec } from './job.js';
|
|
2
2
|
import type { McpServerSpec, SkillSpec } from './agent-capabilities.js';
|
|
3
|
-
import { type ContextFileInfo, type PiRunOutcome
|
|
3
|
+
import { type ContextFileInfo, type PiRunOutcome } from './pi.js';
|
|
4
|
+
import type { PiRunStats, RunDiagnostics } from './pi-reduction.js';
|
|
4
5
|
import { type ProgressGuardLimits } from './progress-guard.js';
|
|
5
6
|
import type { RunOptions } from './runner.js';
|
|
6
7
|
import { type SubscriptionHarness } from './agent-runner.js';
|
package/dist/pi-workspace.js
CHANGED
|
@@ -185,6 +185,10 @@ export async function runAgentInWorkspace(spec, opts = {}) {
|
|
|
185
185
|
// The run's tool-call trajectory, the same hook the Pi path feeds — so a subscription run
|
|
186
186
|
// and a proxied one produce the same evidence rather than one of them producing none.
|
|
187
187
|
onSpan: opts.onSpan,
|
|
188
|
+
// The tool-silence window (stuck-run audit F13), opened by whichever CLI actually runs.
|
|
189
|
+
// Wired for BOTH subscription harnesses: each reports tool activity on its own stream, so
|
|
190
|
+
// each can beat the window it opens.
|
|
191
|
+
beginToolWindow: opts.beginToolWindow,
|
|
188
192
|
// Per-slice review capture, so a parallel review's finished slices are persisted as they
|
|
189
193
|
// land rather than only in the terminal output. Only the subscription runners fan work out
|
|
190
194
|
// across subagents, so this is the only path that can produce it.
|
|
@@ -242,7 +246,7 @@ export async function runAgentInWorkspace(spec, opts = {}) {
|
|
|
242
246
|
model: spec.model,
|
|
243
247
|
proxyBaseUrl: phasedProxyBaseUrl(proxyBaseUrl, opts.currentPhase?.(), spec.proxyPhasePath),
|
|
244
248
|
});
|
|
245
|
-
const { signal, onActivity, onProgress, onSpan } = opts;
|
|
249
|
+
const { signal, onActivity, onProgress, onSpan, beginToolWindow } = opts;
|
|
246
250
|
const piOutcome = await runPi({
|
|
247
251
|
cwd: spec.dir,
|
|
248
252
|
model: spec.model,
|
|
@@ -252,6 +256,7 @@ export async function runAgentInWorkspace(spec, opts = {}) {
|
|
|
252
256
|
onActivity,
|
|
253
257
|
onProgress,
|
|
254
258
|
onSpan,
|
|
259
|
+
beginToolWindow,
|
|
255
260
|
expectsEdits: spec.expectsEdits ?? true,
|
|
256
261
|
// Start from the env/built-in defaults and apply only the per-knob overrides the
|
|
257
262
|
// backend set for this kind (loosen-only), so an unspecified knob keeps its default.
|