pi-crew 0.9.41 → 0.9.44
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/CHANGELOG.md +253 -0
- package/README.md +14 -0
- package/dist/build-meta.json +6450 -12419
- package/dist/index.mjs +57998 -68417
- package/dist/index.mjs.map +4 -4
- package/docs/migration/atomic-write-v2-migration.md +2 -0
- package/docs/superpowers/plans/2026-06-09-fallow-patterns-adoption.md +2 -0
- package/package.json +4 -2
- package/scripts/README.md +6 -0
- package/scripts/build-bundle.mjs +2 -1
- package/scripts/check-all-skills.ts +3 -3
- package/scripts/dev-runner.mjs +106 -0
- package/scripts/postinstall.mjs +6 -2
- package/scripts/verify-skill.ts +2 -2
- package/src/agents/agent-config.ts +1 -1
- package/src/config/config.ts +20 -1
- package/src/config/drift-detector.ts +97 -15
- package/src/config/resilient-parser.ts +4 -4
- package/src/config/types.ts +0 -2
- package/src/extension/crew-cleanup.ts +17 -3
- package/src/extension/crew-vibes/config.ts +1 -1
- package/src/extension/crew-vibes/font-detect.ts +16 -3
- package/src/extension/crew-vibes/index.ts +1 -1
- package/src/extension/cross-extension-rpc.ts +26 -9
- package/src/extension/management.ts +6 -5
- package/src/extension/register.ts +58 -1573
- package/src/extension/registration/command-registration.ts +57 -0
- package/src/extension/registration/commands.ts +7 -2
- package/src/extension/registration/context-builder.ts +131 -0
- package/src/extension/registration/crash-recovery-cache.ts +54 -0
- package/src/extension/registration/foreground-run-controller.ts +238 -0
- package/src/extension/registration/hook-registration.ts +119 -0
- package/src/extension/registration/lazy-configurers.ts +124 -0
- package/src/extension/registration/lifecycle-handlers.ts +731 -0
- package/src/extension/registration/observability.ts +33 -4
- package/src/extension/registration/registration-types.ts +149 -0
- package/src/extension/registration/runtime-cleanup.ts +230 -0
- package/src/extension/registration/subagent-manager-setup.ts +211 -0
- package/src/extension/registration/tool-registration.ts +50 -0
- package/src/extension/registration/wire-cross-extension.ts +37 -0
- package/src/extension/rpc-hmac.ts +21 -1
- package/src/extension/run-import.ts +3 -3
- package/src/extension/team-tool/auto-summarize.ts +4 -4
- package/src/extension/team-tool/cancel.ts +5 -5
- package/src/extension/team-tool/chain-executor.ts +5 -4
- package/src/extension/team-tool/context.ts +11 -1
- package/src/extension/team-tool/doctor.ts +2 -1
- package/src/extension/team-tool/goal-wrap.ts +2 -2
- package/src/extension/team-tool/goal.ts +1 -1
- package/src/extension/team-tool/handle-schedule.ts +25 -36
- package/src/extension/team-tool/orchestrate.ts +0 -1
- package/src/extension/team-tool/parallel-dispatch.ts +5 -0
- package/src/extension/team-tool/run.ts +220 -214
- package/src/extension/team-tool/workflow-manage.ts +1 -1
- package/src/extension/team-tool.ts +69 -16
- package/src/hooks/registry.ts +7 -2
- package/src/observability/correlation.ts +4 -3
- package/src/observability/event-bus.ts +10 -1
- package/src/observability/event-to-metric.ts +8 -7
- package/src/observability/exporters/adapter.ts +6 -9
- package/src/observability/exporters/otlp-exporter.ts +81 -0
- package/src/observability/metric-retention.ts +4 -0
- package/src/observability/metric-sink.ts +14 -4
- package/src/prompt/prompt-runtime.ts +15 -0
- package/src/runtime/adaptive-plan.ts +1 -1
- package/src/runtime/async-runner.ts +13 -4
- package/src/runtime/background-runner.ts +32 -23
- package/src/runtime/capability-inventory.ts +1 -1
- package/src/runtime/chain-runner.ts +5 -5
- package/src/runtime/checkpoint.ts +6 -16
- package/src/runtime/child-pi-constants.ts +42 -0
- package/src/runtime/child-pi-kill.ts +180 -0
- package/src/runtime/child-pi-spawn.ts +234 -0
- package/src/runtime/child-pi-steering.ts +128 -0
- package/src/runtime/child-pi-streams.ts +296 -0
- package/src/runtime/child-pi-transcript.ts +169 -0
- package/src/runtime/child-pi.ts +80 -822
- package/src/runtime/coalesce-tasks.ts +1 -1
- package/src/runtime/compact-stages/tail-capture-stage.ts +1 -1
- package/src/runtime/crash-recovery.ts +63 -47
- package/src/runtime/delivery-coordinator.ts +1 -1
- package/src/runtime/deterministic-ast.ts +2 -2
- package/src/runtime/diagnostic-export.ts +2 -1
- package/src/runtime/dwf-state-store.ts +5 -0
- package/src/runtime/dynamic-workflow-context.ts +78 -18
- package/src/runtime/dynamic-workflow-runner.ts +18 -2
- package/src/runtime/foreground-control.ts +3 -2
- package/src/runtime/goal-evaluator.ts +59 -27
- package/src/runtime/goal-loop-runner.ts +46 -13
- package/src/runtime/goal-state-store.ts +1 -1
- package/src/runtime/handoff-manager.ts +0 -2
- package/src/runtime/intercom-bridge.ts +0 -2
- package/src/runtime/live-agent-manager.ts +30 -5
- package/src/runtime/live-extension-bridge.ts +0 -2
- package/src/runtime/live-session-runtime.ts +65 -57
- package/src/runtime/manifest-cache.ts +59 -0
- package/src/runtime/mcp-proxy.ts +1 -1
- package/src/runtime/orphan-worker-registry.ts +3 -3
- package/src/runtime/output-validator.ts +1 -1
- package/src/runtime/path-overlap.ts +1 -1
- package/src/runtime/pi-args.ts +3 -3
- package/src/runtime/pi-json-output.ts +4 -3
- package/src/runtime/pi-spawn.ts +7 -1
- package/src/runtime/pipeline-runner.ts +1 -4
- package/src/runtime/post-checks.ts +0 -1
- package/src/runtime/retry-runner.ts +1 -1
- package/src/runtime/run-coalesced-task-group.ts +18 -23
- package/src/runtime/scheduler.ts +2 -0
- package/src/runtime/session-resources.ts +1 -1
- package/src/runtime/settings-store.ts +31 -1
- package/src/runtime/skill-effectiveness.ts +2 -2
- package/src/runtime/stale-reconciler.ts +23 -53
- package/src/runtime/subagent-manager.ts +19 -3
- package/src/runtime/task-output-context.ts +2 -1
- package/src/runtime/task-runner/prompt-builder.ts +3 -3
- package/src/runtime/task-runner/run-projection.ts +3 -1
- package/src/runtime/task-runner/state-helpers.ts +13 -1
- package/src/runtime/task-runner.ts +31 -6
- package/src/runtime/team-runner.ts +8 -2
- package/src/runtime/verification-gates.ts +54 -5
- package/src/schema/config-schema.ts +19 -1
- package/src/schema/team-tool-schema.ts +2 -0
- package/src/skills/discover-skills.ts +25 -15
- package/src/state/active-run-registry.ts +0 -1
- package/src/state/atomic-write.ts +37 -11
- package/src/state/blob-store.ts +3 -9
- package/src/state/contracts.ts +5 -1
- package/src/state/crew-init.ts +3 -2
- package/src/state/decision-ledger.ts +2 -2
- package/src/state/event-log-rotation.ts +1 -1
- package/src/state/event-log.ts +4 -3
- package/src/state/gitignore-manager.ts +2 -1
- package/src/state/health-store.ts +5 -2
- package/src/state/instinct-store.ts +11 -2
- package/src/state/locks.ts +132 -49
- package/src/state/mailbox.ts +3 -4
- package/src/state/observation-store.ts +1 -13
- package/src/state/run-cache.ts +12 -12
- package/src/state/run-graph.ts +2 -1
- package/src/state/run-metrics.ts +1 -1
- package/src/state/schedule.ts +7 -1
- package/src/state/state-store.ts +9 -3
- package/src/state/tiered-eval.ts +1 -1
- package/src/state/worker-atomic-writer.ts +1 -0
- package/src/ui/dynamic-border.ts +13 -3
- package/src/ui/live-conversation-overlay.ts +7 -27
- package/src/ui/live-duration.ts +2 -2
- package/src/ui/live-run-sidebar.ts +56 -32
- package/src/ui/mascot.ts +19 -13
- package/src/ui/powerbar-publisher.ts +244 -178
- package/src/ui/render-coalescer.ts +44 -3
- package/src/ui/render-diff.ts +2 -2
- package/src/ui/run-dashboard.ts +122 -21
- package/src/ui/run-event-bus.ts +66 -0
- package/src/ui/run-snapshot-cache.ts +84 -81
- package/src/ui/settings-overlay.ts +3 -3
- package/src/ui/status-colors.ts +24 -0
- package/src/ui/tool-progress-formatter.ts +1 -1
- package/src/ui/tool-render.ts +3 -3
- package/src/ui/transcript-cache.ts +5 -10
- package/src/ui/transcript-entries.ts +68 -72
- package/src/ui/transcript-viewer.ts +54 -14
- package/src/ui/widget/index.ts +26 -15
- package/src/ui/widget/widget-model.ts +18 -9
- package/src/ui/widget/widget-renderer.ts +2 -5
- package/src/utils/fingerprint.ts +1 -1
- package/src/utils/paths.ts +1 -1
- package/src/utils/project-detector.ts +1 -1
- package/src/worktree/worktree-manager.ts +47 -19
- package/src/state/atomic-write-v2.ts +0 -108
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* child-pi-streams.ts — Stdout/stderr line parsing + observation for child Pi.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from child-pi.ts (H-7 decomposition, step 4). The code is a verbatim
|
|
5
|
+
* copy of what lived in child-pi.ts before this extraction — only the imports
|
|
6
|
+
* were updated to import from child-pi-transcript.ts (compactString,
|
|
7
|
+
* compactValue, appendTranscript, flushPendingTranscriptWrites) and
|
|
8
|
+
* child-pi-constants.ts (MAX_*_CHARS, MAX_LINE_BUFFER_BYTES).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { logInternalError } from "../utils/internal-error.ts";
|
|
12
|
+
import type { ChildPiRunInput } from "./child-pi.ts";
|
|
13
|
+
import { MAX_ASSISTANT_TEXT_CHARS, MAX_LINE_BUFFER_BYTES, MAX_TOOL_INPUT_CHARS, MAX_TOOL_RESULT_CHARS } from "./child-pi-constants.ts";
|
|
14
|
+
import { appendTranscript, compactString, compactValue, flushPendingTranscriptWrites } from "./child-pi-transcript.ts";
|
|
15
|
+
import { extractText } from "./pi-json-output.ts";
|
|
16
|
+
|
|
17
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
18
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
19
|
+
return value as Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function compactContentPart(part: unknown): unknown | undefined {
|
|
23
|
+
const record = asRecord(part);
|
|
24
|
+
if (!record) return undefined;
|
|
25
|
+
if (record.type === "text")
|
|
26
|
+
return {
|
|
27
|
+
type: "text",
|
|
28
|
+
text:
|
|
29
|
+
typeof record.text === "string"
|
|
30
|
+
? compactString(record.text, MAX_ASSISTANT_TEXT_CHARS, {
|
|
31
|
+
preserveImportant: false,
|
|
32
|
+
})
|
|
33
|
+
: "",
|
|
34
|
+
};
|
|
35
|
+
if (record.type === "toolCall")
|
|
36
|
+
return {
|
|
37
|
+
type: "toolCall",
|
|
38
|
+
name: record.name,
|
|
39
|
+
input: compactValue(typeof record.input === "string" ? compactString(record.input, MAX_TOOL_INPUT_CHARS) : record.input),
|
|
40
|
+
};
|
|
41
|
+
if (record.type === "toolResult")
|
|
42
|
+
return {
|
|
43
|
+
type: "toolResult",
|
|
44
|
+
name: record.name,
|
|
45
|
+
content: compactValue(
|
|
46
|
+
typeof record.content === "string" ? compactString(record.content, MAX_TOOL_RESULT_CHARS) : record.content,
|
|
47
|
+
),
|
|
48
|
+
};
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function compactChildPiEvent(event: unknown): unknown | undefined {
|
|
53
|
+
const record = asRecord(event);
|
|
54
|
+
if (!record) return undefined;
|
|
55
|
+
if (record.type === "message_update") return undefined;
|
|
56
|
+
if (record.type === "tool_execution_start" || record.type === "tool_execution_end") {
|
|
57
|
+
return {
|
|
58
|
+
type: record.type,
|
|
59
|
+
toolName: record.toolName,
|
|
60
|
+
args: record.args,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (record.type === "tool_result_end" || record.type === "message_end" || record.type === "message") {
|
|
64
|
+
const message = asRecord(record.message);
|
|
65
|
+
if (message?.role === "user" || message?.role === "system") return undefined;
|
|
66
|
+
const content = Array.isArray(message?.content)
|
|
67
|
+
? message.content.map(compactContentPart).filter((part) => part !== undefined)
|
|
68
|
+
: undefined;
|
|
69
|
+
return {
|
|
70
|
+
type: record.type,
|
|
71
|
+
...(typeof record.text === "string" ? { text: record.text } : {}),
|
|
72
|
+
...(message
|
|
73
|
+
? {
|
|
74
|
+
message: {
|
|
75
|
+
role: message.role,
|
|
76
|
+
...(content ? { content } : {}),
|
|
77
|
+
usage: message.usage,
|
|
78
|
+
model: message.model,
|
|
79
|
+
errorMessage: message.errorMessage,
|
|
80
|
+
stopReason: message.stopReason,
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
: {}),
|
|
84
|
+
usage: record.usage,
|
|
85
|
+
model: record.model,
|
|
86
|
+
provider: record.provider,
|
|
87
|
+
stopReason: record.stopReason,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
return record.type ? { type: record.type } : undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function displayTextFromCompactEvent(event: unknown): string | undefined {
|
|
94
|
+
const record = asRecord(event);
|
|
95
|
+
if (!record) return undefined;
|
|
96
|
+
if (record.type === "tool_execution_start") {
|
|
97
|
+
return typeof record.toolName === "string" ? `tool: ${record.toolName}` : "tool started";
|
|
98
|
+
}
|
|
99
|
+
if (record.type !== "message" && record.type !== "message_end") return undefined;
|
|
100
|
+
const message = asRecord(record.message);
|
|
101
|
+
if (message?.role !== undefined && message.role !== "assistant") return undefined;
|
|
102
|
+
const content = Array.isArray(message?.content) ? message.content : [];
|
|
103
|
+
const text = content
|
|
104
|
+
.flatMap((part) => {
|
|
105
|
+
const item = asRecord(part);
|
|
106
|
+
return item?.type === "text" && typeof item.text === "string" ? [item.text] : [];
|
|
107
|
+
})
|
|
108
|
+
.join("\n")
|
|
109
|
+
.trim();
|
|
110
|
+
return text || (typeof record.text === "string" ? record.text : undefined);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function nonJsonLineResult(line: string): {
|
|
114
|
+
persistedLine: string;
|
|
115
|
+
event?: unknown;
|
|
116
|
+
displayLine?: string;
|
|
117
|
+
json: boolean;
|
|
118
|
+
} {
|
|
119
|
+
return { json: false, persistedLine: line, displayLine: line };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function compactChildPiLine(
|
|
123
|
+
line: string,
|
|
124
|
+
preParsed?: unknown,
|
|
125
|
+
): {
|
|
126
|
+
persistedLine: string;
|
|
127
|
+
event?: unknown;
|
|
128
|
+
displayLine?: string;
|
|
129
|
+
json: boolean;
|
|
130
|
+
} {
|
|
131
|
+
// OPT-PHASE2: when the caller (emitLine) already parsed the line, pass the
|
|
132
|
+
// result via preParsed to avoid a redundant JSON.parse. Standalone callers
|
|
133
|
+
// without a preParsed fall back to their own parse+catch (DRY: single
|
|
134
|
+
// compact+return path for both branches).
|
|
135
|
+
let parsed: unknown;
|
|
136
|
+
if (preParsed !== undefined) {
|
|
137
|
+
parsed = preParsed;
|
|
138
|
+
} else {
|
|
139
|
+
try {
|
|
140
|
+
parsed = JSON.parse(line);
|
|
141
|
+
} catch {
|
|
142
|
+
return nonJsonLineResult(line);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const compact = compactChildPiEvent(parsed);
|
|
146
|
+
return {
|
|
147
|
+
json: true,
|
|
148
|
+
event: compact,
|
|
149
|
+
persistedLine: compact ? JSON.stringify(compact) : "",
|
|
150
|
+
displayLine: displayTextFromCompactEvent(compact),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export class ChildPiLineObserver {
|
|
155
|
+
private buffer = "";
|
|
156
|
+
private readonly input: ChildPiRunInput;
|
|
157
|
+
/** F9: bounded ring buffer for RAW assistant-text fragments. Consumers
|
|
158
|
+
* (getRawFinalText) only read the last element, but the legacy implementation
|
|
159
|
+
* accumulated every fragment unconditionally, which let a verbose/long-running
|
|
160
|
+
* worker grow this array linearly with output. We retain the last 2 entries:
|
|
161
|
+
* the consumer needs the last; we keep the second-to-last only as a defensive
|
|
162
|
+
* fence against a race where a final event arrives just after the consumer
|
|
163
|
+
* read (the previous "last" is still the most-recent pre-final text in that
|
|
164
|
+
* window). 2 is well below any plausible consumer's "tail-only" need while
|
|
165
|
+
* bounding memory. */
|
|
166
|
+
private static readonly MAX_RAW_TEXT_EVENTS = 2;
|
|
167
|
+
private readonly rawTextEvents: string[] = [];
|
|
168
|
+
/** F9: bounded ring buffer for intermediate findings. The downstream digest
|
|
169
|
+
* (getIntermediateFindings) slices the last 20, but the array previously grew
|
|
170
|
+
* to 1000s of entries. We keep MAX_INTERMEDIATE_DIGEST_LINES + headroom so
|
|
171
|
+
* the public API behaviour is preserved (still returns "last 20 lines"). */
|
|
172
|
+
private static readonly MAX_INTERMEDIATE_FINDINGS = 32;
|
|
173
|
+
private readonly intermediateFindings: string[] = [];
|
|
174
|
+
|
|
175
|
+
constructor(input: ChildPiRunInput) {
|
|
176
|
+
this.input = input;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
observe(text: string): void {
|
|
180
|
+
this.buffer += text;
|
|
181
|
+
// Cap the buffer to prevent unbounded memory growth when a child process
|
|
182
|
+
// produces output without newlines (RT-F8). When exceeded, force-flush
|
|
183
|
+
// the buffer as a single line and log a warning.
|
|
184
|
+
if (this.buffer.length > MAX_LINE_BUFFER_BYTES) {
|
|
185
|
+
logInternalError(
|
|
186
|
+
"child-pi.buffer-overflow",
|
|
187
|
+
new Error(`Line buffer exceeded ${MAX_LINE_BUFFER_BYTES} bytes; force-flushing`),
|
|
188
|
+
`bufferLen=${this.buffer.length}`,
|
|
189
|
+
);
|
|
190
|
+
const line = this.buffer;
|
|
191
|
+
this.buffer = "";
|
|
192
|
+
this.emitLine(line);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const lines = this.buffer.split(/\r?\n/);
|
|
196
|
+
this.buffer = lines.pop() ?? "";
|
|
197
|
+
for (const line of lines) this.emitLine(line);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
flush(): Promise<void> {
|
|
201
|
+
if (this.buffer) {
|
|
202
|
+
const line = this.buffer;
|
|
203
|
+
this.buffer = "";
|
|
204
|
+
this.emitLine(line);
|
|
205
|
+
}
|
|
206
|
+
// OPT-06 follow-up: appendTranscript is fire-and-forget async, so the file
|
|
207
|
+
// may not exist on disk by the time this returns. Drain the module-scoped
|
|
208
|
+
// transcript batch buffer before resolving so callers that immediately read the
|
|
209
|
+
// transcript file (e.g. integration tests at phase4-runtime:37/:68/:103
|
|
210
|
+
// after `await observer.flush()`) see the full content.
|
|
211
|
+
return flushPendingTranscriptWrites();
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Last non-empty RAW assistant text (mirrors {@link parsePiJsonOutput}'s
|
|
215
|
+
* finalText semantics but uncapped). Undefined when no assistant text was
|
|
216
|
+
* seen by this observer. {@link extractText} already drops empty fragments,
|
|
217
|
+
* so the last entry is the final assistant utterance. */
|
|
218
|
+
getRawFinalText(): string | undefined {
|
|
219
|
+
return this.rawTextEvents.length > 0 ? this.rawTextEvents[this.rawTextEvents.length - 1] : undefined;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** #7 hardening: returns a bounded digest of intermediate findings accumulated
|
|
223
|
+
* during the run. This is NOT the final answer — it is a best-effort capture
|
|
224
|
+
* of the last assistant text or tool-result display lines before budget
|
|
225
|
+
* exhaustion. Only populated when getRawFinalText() would return undefined.
|
|
226
|
+
* @param maxChars - maximum total characters to return (default 500). */
|
|
227
|
+
getIntermediateFindings(maxChars = 500): string {
|
|
228
|
+
const MAX_INTERMEDIATE_DIGEST_LINES = 20;
|
|
229
|
+
if (this.intermediateFindings.length === 0) return "";
|
|
230
|
+
// Take the last N lines and join, then cap.
|
|
231
|
+
const lines = this.intermediateFindings.slice(-MAX_INTERMEDIATE_DIGEST_LINES);
|
|
232
|
+
const joined = lines.join("\n");
|
|
233
|
+
if (joined.length <= maxChars) return joined;
|
|
234
|
+
// Return the tail within the budget.
|
|
235
|
+
return joined.slice(-maxChars);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
private emitLine(line: string): void {
|
|
239
|
+
if (!line.trim()) return;
|
|
240
|
+
// OPT-PHASE2: parse the line EXACTLY ONCE. The parsed value feeds both
|
|
241
|
+
// (a) raw assistant-text extraction for the authoritative result and
|
|
242
|
+
// (b) compaction for the telemetry transcript — previously each path
|
|
243
|
+
// called JSON.parse independently (2 parses/line). When the line is not
|
|
244
|
+
// valid JSON, parsed stays undefined and compactChildPiLine runs its own
|
|
245
|
+
// catch path to produce the json:false fallback.
|
|
246
|
+
let parsed: unknown;
|
|
247
|
+
try {
|
|
248
|
+
parsed = JSON.parse(line);
|
|
249
|
+
} catch {
|
|
250
|
+
parsed = undefined;
|
|
251
|
+
}
|
|
252
|
+
if (parsed !== undefined) {
|
|
253
|
+
const rawTexts = extractText(parsed);
|
|
254
|
+
if (rawTexts.length > 0) {
|
|
255
|
+
// F9: trim from the front if the push would exceed the cap. Slice's
|
|
256
|
+
// second arg excludes the index, so this drops the oldest entries
|
|
257
|
+
// while keeping the freshly pushed tail.
|
|
258
|
+
this.rawTextEvents.push(...rawTexts);
|
|
259
|
+
const rawOverflow = this.rawTextEvents.length - ChildPiLineObserver.MAX_RAW_TEXT_EVENTS;
|
|
260
|
+
if (rawOverflow > 0) this.rawTextEvents.splice(0, rawOverflow);
|
|
261
|
+
// Also capture raw assistant text as intermediate findings — the last raw
|
|
262
|
+
// text may be a partial answer before the worker ran out of budget.
|
|
263
|
+
const last = rawTexts[rawTexts.length - 1];
|
|
264
|
+
if (last.trim().length > 0) {
|
|
265
|
+
this.intermediateFindings.push(last.trim());
|
|
266
|
+
const findingsOverflow = this.intermediateFindings.length - ChildPiLineObserver.MAX_INTERMEDIATE_FINDINGS;
|
|
267
|
+
if (findingsOverflow > 0) this.intermediateFindings.splice(0, findingsOverflow);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
// OPT-PHASE2: construct the non-JSON fallback directly when parsing failed,
|
|
272
|
+
// so a broken line triggers exactly ONE (failed) parse instead of two.
|
|
273
|
+
const compact = parsed !== undefined ? compactChildPiLine(line, parsed) : nonJsonLineResult(line);
|
|
274
|
+
if (compact.event !== undefined) {
|
|
275
|
+
try {
|
|
276
|
+
this.input.onJsonEvent?.(compact.event);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
logInternalError("child-pi.on-json-event", error, `line=${compact.persistedLine ?? compact.displayLine ?? ""}`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (compact.persistedLine) appendTranscript(this.input, compact.persistedLine);
|
|
282
|
+
if (compact.displayLine?.trim()) {
|
|
283
|
+
try {
|
|
284
|
+
this.input.onStdoutLine?.(compact.displayLine);
|
|
285
|
+
} catch (error) {
|
|
286
|
+
logInternalError("child-pi.on-stdout-line", error, `line=${compact.displayLine}`);
|
|
287
|
+
}
|
|
288
|
+
// #7 hardening: capture display lines (tool results, stdout) as intermediate
|
|
289
|
+
// findings. This ensures we capture tool output even when no assistant text
|
|
290
|
+
// is emitted (budget exhausted on tool calls).
|
|
291
|
+
this.intermediateFindings.push(compact.displayLine!.trim());
|
|
292
|
+
const findingsOverflow = this.intermediateFindings.length - ChildPiLineObserver.MAX_INTERMEDIATE_FINDINGS;
|
|
293
|
+
if (findingsOverflow > 0) this.intermediateFindings.splice(0, findingsOverflow);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* child-pi-transcript.ts — Transcript batching module for child Pi worker output.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from child-pi.ts (H-7 decomposition, step 1). Zero behavior change.
|
|
5
|
+
*
|
|
6
|
+
* Architecture:
|
|
7
|
+
* appendTranscript() validates the transcriptPath against the artifactsRoot
|
|
8
|
+
* containment boundary, redacts the line, and pushes it to a module-scoped
|
|
9
|
+
* batch buffer keyed by safePath. A debounced 50ms timer flushes the buffer
|
|
10
|
+
* in one open/write/close per path (O_NOFOLLOW | O_CREAT | O_APPEND).
|
|
11
|
+
*
|
|
12
|
+
* Lifecycle boundaries (ChildPiLineObserver.flush, runChildPi settle) must
|
|
13
|
+
* call flushPendingTranscriptWrites() so callers that immediately read the
|
|
14
|
+
* transcript file see complete content.
|
|
15
|
+
*
|
|
16
|
+
* Ordering: lines are appended in call order. The flush writes the joined
|
|
17
|
+
* array preserving intra-batch order. Inter-batch order is not guaranteed
|
|
18
|
+
* but transcript is append-only telemetry.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import * as fs from "node:fs";
|
|
22
|
+
import { DEFAULT_CHILD_PI } from "../config/defaults.ts";
|
|
23
|
+
import { logInternalError } from "../utils/internal-error.ts";
|
|
24
|
+
import { redactJsonLine } from "../utils/redaction.ts";
|
|
25
|
+
import { resolveRealContainedPath } from "../utils/safe-paths.ts";
|
|
26
|
+
import type { ChildPiRunInput } from "./child-pi.ts";
|
|
27
|
+
import { applyCompactPipeline } from "./compact-pipeline.ts";
|
|
28
|
+
import { TruncationStage } from "./compact-stages/truncation-stage.ts";
|
|
29
|
+
|
|
30
|
+
// ── Transcript batch buffer (OPT-PHASE3) ────────────────────────────────
|
|
31
|
+
// Instead of open/write/close per line (3 syscalls × N), accumulate lines
|
|
32
|
+
// in a module-scoped buffer and flush them in one open/write/close per path
|
|
33
|
+
// every TRANSCRIPT_FLUSH_MS. Lifecycle boundaries (observer.flush, settle)
|
|
34
|
+
// force-flush the buffer before returning so transcript reads are complete.
|
|
35
|
+
const transcriptBatches = new Map<string, string[]>();
|
|
36
|
+
let transcriptFlushTimer: ReturnType<typeof setTimeout> | undefined;
|
|
37
|
+
const TRANSCRIPT_FLUSH_MS = 50;
|
|
38
|
+
|
|
39
|
+
export function appendTranscript(input: ChildPiRunInput, line: string): void {
|
|
40
|
+
if (!input.transcriptPath) return;
|
|
41
|
+
// SECURITY FIX (Issue #1): Validate transcriptPath against artifactsRoot to prevent
|
|
42
|
+
// arbitrary file writes and symlink traversal attacks. An attacker who can influence
|
|
43
|
+
// the task graph could set transcriptPath to /etc/passwd or similar, and mkdirSync
|
|
44
|
+
// with recursive:true would create parent directories. Additionally, appendFileSync
|
|
45
|
+
// follows symlinks, potentially writing to sensitive files.
|
|
46
|
+
let safePath: string;
|
|
47
|
+
try {
|
|
48
|
+
const artifactsRoot = input.artifactsRoot ?? input.cwd;
|
|
49
|
+
safePath = resolveRealContainedPath(artifactsRoot, input.transcriptPath);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
logInternalError("child-pi.transcript-path-rejected", error as Error, `transcriptPath=${input.transcriptPath}`);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
trackTranscriptWrite(safePath, line);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function scheduleTranscriptFlush(): void {
|
|
58
|
+
if (transcriptFlushTimer) return;
|
|
59
|
+
transcriptFlushTimer = setTimeout(() => {
|
|
60
|
+
transcriptFlushTimer = undefined;
|
|
61
|
+
void flushTranscriptBatches();
|
|
62
|
+
}, TRANSCRIPT_FLUSH_MS);
|
|
63
|
+
transcriptFlushTimer.unref?.();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function flushTranscriptBatches(): Promise<void> {
|
|
67
|
+
const entries = [...transcriptBatches.entries()];
|
|
68
|
+
transcriptBatches.clear();
|
|
69
|
+
await Promise.allSettled(
|
|
70
|
+
entries.map(async ([safePath, lines]) => {
|
|
71
|
+
if (lines.length === 0) return;
|
|
72
|
+
const content = lines.join("");
|
|
73
|
+
try {
|
|
74
|
+
const fd = await fs.promises.open(
|
|
75
|
+
safePath,
|
|
76
|
+
fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW | fs.constants.O_CREAT | fs.constants.O_APPEND,
|
|
77
|
+
0o600,
|
|
78
|
+
);
|
|
79
|
+
try {
|
|
80
|
+
await fd.write(content, undefined, "utf-8");
|
|
81
|
+
} finally {
|
|
82
|
+
await fd.close();
|
|
83
|
+
}
|
|
84
|
+
} catch (error) {
|
|
85
|
+
logInternalError("child-pi.transcript-write-failed", error as Error, `path=${safePath}`);
|
|
86
|
+
}
|
|
87
|
+
}),
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function trackTranscriptWrite(safePath: string, line: string): void {
|
|
92
|
+
const content = `${redactJsonLine(line)}\n`;
|
|
93
|
+
let batch = transcriptBatches.get(safePath);
|
|
94
|
+
if (!batch) {
|
|
95
|
+
batch = [];
|
|
96
|
+
transcriptBatches.set(safePath, batch);
|
|
97
|
+
}
|
|
98
|
+
batch.push(content);
|
|
99
|
+
scheduleTranscriptFlush();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Drain the transcript batch buffer and await any remaining in-flight writes.
|
|
104
|
+
* Called by lifecycle boundaries (ChildPiLineObserver.flush, runChildPi settle)
|
|
105
|
+
* so that transcript files are complete before callers read them.
|
|
106
|
+
*
|
|
107
|
+
* Uses a while loop to re-check the buffer after each flush — new lines may
|
|
108
|
+
* arrive during the async I/O window (trackTranscriptWrite → scheduleTranscriptFlush).
|
|
109
|
+
*/
|
|
110
|
+
export async function flushPendingTranscriptWrites(): Promise<void> {
|
|
111
|
+
if (transcriptFlushTimer) {
|
|
112
|
+
clearTimeout(transcriptFlushTimer);
|
|
113
|
+
transcriptFlushTimer = undefined;
|
|
114
|
+
}
|
|
115
|
+
while (transcriptBatches.size > 0) {
|
|
116
|
+
await flushTranscriptBatches();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Reset the module-scoped transcript batch state. Exported for test isolation
|
|
122
|
+
* only — production code should never call this.
|
|
123
|
+
*/
|
|
124
|
+
export function resetTranscriptBatchState(): void {
|
|
125
|
+
if (transcriptFlushTimer) {
|
|
126
|
+
clearTimeout(transcriptFlushTimer);
|
|
127
|
+
transcriptFlushTimer = undefined;
|
|
128
|
+
}
|
|
129
|
+
transcriptBatches.clear();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// ── Compaction helpers (moved from child-pi.ts; these don't need batching) ──
|
|
133
|
+
|
|
134
|
+
export function compactString(
|
|
135
|
+
value: string,
|
|
136
|
+
maxChars = DEFAULT_CHILD_PI.maxCompactContentChars,
|
|
137
|
+
opts: { preserveImportant?: boolean } = {},
|
|
138
|
+
): string {
|
|
139
|
+
if (value.length <= maxChars) return value;
|
|
140
|
+
const result = applyCompactPipeline(value, [
|
|
141
|
+
new TruncationStage(maxChars, {
|
|
142
|
+
preserveImportant: opts.preserveImportant,
|
|
143
|
+
}),
|
|
144
|
+
]);
|
|
145
|
+
return result.text;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function compactValue(value: unknown): unknown {
|
|
149
|
+
if (typeof value === "string") return compactString(value);
|
|
150
|
+
if (Array.isArray(value)) {
|
|
151
|
+
// BUG-4: silent .slice(0, 20) lost items 21-50 with no marker.
|
|
152
|
+
if (value.length > 20) {
|
|
153
|
+
return [...value.slice(0, 20).map(compactValue), `[pi-crew truncated ${value.length - 20} entries]`];
|
|
154
|
+
}
|
|
155
|
+
return value.map(compactValue);
|
|
156
|
+
}
|
|
157
|
+
const record = asRecord(value);
|
|
158
|
+
if (!record) return value;
|
|
159
|
+
const entries = Object.entries(record);
|
|
160
|
+
const compacted: Record<string, unknown> = {};
|
|
161
|
+
for (const [key, entry] of entries.slice(0, 20)) compacted[key] = compactValue(entry);
|
|
162
|
+
if (entries.length > 20) compacted["[truncated]"] = `${entries.length - 20} entries`;
|
|
163
|
+
return compacted;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
167
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
168
|
+
return value as Record<string, unknown>;
|
|
169
|
+
}
|