pi-goal-delegate 0.1.0 → 0.3.1
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 +147 -0
- package/README.md +409 -280
- package/package.json +2 -2
- package/skills/delegate/SKILL.md +128 -47
- package/src/command.ts +124 -32
- package/src/contract.ts +137 -11
- package/src/doctor.ts +385 -0
- package/src/events.ts +22 -1
- package/src/index.ts +466 -271
- package/src/registry.ts +108 -29
- package/src/result-schema.ts +143 -0
- package/src/retention.ts +132 -34
- package/src/run.ts +93 -21
- package/src/spawn.ts +6 -2
- package/src/supervisor.mjs +113 -4
- package/src/verify.ts +16 -1
- package/src/worker.ts +128 -59
- package/src/worktree.ts +107 -3
package/src/run.ts
CHANGED
|
@@ -24,12 +24,14 @@ import {
|
|
|
24
24
|
formatDuration,
|
|
25
25
|
formatUsage,
|
|
26
26
|
isTerminal,
|
|
27
|
+
MAX_WAIT_MS,
|
|
27
28
|
parentBudgetVerdict,
|
|
28
29
|
shortGoal,
|
|
29
30
|
verifiedStatus,
|
|
30
31
|
type BudgetLimits,
|
|
31
32
|
type BudgetVerdict,
|
|
32
33
|
type ContainmentVerdict,
|
|
34
|
+
type JsonValue,
|
|
33
35
|
type RunProgress,
|
|
34
36
|
type RunScope,
|
|
35
37
|
type RunSpec,
|
|
@@ -55,6 +57,7 @@ import {
|
|
|
55
57
|
} from "./identity.ts";
|
|
56
58
|
import {
|
|
57
59
|
buildChildCommand,
|
|
60
|
+
childEnvironment,
|
|
58
61
|
describeRead,
|
|
59
62
|
ensureRunDir,
|
|
60
63
|
isRunId,
|
|
@@ -72,10 +75,17 @@ import {
|
|
|
72
75
|
appendJsonLine,
|
|
73
76
|
} from "./spawn.ts";
|
|
74
77
|
import { runVerification } from "./verify.ts";
|
|
75
|
-
import {
|
|
78
|
+
import {
|
|
79
|
+
createWorktree,
|
|
80
|
+
exportWorktreeIntegration,
|
|
81
|
+
removeWorktree,
|
|
82
|
+
worktreeCleanupEnabled,
|
|
83
|
+
type WorktreeIntegration,
|
|
84
|
+
type WorktreeRef,
|
|
85
|
+
} from "./worktree.ts";
|
|
76
86
|
|
|
77
87
|
const TICK_MS = 250;
|
|
78
|
-
const INLINE_LIMIT_MS =
|
|
88
|
+
const INLINE_LIMIT_MS = MAX_WAIT_MS;
|
|
79
89
|
const DEFAULT_VERIFY_TIMEOUT_MS = 120_000;
|
|
80
90
|
|
|
81
91
|
/** What the child writes at the moment it has a verdict. */
|
|
@@ -87,6 +97,9 @@ export interface ChildResult {
|
|
|
87
97
|
evidence?: string;
|
|
88
98
|
/** What the parent must provide. Only a blocked verdict carries one. */
|
|
89
99
|
needs?: string;
|
|
100
|
+
result?: JsonValue;
|
|
101
|
+
/** The child's successful completion gate, before the parent's independent check. */
|
|
102
|
+
childVerification?: VerificationRecord;
|
|
90
103
|
turns?: number;
|
|
91
104
|
maxTurns?: number;
|
|
92
105
|
toolCalls?: number;
|
|
@@ -169,6 +182,12 @@ export interface RunOutcome {
|
|
|
169
182
|
evidence?: string;
|
|
170
183
|
/** What the child needs in order to continue. Set only for a blocked run. */
|
|
171
184
|
needs?: string;
|
|
185
|
+
/** Structured JSON returned to the parent or a codemode orchestrator. */
|
|
186
|
+
result?: JsonValue;
|
|
187
|
+
/** The successful child-side gate; `verification` below is the parent's recheck. */
|
|
188
|
+
childVerification?: VerificationRecord;
|
|
189
|
+
/** Previous run whose session and worktree this run continues. */
|
|
190
|
+
resumedFrom?: string;
|
|
172
191
|
/**
|
|
173
192
|
* What the parent proved about the completion claim.
|
|
174
193
|
*
|
|
@@ -190,6 +209,8 @@ export interface RunOutcome {
|
|
|
190
209
|
logCapReached?: boolean;
|
|
191
210
|
settledInline?: boolean;
|
|
192
211
|
worktree?: WorktreeRef;
|
|
212
|
+
/** Diff, patch, and apply-check for integrating an isolated checkout. */
|
|
213
|
+
integration?: WorktreeIntegration;
|
|
193
214
|
error?: string;
|
|
194
215
|
}
|
|
195
216
|
|
|
@@ -200,6 +221,12 @@ export interface StartRequest {
|
|
|
200
221
|
maxTurns: number;
|
|
201
222
|
timeoutMinutes: number;
|
|
202
223
|
maxCostUsd?: number;
|
|
224
|
+
resultSchema?: Record<string, unknown>;
|
|
225
|
+
/** Absolute position and maximum for this delegation tree. */
|
|
226
|
+
depth?: number;
|
|
227
|
+
maxDepth?: number;
|
|
228
|
+
/** A parent run's deadline, which a nested run may not exceed. */
|
|
229
|
+
parentDeadline?: number;
|
|
203
230
|
model?: string;
|
|
204
231
|
modelSource: RunSpec["modelSource"];
|
|
205
232
|
thinking: string;
|
|
@@ -219,6 +246,8 @@ export interface StartRequest {
|
|
|
219
246
|
worktree?: boolean;
|
|
220
247
|
/** Bounded wait for an immediate settle. 0 returns the handle at once. */
|
|
221
248
|
inlineSettleMs?: number;
|
|
249
|
+
/** Aborts only the inline wait; the admitted run continues in the background. */
|
|
250
|
+
signal?: AbortSignal;
|
|
222
251
|
/**
|
|
223
252
|
* Called once admission is real: spec on disk, supervisor spawned, watcher
|
|
224
253
|
* running. A registry uses it to register the handle before the inline wait,
|
|
@@ -227,7 +256,7 @@ export interface StartRequest {
|
|
|
227
256
|
onAdmitted?: (handle: RunHandle) => void;
|
|
228
257
|
/** Tools active in the parent, used to keep codemode callable in the child. */
|
|
229
258
|
parentActiveTools?: readonly string[];
|
|
230
|
-
onProgress?: (progress: RunProgress, status: RunStatus) => void;
|
|
259
|
+
onProgress?: (progress: RunProgress, status: RunStatus, runId: string) => void;
|
|
231
260
|
onSettle?: (outcome: RunOutcome) => void;
|
|
232
261
|
}
|
|
233
262
|
|
|
@@ -254,7 +283,7 @@ export interface RunHandle {
|
|
|
254
283
|
cancel: (reason?: KillReason, graceMs?: number) => Promise<RunOutcome>;
|
|
255
284
|
}
|
|
256
285
|
|
|
257
|
-
type KillReason = "abort" | "timeout" | "limit";
|
|
286
|
+
type KillReason = "abort" | "timeout" | "limit" | "no_progress";
|
|
258
287
|
|
|
259
288
|
function newRunId(): string {
|
|
260
289
|
return `dl_${Date.now().toString(36)}_${randomBytes(4).toString("hex")}`;
|
|
@@ -285,7 +314,7 @@ interface Runtime {
|
|
|
285
314
|
tick?: ReturnType<typeof setInterval>;
|
|
286
315
|
deadline?: ReturnType<typeof setTimeout>;
|
|
287
316
|
onSettle?: (outcome: RunOutcome) => void;
|
|
288
|
-
onProgress?: (progress: RunProgress, status: RunStatus) => void;
|
|
317
|
+
onProgress?: (progress: RunProgress, status: RunStatus, runId: string) => void;
|
|
289
318
|
resolveDone: (outcome: RunOutcome) => void;
|
|
290
319
|
lastProgressAt: number;
|
|
291
320
|
}
|
|
@@ -298,6 +327,7 @@ function statusFrom(killReason: Runtime["killReason"], result: ChildResult | und
|
|
|
298
327
|
if (killReason === "timeout") return "timeout";
|
|
299
328
|
if (killReason === "limit") return "limit";
|
|
300
329
|
if (killReason === "abort") return "aborted";
|
|
330
|
+
if (killReason === "no_progress") return "no_progress";
|
|
301
331
|
if (result?.status && result.status !== "stopped" && isTerminal(result.status as RunStatus)) {
|
|
302
332
|
return result.status as RunStatus;
|
|
303
333
|
}
|
|
@@ -408,6 +438,9 @@ async function seal(runtime: Runtime, handle: RunHandle): Promise<RunOutcome> {
|
|
|
408
438
|
|
|
409
439
|
const { verified, verification } = await verifyClaim(runtime, status, result);
|
|
410
440
|
status = verifiedStatus(status, verified);
|
|
441
|
+
const integration = runtime.spec.worktree
|
|
442
|
+
? exportWorktreeIntegration(runtime.spec.worktree, runtime.paths.dir)
|
|
443
|
+
: undefined;
|
|
411
444
|
|
|
412
445
|
const outcome: RunOutcome = {
|
|
413
446
|
version: 1,
|
|
@@ -422,6 +455,9 @@ async function seal(runtime: Runtime, handle: RunHandle): Promise<RunOutcome> {
|
|
|
422
455
|
summary: runtime.killDetail ?? summarize(result, handle.progress, exit),
|
|
423
456
|
evidence: result?.evidence?.trim() || undefined,
|
|
424
457
|
needs: result?.needs?.trim() || undefined,
|
|
458
|
+
result: result?.result,
|
|
459
|
+
childVerification: result?.childVerification,
|
|
460
|
+
resumedFrom: runtime.spec.resumedFrom,
|
|
425
461
|
verified,
|
|
426
462
|
verification,
|
|
427
463
|
sessionFile: result?.sessionFile,
|
|
@@ -435,6 +471,7 @@ async function seal(runtime: Runtime, handle: RunHandle): Promise<RunOutcome> {
|
|
|
435
471
|
leakedPids: runtime.leakedPids,
|
|
436
472
|
logCapReached: state.kind === "ok" && (state.value.capped?.length ?? 0) > 0,
|
|
437
473
|
worktree: runtime.spec.worktree,
|
|
474
|
+
integration,
|
|
438
475
|
error: result?.error ?? exit?.error,
|
|
439
476
|
};
|
|
440
477
|
writeJsonAtomic(runtime.paths.outcome, outcome);
|
|
@@ -477,6 +514,7 @@ async function verifyClaim(
|
|
|
477
514
|
command: runtime.spec.verify.command,
|
|
478
515
|
cwd: runtime.spec.cwd,
|
|
479
516
|
timeoutMs: Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_VERIFY_TIMEOUT_MS,
|
|
517
|
+
env: childEnvironment({}),
|
|
480
518
|
});
|
|
481
519
|
// A timed-out or unspawnable command is not a pass. `exitCode === 0` is.
|
|
482
520
|
const passed = !verification.timedOut && verification.exitCode === 0;
|
|
@@ -588,7 +626,10 @@ function buildSpec(runId: string, request: StartRequest, cwd: string): RunSpec {
|
|
|
588
626
|
context: request.context,
|
|
589
627
|
maxTurns: request.maxTurns,
|
|
590
628
|
timeoutMinutes: request.timeoutMinutes,
|
|
591
|
-
deadline:
|
|
629
|
+
deadline: Math.min(
|
|
630
|
+
Date.now() + request.timeoutMinutes * 60_000,
|
|
631
|
+
request.parentDeadline ?? Number.POSITIVE_INFINITY,
|
|
632
|
+
),
|
|
592
633
|
resultPath: paths.result,
|
|
593
634
|
inboxPath: paths.inbox,
|
|
594
635
|
model: request.model,
|
|
@@ -599,8 +640,12 @@ function buildSpec(runId: string, request: StartRequest, cwd: string): RunSpec {
|
|
|
599
640
|
scope: request.scope,
|
|
600
641
|
sessionId: request.sessionId,
|
|
601
642
|
isolated: request.isolated,
|
|
643
|
+
resultSchema: request.resultSchema,
|
|
644
|
+
depth: request.depth ?? 0,
|
|
645
|
+
maxDepth: request.maxDepth ?? 0,
|
|
602
646
|
verify: request.verify,
|
|
603
647
|
resumeSession: request.resumeFrom,
|
|
648
|
+
resumedFrom: request.resumeFrom,
|
|
604
649
|
maxCostUsd: Math.max(0, request.maxCostUsd ?? DEFAULT_MAX_COST_USD),
|
|
605
650
|
createdAt: Date.now(),
|
|
606
651
|
};
|
|
@@ -613,10 +658,10 @@ function buildSpec(runId: string, request: StartRequest, cwd: string): RunSpec {
|
|
|
613
658
|
* file another process appends to. Reading it incrementally is what turns a
|
|
614
659
|
* durable log into a live turn count, a live cost, and a runaway net.
|
|
615
660
|
*/
|
|
616
|
-
function watch(runtime: Runtime, handle: RunHandle, startOffset: number): void {
|
|
661
|
+
function watch(runtime: Runtime, handle: RunHandle, startOffset: number, sourcePath: string): void {
|
|
617
662
|
const { paths } = runtime;
|
|
618
663
|
const progress = handle.progress;
|
|
619
|
-
const tailer = new LiveTail(
|
|
664
|
+
const tailer = new LiveTail(sourcePath, progress, readRange, startOffset);
|
|
620
665
|
runtime.tailer = tailer;
|
|
621
666
|
// One poll at a time. A large log, or the fence that follows a dead
|
|
622
667
|
// supervisor, can outlast the tick; two overlapping polls would read the same
|
|
@@ -642,7 +687,12 @@ function watch(runtime: Runtime, handle: RunHandle, startOffset: number): void {
|
|
|
642
687
|
? "limit"
|
|
643
688
|
: "running";
|
|
644
689
|
handle.status = live;
|
|
645
|
-
runtime.onProgress?.(progress, live);
|
|
690
|
+
runtime.onProgress?.(progress, live, handle.runId);
|
|
691
|
+
}
|
|
692
|
+
if (progress.noProgressReason && !runtime.killReason) {
|
|
693
|
+
runtime.killDetail = progress.noProgressReason;
|
|
694
|
+
await cancelRun(runtime, handle, "no_progress");
|
|
695
|
+
return;
|
|
646
696
|
}
|
|
647
697
|
// The parent's share of the budget: the same limits the child
|
|
648
698
|
// enforces, plus a grace, so this is a runaway net rather than a
|
|
@@ -699,10 +749,14 @@ export async function startRun(request: StartRequest): Promise<RunHandle> {
|
|
|
699
749
|
// a silent fall back to the shared tree.
|
|
700
750
|
let worktree: WorktreeRef | undefined;
|
|
701
751
|
if (request.worktree) worktree = createWorktree(runId, request.cwd);
|
|
752
|
+
const resumeSession = resolveResume(request.resumeFrom);
|
|
753
|
+
if (!request.worktree && request.resumeFrom && isRunId(request.resumeFrom)) {
|
|
754
|
+
const previous = readSpecFile(request.resumeFrom);
|
|
755
|
+
if (previous?.worktree && existsSync(previous.worktree.path)) worktree = previous.worktree;
|
|
756
|
+
}
|
|
702
757
|
const cwd = worktree?.path ?? request.cwd;
|
|
703
758
|
const paths = runPaths(runId);
|
|
704
759
|
ensureRunDir(paths);
|
|
705
|
-
const resumeSession = resolveResume(request.resumeFrom);
|
|
706
760
|
const tools = mergeTools(request.tools, request.parentActiveTools ?? []);
|
|
707
761
|
const draft = buildSpec(runId, request, cwd);
|
|
708
762
|
const child = buildChildCommand({
|
|
@@ -837,21 +891,27 @@ export async function startRun(request: StartRequest): Promise<RunHandle> {
|
|
|
837
891
|
writeJsonAtomic(paths.meta, meta);
|
|
838
892
|
handle.status = "running";
|
|
839
893
|
|
|
840
|
-
watch(runtime, handle, 0);
|
|
894
|
+
watch(runtime, handle, 0, paths.control);
|
|
841
895
|
request.onAdmitted?.(handle);
|
|
842
896
|
|
|
843
897
|
// The window is a deadline, not a timer that outlives it: when the run
|
|
844
|
-
// settles first the
|
|
845
|
-
//
|
|
898
|
+
// settles first or the caller aborts the wait, the timeout and listener are
|
|
899
|
+
// cleared while the child keeps running in its own process.
|
|
846
900
|
const inlineSettleMs = Math.min(Math.max(0, request.inlineSettleMs ?? 1000), INLINE_LIMIT_MS);
|
|
847
|
-
if (inlineSettleMs > 0) {
|
|
848
|
-
let expired;
|
|
901
|
+
if (inlineSettleMs > 0 && !request.signal?.aborted) {
|
|
902
|
+
let expired: ReturnType<typeof setTimeout> | undefined;
|
|
903
|
+
let onAbort: (() => void) | undefined;
|
|
849
904
|
const window = new Promise<false>((resolve) => {
|
|
850
905
|
expired = setTimeout(() => resolve(false), inlineSettleMs);
|
|
906
|
+
if (request.signal) {
|
|
907
|
+
onAbort = () => resolve(false);
|
|
908
|
+
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
909
|
+
}
|
|
851
910
|
});
|
|
852
911
|
const settled = await Promise.race([done.then(() => true), window]);
|
|
853
|
-
clearTimeout(expired);
|
|
854
|
-
if (
|
|
912
|
+
if (expired) clearTimeout(expired);
|
|
913
|
+
if (onAbort && request.signal) request.signal.removeEventListener("abort", onAbort);
|
|
914
|
+
if (settled && handle.outcome && !request.signal?.aborted) handle.outcome.settledInline = true;
|
|
855
915
|
}
|
|
856
916
|
return handle;
|
|
857
917
|
}
|
|
@@ -909,9 +969,20 @@ export function formatOutcome(outcome: RunOutcome): string {
|
|
|
909
969
|
// A blocked run has no evidence and no result: it has a request. Printing that
|
|
910
970
|
// request under "Evidence:" told the parent the opposite of what it was.
|
|
911
971
|
if (outcome.needs) lines.push("", `Needs: ${outcome.needs}`);
|
|
972
|
+
if (outcome.result !== undefined) lines.push("", `Result: ${JSON.stringify(outcome.result)}`);
|
|
912
973
|
lines.push("", verificationLine(outcome));
|
|
913
974
|
if (outcome.sessionFile) lines.push(`Child session: ${outcome.sessionFile}`);
|
|
914
975
|
if (outcome.worktree) lines.push(`Worktree: ${outcome.worktree.path} (branch ${outcome.worktree.branch})`);
|
|
976
|
+
if (outcome.integration) {
|
|
977
|
+
if (outcome.integration.diffStat) lines.push("", "Diff stat:", outcome.integration.diffStat);
|
|
978
|
+
if (outcome.integration.status) lines.push("", "Worktree status:", outcome.integration.status);
|
|
979
|
+
if (outcome.integration.patchPath) {
|
|
980
|
+
lines.push(`Patch: ${outcome.integration.patchPath}`);
|
|
981
|
+
lines.push(`Apply check: ${outcome.integration.applyCheck?.ok ? "passed" : "failed"}`);
|
|
982
|
+
if (outcome.integration.applyCommand) lines.push(`Apply with: ${outcome.integration.applyCommand}`);
|
|
983
|
+
}
|
|
984
|
+
if (outcome.integration.error) lines.push(`Worktree integration error: ${outcome.integration.error}`);
|
|
985
|
+
}
|
|
915
986
|
if (outcome.containmentVerdict) lines.push(`Containment: ${containmentLine(outcome)}`);
|
|
916
987
|
if (outcome.leakedPids?.length) lines.push(`WARNING: descendants survived cancellation: ${outcome.leakedPids.join(", ")}`);
|
|
917
988
|
lines.push(`Run record: ${outcome.runDir}`);
|
|
@@ -953,9 +1024,10 @@ export async function progressOf(paths: RunPaths): Promise<{ progress: RunProgre
|
|
|
953
1024
|
const progress = emptyProgress();
|
|
954
1025
|
let bytes = 0;
|
|
955
1026
|
try {
|
|
956
|
-
const
|
|
1027
|
+
const source = existsSync(paths.control) ? paths.control : paths.events;
|
|
1028
|
+
const size = (await stat(source)).size;
|
|
957
1029
|
if (size <= 0) return { progress, bytes };
|
|
958
|
-
const buffer = await readRange(
|
|
1030
|
+
const buffer = await readRange(source, 0, size);
|
|
959
1031
|
foldText(buffer.toString("utf8"), progress);
|
|
960
1032
|
bytes = buffer.length;
|
|
961
1033
|
} catch {
|
|
@@ -985,7 +1057,7 @@ export type AttachResult =
|
|
|
985
1057
|
export async function attachRun(
|
|
986
1058
|
runId: string,
|
|
987
1059
|
spec: RunSpec,
|
|
988
|
-
sink: { onSettle?: (outcome: RunOutcome) => void; onProgress?: (progress: RunProgress, status: RunStatus) => void },
|
|
1060
|
+
sink: { onSettle?: (outcome: RunOutcome) => void; onProgress?: (progress: RunProgress, status: RunStatus, runId: string) => void },
|
|
989
1061
|
meta?: RunMetaRecord,
|
|
990
1062
|
): Promise<AttachResult> {
|
|
991
1063
|
const paths = runPaths(runId);
|
|
@@ -1038,7 +1110,7 @@ export async function attachRun(
|
|
|
1038
1110
|
return { kind: "sealed", handle };
|
|
1039
1111
|
}
|
|
1040
1112
|
if (alive) {
|
|
1041
|
-
watch(runtime, handle, bytes);
|
|
1113
|
+
watch(runtime, handle, bytes, existsSync(paths.control) ? paths.control : paths.events);
|
|
1042
1114
|
return { kind: "attached", handle };
|
|
1043
1115
|
}
|
|
1044
1116
|
if (!observable) {
|
package/src/spawn.ts
CHANGED
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
* result.json the child, its verdict, and nothing else
|
|
14
14
|
* state.json the supervisor: pid, process group, exit, log cap
|
|
15
15
|
* inbox.jsonl the parent, appended; the child reads it
|
|
16
|
-
* child.jsonl the supervisor, the child's stdout
|
|
16
|
+
* child.jsonl the supervisor, the child's capped raw stdout
|
|
17
|
+
* control.jsonl the supervisor, compact accounting and breaker events
|
|
17
18
|
* child.log the supervisor, the child's stderr
|
|
18
19
|
*
|
|
19
20
|
* Before this split the supervisor wrote three files (pid.json, exit.json,
|
|
@@ -48,7 +49,7 @@ export function delegateRoot(): string {
|
|
|
48
49
|
/**
|
|
49
50
|
* Run ids are `dl_<time36>_<random hex>`. Anything else is not a record this
|
|
50
51
|
* extension created, and it is never allowed to name a path: a run id arrives
|
|
51
|
-
* from the model (`
|
|
52
|
+
* from the model (`delegate_status`) and from a command line, so a value like
|
|
52
53
|
* `../../etc` must be rejected before it is joined to the record root.
|
|
53
54
|
*/
|
|
54
55
|
const RUN_ID = /^dl_[a-z0-9]+_[a-z0-9]+$/u;
|
|
@@ -63,6 +64,8 @@ export interface RunPaths {
|
|
|
63
64
|
meta: string;
|
|
64
65
|
state: string;
|
|
65
66
|
events: string;
|
|
67
|
+
/** Compact accounting and breaker events, written even after the raw log cap. */
|
|
68
|
+
control: string;
|
|
66
69
|
log: string;
|
|
67
70
|
result: string;
|
|
68
71
|
outcome: string;
|
|
@@ -84,6 +87,7 @@ export function runPaths(runId: string): RunPaths {
|
|
|
84
87
|
meta: join(dir, "meta.json"),
|
|
85
88
|
state: join(dir, "state.json"),
|
|
86
89
|
events: join(dir, "child.jsonl"),
|
|
90
|
+
control: join(dir, "control.jsonl"),
|
|
87
91
|
log: join(dir, "child.log"),
|
|
88
92
|
result: join(dir, "result.json"),
|
|
89
93
|
outcome: join(dir, "outcome.json"),
|
package/src/supervisor.mjs
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
* outlive a turn, survive /reload, and be read back by a later Pi process.
|
|
7
7
|
*
|
|
8
8
|
* Contract:
|
|
9
|
-
* - stdout of the child is the JSON event stream -> child.jsonl
|
|
9
|
+
* - stdout of the child is the raw JSON event stream -> child.jsonl
|
|
10
|
+
* - compact accounting and breaker events survive the raw cap -> control.jsonl
|
|
10
11
|
* - stderr of the child is diagnostics -> child.log
|
|
11
12
|
* - the cap is a logging policy: past it we keep draining and discard the rest,
|
|
12
13
|
* because a reader that stops reading turns a full pipe into a hung child
|
|
@@ -23,8 +24,10 @@
|
|
|
23
24
|
*/
|
|
24
25
|
|
|
25
26
|
import { spawn } from "node:child_process";
|
|
27
|
+
import { createHash } from "node:crypto";
|
|
26
28
|
import { createReadStream, createWriteStream, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
27
29
|
import { join } from "node:path";
|
|
30
|
+
import { StringDecoder } from "node:string_decoder";
|
|
28
31
|
|
|
29
32
|
const RECORD_VERSION = 1;
|
|
30
33
|
|
|
@@ -114,7 +117,109 @@ try {
|
|
|
114
117
|
|
|
115
118
|
const stdout = createWriteStream(join(dir, "child.jsonl"), { flags: "a", mode: 0o600 });
|
|
116
119
|
const stderr = createWriteStream(join(dir, "child.log"), { flags: "a", mode: 0o600 });
|
|
117
|
-
|
|
120
|
+
const control = createWriteStream(join(dir, "control.jsonl"), { flags: "a", mode: 0o600 });
|
|
121
|
+
for (const stream of [stdout, stderr, control]) stream.on("error", () => undefined);
|
|
122
|
+
|
|
123
|
+
function canonical(value) {
|
|
124
|
+
if (value === null || typeof value !== "object") return value;
|
|
125
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
126
|
+
const sorted = {};
|
|
127
|
+
for (const key of Object.keys(value).sort()) sorted[key] = canonical(value[key]);
|
|
128
|
+
return sorted;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function signature(toolName, args) {
|
|
132
|
+
const canonicalArgs = JSON.stringify(canonical(args ?? {}));
|
|
133
|
+
return `${String(toolName ?? "?")}:${createHash("sha256").update(canonicalArgs).digest("hex")}`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Copy only accounting and breaker facts; never large tool results or thinking payloads. */
|
|
137
|
+
function controlEvent(event) {
|
|
138
|
+
switch (event.type) {
|
|
139
|
+
case "session":
|
|
140
|
+
return { type: "session", id: event.id };
|
|
141
|
+
case "turn_start":
|
|
142
|
+
case "agent_settled":
|
|
143
|
+
return { type: event.type };
|
|
144
|
+
case "tool_execution_start":
|
|
145
|
+
return {
|
|
146
|
+
type: event.type,
|
|
147
|
+
toolCallId: event.toolCallId,
|
|
148
|
+
toolName: event.toolName,
|
|
149
|
+
signature: signature(event.toolName, event.args),
|
|
150
|
+
};
|
|
151
|
+
case "tool_execution_end":
|
|
152
|
+
return { type: event.type, toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError === true };
|
|
153
|
+
case "message_end": {
|
|
154
|
+
const message = event.message;
|
|
155
|
+
if (!message || message.role !== "assistant") return undefined;
|
|
156
|
+
// The text of a message can arrive as one string or as content blocks.
|
|
157
|
+
// Dropping the string form left lastText empty, which silently disabled
|
|
158
|
+
// the parent's idle-answer breaker for that child.
|
|
159
|
+
const content =
|
|
160
|
+
typeof message.content === "string"
|
|
161
|
+
? [{ type: "text", text: message.content.slice(-4000) }]
|
|
162
|
+
: Array.isArray(message.content)
|
|
163
|
+
? message.content
|
|
164
|
+
.filter((block) => block?.type === "text" && typeof block.text === "string")
|
|
165
|
+
.map((block) => ({ type: "text", text: block.text.slice(-4000) }))
|
|
166
|
+
: [];
|
|
167
|
+
return {
|
|
168
|
+
type: event.type,
|
|
169
|
+
message: {
|
|
170
|
+
role: "assistant",
|
|
171
|
+
content,
|
|
172
|
+
usage: message.usage,
|
|
173
|
+
errorMessage: typeof message.errorMessage === "string" ? message.errorMessage.slice(-2000) : undefined,
|
|
174
|
+
stopReason: message.stopReason,
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
case "compaction_end":
|
|
179
|
+
return {
|
|
180
|
+
type: event.type,
|
|
181
|
+
result: event.result ? { usage: event.result.usage } : undefined,
|
|
182
|
+
errorMessage: typeof event.errorMessage === "string" ? event.errorMessage.slice(-2000) : undefined,
|
|
183
|
+
};
|
|
184
|
+
case "auto_retry_end":
|
|
185
|
+
return { type: event.type, success: event.success, finalError: typeof event.finalError === "string" ? event.finalError.slice(-2000) : undefined };
|
|
186
|
+
case "extension_error":
|
|
187
|
+
return { type: event.type, error: typeof event.error === "string" ? event.error.slice(-2000) : undefined };
|
|
188
|
+
default:
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Decode with a stateful decoder: a pipe chunk can split a multi-byte UTF-8
|
|
194
|
+
// character in half, and chunk.toString() would turn both halves into U+FFFD.
|
|
195
|
+
// That corrupts lastText and the call signature used for repetition detection.
|
|
196
|
+
const controlDecoder = new StringDecoder("utf8");
|
|
197
|
+
let controlBuffer = "";
|
|
198
|
+
|
|
199
|
+
function parseControlLine(line) {
|
|
200
|
+
if (!line.trim()) return;
|
|
201
|
+
try {
|
|
202
|
+
const compact = controlEvent(JSON.parse(line));
|
|
203
|
+
if (compact) control.write(JSON.stringify(compact) + "\n");
|
|
204
|
+
} catch {
|
|
205
|
+
// A torn or non-JSON raw line is payload, not a control failure.
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function observeControl(chunk) {
|
|
210
|
+
controlBuffer += typeof chunk === "string" ? chunk : controlDecoder.write(chunk);
|
|
211
|
+
const lines = controlBuffer.split("\n");
|
|
212
|
+
controlBuffer = lines.pop() ?? "";
|
|
213
|
+
if (controlBuffer.length > 4 * 1024 * 1024) controlBuffer = "";
|
|
214
|
+
for (const line of lines) parseControlLine(line);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Emit whatever the child wrote without a final newline before the file closes. */
|
|
218
|
+
function flushControl() {
|
|
219
|
+
const rest = controlBuffer + controlDecoder.end();
|
|
220
|
+
controlBuffer = "";
|
|
221
|
+
parseControlLine(rest);
|
|
222
|
+
}
|
|
118
223
|
|
|
119
224
|
const logged = { stdout: 0, stderr: 0 };
|
|
120
225
|
|
|
@@ -153,7 +258,10 @@ try {
|
|
|
153
258
|
state.childPid = child.pid ?? null;
|
|
154
259
|
sealState({});
|
|
155
260
|
|
|
156
|
-
child.stdout.on("data", (chunk) =>
|
|
261
|
+
child.stdout.on("data", (chunk) => {
|
|
262
|
+
append("stdout", chunk);
|
|
263
|
+
observeControl(chunk);
|
|
264
|
+
});
|
|
157
265
|
child.stderr.on("data", (chunk) => append("stderr", chunk));
|
|
158
266
|
|
|
159
267
|
let settled = false;
|
|
@@ -208,7 +316,8 @@ const outcome = await new Promise((resolve) => {
|
|
|
208
316
|
settled = true;
|
|
209
317
|
if (killTimer) clearTimeout(killTimer);
|
|
210
318
|
if (owner) owner.destroy();
|
|
211
|
-
|
|
319
|
+
flushControl();
|
|
320
|
+
await Promise.all([closeStream(stdout), closeStream(stderr), closeStream(control)]);
|
|
212
321
|
sealState({
|
|
213
322
|
exit: {
|
|
214
323
|
exitCode: outcome.exitCode ?? null,
|
package/src/verify.ts
CHANGED
|
@@ -9,6 +9,14 @@
|
|
|
9
9
|
* The command runs in the parent, in the child's own working directory, with
|
|
10
10
|
* the parent's environment. Its exit status is the verdict; its output is kept
|
|
11
11
|
* as bounded context for the human and the model.
|
|
12
|
+
*
|
|
13
|
+
* The command is a shell command line, by contract: `pnpm test --filter x` is
|
|
14
|
+
* what a caller writes, and a pipeline or a redirect is a legitimate gate. It is
|
|
15
|
+
* therefore spawned through a shell, which is exactly as much authority as the
|
|
16
|
+
* caller already has: `verify` is chosen by the same agent that could run the
|
|
17
|
+
* same string with the `bash` tool. It is not an injection boundary, and the
|
|
18
|
+
* only defence that would matter here - refusing shell syntax - would break the
|
|
19
|
+
* feature it defends.
|
|
12
20
|
*/
|
|
13
21
|
|
|
14
22
|
import { spawn } from "node:child_process";
|
|
@@ -21,6 +29,8 @@ export interface VerifyRequest {
|
|
|
21
29
|
cwd: string;
|
|
22
30
|
timeoutMs?: number;
|
|
23
31
|
signal?: AbortSignal;
|
|
32
|
+
/** Explicit environment, normally filtered with the same policy as the child. */
|
|
33
|
+
env?: NodeJS.ProcessEnv;
|
|
24
34
|
}
|
|
25
35
|
|
|
26
36
|
function tail(text: string): string {
|
|
@@ -59,11 +69,16 @@ export function runVerification(request: VerifyRequest): Promise<VerificationRec
|
|
|
59
69
|
|
|
60
70
|
let child;
|
|
61
71
|
try {
|
|
72
|
+
// The shell is the contract, not an accident: see the module header. The
|
|
73
|
+
// command comes from the delegating agent, which already holds shell
|
|
74
|
+
// authority in this session, and `PI_DELEGATE_ENV_DROP` is what bounds
|
|
75
|
+
// what it can reach.
|
|
76
|
+
// nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true
|
|
62
77
|
child = spawn(request.command, [], {
|
|
63
78
|
cwd: request.cwd,
|
|
64
79
|
shell: true,
|
|
65
80
|
stdio: ["ignore", "pipe", "pipe"],
|
|
66
|
-
env: process.env,
|
|
81
|
+
env: request.env ?? process.env,
|
|
67
82
|
windowsHide: true,
|
|
68
83
|
});
|
|
69
84
|
} catch (error) {
|