pi-goal-delegate 0.1.0 → 0.2.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/CHANGELOG.md +58 -0
- package/README.md +74 -40
- package/package.json +1 -1
- package/skills/delegate/SKILL.md +12 -15
- package/src/command.ts +36 -5
- package/src/contract.ts +128 -11
- package/src/events.ts +22 -1
- package/src/index.ts +82 -10
- package/src/registry.ts +78 -22
- package/src/result-schema.ts +132 -0
- package/src/retention.ts +46 -9
- package/src/run.ts +73 -10
- package/src/spawn.ts +5 -1
- package/src/supervisor.mjs +113 -4
- package/src/verify.ts +3 -1
- package/src/worker.ts +128 -59
- package/src/worktree.ts +107 -3
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* result-schema.ts - the contract for a child's structured result.
|
|
3
|
+
*
|
|
4
|
+
* A `resultSchema` is enforced by the child at `delegate_complete`. Two failures
|
|
5
|
+
* are worth separating there, because they need different repairs:
|
|
6
|
+
*
|
|
7
|
+
* - the value does not satisfy the schema: the child rewrites the value;
|
|
8
|
+
* - the schema itself is unusable - a dangling `$ref`, a reference into a
|
|
9
|
+
* document this package cannot reach, a shape TypeBox cannot evaluate: no
|
|
10
|
+
* value can satisfy it. The child can never complete, and every
|
|
11
|
+
* retry spends budget on a dead end. That case is caught at admission, in the
|
|
12
|
+
* parent, where the caller can still fix the contract.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { Value } from "typebox/value";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A local JSON pointer inside the schema document, or undefined when it misses.
|
|
19
|
+
*
|
|
20
|
+
* The fragment of `#/a/b` is `/a/b`, not `a/b`: the leading slash is part of
|
|
21
|
+
* the pointer, and treating the fragment as the pointer resolves every ref to
|
|
22
|
+
* the empty top-level key.
|
|
23
|
+
*/
|
|
24
|
+
function pointer(schema: unknown, fragment: string): unknown {
|
|
25
|
+
if (fragment === "") return schema;
|
|
26
|
+
if (!fragment.startsWith("/")) return undefined;
|
|
27
|
+
let cursor: unknown = schema;
|
|
28
|
+
for (const token of fragment.slice(1).split("/")) {
|
|
29
|
+
let key: string;
|
|
30
|
+
try {
|
|
31
|
+
key = decodeURIComponent(token).replaceAll("~1", "/").replaceAll("~0", "~");
|
|
32
|
+
} catch {
|
|
33
|
+
// A malformed percent escape names no member of any document. It is an
|
|
34
|
+
// unresolved pointer, not a crash inside the caller's argument check.
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
if (typeof cursor !== "object" || cursor === null) return undefined;
|
|
38
|
+
// Own properties only. A plain index read resolves `#/toString` through the
|
|
39
|
+
// prototype chain, so the audit admitted a schema the validator rejects for
|
|
40
|
+
// every value - the exact trap this audit exists to refuse.
|
|
41
|
+
if (!Object.hasOwn(cursor, key)) return undefined;
|
|
42
|
+
cursor = (cursor as Record<string, unknown>)[key];
|
|
43
|
+
if (cursor === undefined) return undefined;
|
|
44
|
+
}
|
|
45
|
+
return cursor;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** `$ref` values this package cannot resolve, split by the reason. */
|
|
49
|
+
interface RefAudit {
|
|
50
|
+
/** Local pointers that name nothing in this document. */
|
|
51
|
+
dangling: string[];
|
|
52
|
+
/** References into another document, for which this package has no resolver. */
|
|
53
|
+
external: string[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function auditRefs(schema: unknown): RefAudit {
|
|
57
|
+
const dangling = new Set<string>();
|
|
58
|
+
const external = new Set<string>();
|
|
59
|
+
const visit = (node: unknown): void => {
|
|
60
|
+
if (Array.isArray(node)) {
|
|
61
|
+
for (const item of node) visit(item);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (typeof node !== "object" || node === null) return;
|
|
65
|
+
for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
|
|
66
|
+
if (key === "$ref" && typeof value === "string") {
|
|
67
|
+
if (!value.startsWith("#")) {
|
|
68
|
+
// `other.json#/t` and `https://.../t` name a document nothing here
|
|
69
|
+
// loads. TypeBox answers false for every value rather than throwing,
|
|
70
|
+
// so a sample could never expose it: the audit has to say the name.
|
|
71
|
+
external.add(value);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
// `#` is the whole document; `#name` is an anchor, not a pointer, and
|
|
75
|
+
// is left to the validator rather than judged here.
|
|
76
|
+
const fragment = value.slice(1);
|
|
77
|
+
if (fragment !== "" && fragment.startsWith("/") && pointer(schema, fragment) === undefined) dangling.add(value);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
visit(value);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
visit(schema);
|
|
84
|
+
return { dangling: [...dangling], external: [...external] };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Values every JSON document can be classified against, for a liveness probe. */
|
|
88
|
+
const SAMPLES: readonly unknown[] = [null, {}, [], "", 0, true];
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Why a schema cannot be used at all, or undefined when it is worth admitting.
|
|
92
|
+
*
|
|
93
|
+
* `Value.Check` answers false for a value that does not match, which is the
|
|
94
|
+
* right answer. A `$ref` that resolves nowhere makes it answer false for *every*
|
|
95
|
+
* value: TypeBox fails closed, and a completion contract that fails closed on
|
|
96
|
+
* purpose on nothing is a trap rather than a gate.
|
|
97
|
+
*/
|
|
98
|
+
export function auditResultSchema(schema: Record<string, unknown>): string | undefined {
|
|
99
|
+
const { dangling, external } = auditRefs(schema);
|
|
100
|
+
if (dangling.length > 0) {
|
|
101
|
+
return `resultSchema has an unresolved $ref (${dangling.slice(0, 3).join(", ")}), so no result could ever satisfy it.`;
|
|
102
|
+
}
|
|
103
|
+
if (external.length > 0) {
|
|
104
|
+
return `resultSchema has a $ref into another document (${external.slice(0, 3).join(", ")}), which cannot be resolved here, so no result could ever satisfy it.`;
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
for (const sample of SAMPLES) Value.Check(schema as never, sample);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
return `resultSchema cannot be evaluated: ${String(error).slice(0, 300)}`;
|
|
110
|
+
}
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* A bounded, actionable account of why a value failed its schema.
|
|
116
|
+
*
|
|
117
|
+
* "Does not satisfy the schema" is a dead end for a child that cannot see which
|
|
118
|
+
* field is wrong. The instance path and the reason are both in the validator's
|
|
119
|
+
* own error list, so the repair is one call away instead of a guess.
|
|
120
|
+
*/
|
|
121
|
+
export function describeSchemaErrors(schema: Record<string, unknown>, value: unknown, limit = 4): string {
|
|
122
|
+
let errors: Array<{ instancePath?: string; message?: string }>;
|
|
123
|
+
try {
|
|
124
|
+
errors = Value.Errors(schema as never, value) as unknown as Array<{ instancePath?: string; message?: string }>;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
return `The schema itself could not be evaluated: ${String(error).slice(0, 300)}`;
|
|
127
|
+
}
|
|
128
|
+
const lines = errors.slice(0, limit).map((error) => `${error.instancePath || "/"}: ${error.message ?? "invalid"}`);
|
|
129
|
+
if (lines.length === 0) return "The value does not satisfy the result schema.";
|
|
130
|
+
const more = errors.length > lines.length ? ` (and ${errors.length - lines.length} more)` : "";
|
|
131
|
+
return `${lines.join("; ")}${more}`;
|
|
132
|
+
}
|
package/src/retention.ts
CHANGED
|
@@ -24,6 +24,7 @@ import { existsSync, lstatSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
|
24
24
|
import { join, resolve } from "node:path";
|
|
25
25
|
import { identityAlive, type ProcessIdentity } from "./identity.ts";
|
|
26
26
|
import { delegateRoot, isRunId, readJson, value } from "./spawn.ts";
|
|
27
|
+
import { removeWorktree, type WorktreeRef } from "./worktree.ts";
|
|
27
28
|
|
|
28
29
|
const KEEP_ENV = "PI_DELEGATE_MAX_RUNS";
|
|
29
30
|
const AGE_ENV = "PI_DELEGATE_RETENTION_DAYS";
|
|
@@ -108,7 +109,7 @@ interface MetaShape {
|
|
|
108
109
|
}
|
|
109
110
|
|
|
110
111
|
interface OutcomeShape {
|
|
111
|
-
worktree?:
|
|
112
|
+
worktree?: WorktreeRef;
|
|
112
113
|
}
|
|
113
114
|
|
|
114
115
|
/** True when the directory is a run record this extension may consider. */
|
|
@@ -277,7 +278,10 @@ export function pruneRunRecords(options: PruneOptions = {}): PruneResult {
|
|
|
277
278
|
result.kept += 1;
|
|
278
279
|
continue;
|
|
279
280
|
}
|
|
280
|
-
releaseWorktree(root, candidate.dir)
|
|
281
|
+
if (!releaseWorktree(root, candidate.dir)) {
|
|
282
|
+
result.kept += 1;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
281
285
|
try {
|
|
282
286
|
rmSync(candidate.dir, { recursive: true, force: true });
|
|
283
287
|
result.removed.push(candidate.runId);
|
|
@@ -296,18 +300,51 @@ export function pruneRunRecords(options: PruneOptions = {}): PruneResult {
|
|
|
296
300
|
* other leaves an orphan directory that `git worktree list` reports forever. A
|
|
297
301
|
* path outside the record root is left alone: it is not ours to delete.
|
|
298
302
|
*/
|
|
299
|
-
function releaseWorktree(root: string, dir: string):
|
|
300
|
-
const
|
|
301
|
-
const path =
|
|
302
|
-
if (!path) return;
|
|
303
|
+
function releaseWorktree(root: string, dir: string): boolean {
|
|
304
|
+
const worktree = recordWorktree(dir);
|
|
305
|
+
const path = worktree?.path;
|
|
306
|
+
if (!path) return true;
|
|
303
307
|
const worktreeRoot = resolve(root, "worktrees");
|
|
304
308
|
const resolved = resolve(path);
|
|
305
|
-
if (!resolved.startsWith(worktreeRoot + "/") && resolved !== worktreeRoot) return;
|
|
309
|
+
if (!resolved.startsWith(worktreeRoot + "/") && resolved !== worktreeRoot) return true;
|
|
310
|
+
if (!existsSync(resolved)) return true;
|
|
311
|
+
if (worktreeReferencedElsewhere(root, resolved, dir)) return true;
|
|
312
|
+
if (!worktree.repo || !worktree.branch) return false;
|
|
313
|
+
// A dirty tree, a missing repository, or a git failure all preserve both the
|
|
314
|
+
// checkout and its record. The only removal path is git's own clean-tree check.
|
|
315
|
+
return removeWorktree(worktree);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* The checkout a record points at, from whichever file still has it.
|
|
320
|
+
*
|
|
321
|
+
* A run killed before it settled never wrote outcome.json, so spec.json is the
|
|
322
|
+
* only record of the checkout this process created. Reading outcome.json alone
|
|
323
|
+
* deleted that record and orphaned the checkout in `git worktree list` forever,
|
|
324
|
+
* taking the only pointer to any unmerged work with it.
|
|
325
|
+
*/
|
|
326
|
+
function recordWorktree(dir: string): WorktreeRef | undefined {
|
|
327
|
+
const outcome = value(readJson<OutcomeShape>(join(dir, "outcome.json")));
|
|
328
|
+
if (outcome?.worktree) return outcome.worktree;
|
|
329
|
+
const spec = value(readJson<{ worktree?: WorktreeRef }>(join(dir, "spec.json")));
|
|
330
|
+
return spec?.worktree;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function worktreeReferencedElsewhere(root: string, path: string, excludedDir: string): boolean {
|
|
334
|
+
let names: string[];
|
|
306
335
|
try {
|
|
307
|
-
|
|
336
|
+
names = readdirSync(root);
|
|
308
337
|
} catch {
|
|
309
|
-
|
|
338
|
+
return true;
|
|
339
|
+
}
|
|
340
|
+
for (const name of names) {
|
|
341
|
+
if (!isRunId(name)) continue;
|
|
342
|
+
const dir = join(root, name);
|
|
343
|
+
if (dir === excludedDir) continue;
|
|
344
|
+
const worktree = recordWorktree(dir);
|
|
345
|
+
if (worktree?.path && resolve(worktree.path) === path) return true;
|
|
310
346
|
}
|
|
347
|
+
return false;
|
|
311
348
|
}
|
|
312
349
|
|
|
313
350
|
/** Total bytes a record directory holds, for a caller that wants to report it. */
|
package/src/run.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
type BudgetLimits,
|
|
31
31
|
type BudgetVerdict,
|
|
32
32
|
type ContainmentVerdict,
|
|
33
|
+
type JsonValue,
|
|
33
34
|
type RunProgress,
|
|
34
35
|
type RunScope,
|
|
35
36
|
type RunSpec,
|
|
@@ -55,6 +56,7 @@ import {
|
|
|
55
56
|
} from "./identity.ts";
|
|
56
57
|
import {
|
|
57
58
|
buildChildCommand,
|
|
59
|
+
childEnvironment,
|
|
58
60
|
describeRead,
|
|
59
61
|
ensureRunDir,
|
|
60
62
|
isRunId,
|
|
@@ -72,7 +74,14 @@ import {
|
|
|
72
74
|
appendJsonLine,
|
|
73
75
|
} from "./spawn.ts";
|
|
74
76
|
import { runVerification } from "./verify.ts";
|
|
75
|
-
import {
|
|
77
|
+
import {
|
|
78
|
+
createWorktree,
|
|
79
|
+
exportWorktreeIntegration,
|
|
80
|
+
removeWorktree,
|
|
81
|
+
worktreeCleanupEnabled,
|
|
82
|
+
type WorktreeIntegration,
|
|
83
|
+
type WorktreeRef,
|
|
84
|
+
} from "./worktree.ts";
|
|
76
85
|
|
|
77
86
|
const TICK_MS = 250;
|
|
78
87
|
const INLINE_LIMIT_MS = 10_000;
|
|
@@ -87,6 +96,9 @@ export interface ChildResult {
|
|
|
87
96
|
evidence?: string;
|
|
88
97
|
/** What the parent must provide. Only a blocked verdict carries one. */
|
|
89
98
|
needs?: string;
|
|
99
|
+
result?: JsonValue;
|
|
100
|
+
/** The child's successful completion gate, before the parent's independent check. */
|
|
101
|
+
childVerification?: VerificationRecord;
|
|
90
102
|
turns?: number;
|
|
91
103
|
maxTurns?: number;
|
|
92
104
|
toolCalls?: number;
|
|
@@ -169,6 +181,12 @@ export interface RunOutcome {
|
|
|
169
181
|
evidence?: string;
|
|
170
182
|
/** What the child needs in order to continue. Set only for a blocked run. */
|
|
171
183
|
needs?: string;
|
|
184
|
+
/** Structured JSON returned to the parent or a codemode orchestrator. */
|
|
185
|
+
result?: JsonValue;
|
|
186
|
+
/** The successful child-side gate; `verification` below is the parent's recheck. */
|
|
187
|
+
childVerification?: VerificationRecord;
|
|
188
|
+
/** Previous run whose session and worktree this run continues. */
|
|
189
|
+
resumedFrom?: string;
|
|
172
190
|
/**
|
|
173
191
|
* What the parent proved about the completion claim.
|
|
174
192
|
*
|
|
@@ -190,6 +208,8 @@ export interface RunOutcome {
|
|
|
190
208
|
logCapReached?: boolean;
|
|
191
209
|
settledInline?: boolean;
|
|
192
210
|
worktree?: WorktreeRef;
|
|
211
|
+
/** Diff, patch, and apply-check for integrating an isolated checkout. */
|
|
212
|
+
integration?: WorktreeIntegration;
|
|
193
213
|
error?: string;
|
|
194
214
|
}
|
|
195
215
|
|
|
@@ -200,6 +220,12 @@ export interface StartRequest {
|
|
|
200
220
|
maxTurns: number;
|
|
201
221
|
timeoutMinutes: number;
|
|
202
222
|
maxCostUsd?: number;
|
|
223
|
+
resultSchema?: Record<string, unknown>;
|
|
224
|
+
/** Absolute position and maximum for this delegation tree. */
|
|
225
|
+
depth?: number;
|
|
226
|
+
maxDepth?: number;
|
|
227
|
+
/** A parent run's deadline, which a nested run may not exceed. */
|
|
228
|
+
parentDeadline?: number;
|
|
203
229
|
model?: string;
|
|
204
230
|
modelSource: RunSpec["modelSource"];
|
|
205
231
|
thinking: string;
|
|
@@ -254,7 +280,7 @@ export interface RunHandle {
|
|
|
254
280
|
cancel: (reason?: KillReason, graceMs?: number) => Promise<RunOutcome>;
|
|
255
281
|
}
|
|
256
282
|
|
|
257
|
-
type KillReason = "abort" | "timeout" | "limit";
|
|
283
|
+
type KillReason = "abort" | "timeout" | "limit" | "no_progress";
|
|
258
284
|
|
|
259
285
|
function newRunId(): string {
|
|
260
286
|
return `dl_${Date.now().toString(36)}_${randomBytes(4).toString("hex")}`;
|
|
@@ -298,6 +324,7 @@ function statusFrom(killReason: Runtime["killReason"], result: ChildResult | und
|
|
|
298
324
|
if (killReason === "timeout") return "timeout";
|
|
299
325
|
if (killReason === "limit") return "limit";
|
|
300
326
|
if (killReason === "abort") return "aborted";
|
|
327
|
+
if (killReason === "no_progress") return "no_progress";
|
|
301
328
|
if (result?.status && result.status !== "stopped" && isTerminal(result.status as RunStatus)) {
|
|
302
329
|
return result.status as RunStatus;
|
|
303
330
|
}
|
|
@@ -408,6 +435,9 @@ async function seal(runtime: Runtime, handle: RunHandle): Promise<RunOutcome> {
|
|
|
408
435
|
|
|
409
436
|
const { verified, verification } = await verifyClaim(runtime, status, result);
|
|
410
437
|
status = verifiedStatus(status, verified);
|
|
438
|
+
const integration = runtime.spec.worktree
|
|
439
|
+
? exportWorktreeIntegration(runtime.spec.worktree, runtime.paths.dir)
|
|
440
|
+
: undefined;
|
|
411
441
|
|
|
412
442
|
const outcome: RunOutcome = {
|
|
413
443
|
version: 1,
|
|
@@ -422,6 +452,9 @@ async function seal(runtime: Runtime, handle: RunHandle): Promise<RunOutcome> {
|
|
|
422
452
|
summary: runtime.killDetail ?? summarize(result, handle.progress, exit),
|
|
423
453
|
evidence: result?.evidence?.trim() || undefined,
|
|
424
454
|
needs: result?.needs?.trim() || undefined,
|
|
455
|
+
result: result?.result,
|
|
456
|
+
childVerification: result?.childVerification,
|
|
457
|
+
resumedFrom: runtime.spec.resumedFrom,
|
|
425
458
|
verified,
|
|
426
459
|
verification,
|
|
427
460
|
sessionFile: result?.sessionFile,
|
|
@@ -435,6 +468,7 @@ async function seal(runtime: Runtime, handle: RunHandle): Promise<RunOutcome> {
|
|
|
435
468
|
leakedPids: runtime.leakedPids,
|
|
436
469
|
logCapReached: state.kind === "ok" && (state.value.capped?.length ?? 0) > 0,
|
|
437
470
|
worktree: runtime.spec.worktree,
|
|
471
|
+
integration,
|
|
438
472
|
error: result?.error ?? exit?.error,
|
|
439
473
|
};
|
|
440
474
|
writeJsonAtomic(runtime.paths.outcome, outcome);
|
|
@@ -477,6 +511,7 @@ async function verifyClaim(
|
|
|
477
511
|
command: runtime.spec.verify.command,
|
|
478
512
|
cwd: runtime.spec.cwd,
|
|
479
513
|
timeoutMs: Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_VERIFY_TIMEOUT_MS,
|
|
514
|
+
env: childEnvironment({}),
|
|
480
515
|
});
|
|
481
516
|
// A timed-out or unspawnable command is not a pass. `exitCode === 0` is.
|
|
482
517
|
const passed = !verification.timedOut && verification.exitCode === 0;
|
|
@@ -588,7 +623,10 @@ function buildSpec(runId: string, request: StartRequest, cwd: string): RunSpec {
|
|
|
588
623
|
context: request.context,
|
|
589
624
|
maxTurns: request.maxTurns,
|
|
590
625
|
timeoutMinutes: request.timeoutMinutes,
|
|
591
|
-
deadline:
|
|
626
|
+
deadline: Math.min(
|
|
627
|
+
Date.now() + request.timeoutMinutes * 60_000,
|
|
628
|
+
request.parentDeadline ?? Number.POSITIVE_INFINITY,
|
|
629
|
+
),
|
|
592
630
|
resultPath: paths.result,
|
|
593
631
|
inboxPath: paths.inbox,
|
|
594
632
|
model: request.model,
|
|
@@ -599,8 +637,12 @@ function buildSpec(runId: string, request: StartRequest, cwd: string): RunSpec {
|
|
|
599
637
|
scope: request.scope,
|
|
600
638
|
sessionId: request.sessionId,
|
|
601
639
|
isolated: request.isolated,
|
|
640
|
+
resultSchema: request.resultSchema,
|
|
641
|
+
depth: request.depth ?? 0,
|
|
642
|
+
maxDepth: request.maxDepth ?? 0,
|
|
602
643
|
verify: request.verify,
|
|
603
644
|
resumeSession: request.resumeFrom,
|
|
645
|
+
resumedFrom: request.resumeFrom,
|
|
604
646
|
maxCostUsd: Math.max(0, request.maxCostUsd ?? DEFAULT_MAX_COST_USD),
|
|
605
647
|
createdAt: Date.now(),
|
|
606
648
|
};
|
|
@@ -613,10 +655,10 @@ function buildSpec(runId: string, request: StartRequest, cwd: string): RunSpec {
|
|
|
613
655
|
* file another process appends to. Reading it incrementally is what turns a
|
|
614
656
|
* durable log into a live turn count, a live cost, and a runaway net.
|
|
615
657
|
*/
|
|
616
|
-
function watch(runtime: Runtime, handle: RunHandle, startOffset: number): void {
|
|
658
|
+
function watch(runtime: Runtime, handle: RunHandle, startOffset: number, sourcePath: string): void {
|
|
617
659
|
const { paths } = runtime;
|
|
618
660
|
const progress = handle.progress;
|
|
619
|
-
const tailer = new LiveTail(
|
|
661
|
+
const tailer = new LiveTail(sourcePath, progress, readRange, startOffset);
|
|
620
662
|
runtime.tailer = tailer;
|
|
621
663
|
// One poll at a time. A large log, or the fence that follows a dead
|
|
622
664
|
// supervisor, can outlast the tick; two overlapping polls would read the same
|
|
@@ -644,6 +686,11 @@ function watch(runtime: Runtime, handle: RunHandle, startOffset: number): void {
|
|
|
644
686
|
handle.status = live;
|
|
645
687
|
runtime.onProgress?.(progress, live);
|
|
646
688
|
}
|
|
689
|
+
if (progress.noProgressReason && !runtime.killReason) {
|
|
690
|
+
runtime.killDetail = progress.noProgressReason;
|
|
691
|
+
await cancelRun(runtime, handle, "no_progress");
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
647
694
|
// The parent's share of the budget: the same limits the child
|
|
648
695
|
// enforces, plus a grace, so this is a runaway net rather than a
|
|
649
696
|
// second, tighter budget.
|
|
@@ -699,10 +746,14 @@ export async function startRun(request: StartRequest): Promise<RunHandle> {
|
|
|
699
746
|
// a silent fall back to the shared tree.
|
|
700
747
|
let worktree: WorktreeRef | undefined;
|
|
701
748
|
if (request.worktree) worktree = createWorktree(runId, request.cwd);
|
|
749
|
+
const resumeSession = resolveResume(request.resumeFrom);
|
|
750
|
+
if (!request.worktree && request.resumeFrom && isRunId(request.resumeFrom)) {
|
|
751
|
+
const previous = readSpecFile(request.resumeFrom);
|
|
752
|
+
if (previous?.worktree && existsSync(previous.worktree.path)) worktree = previous.worktree;
|
|
753
|
+
}
|
|
702
754
|
const cwd = worktree?.path ?? request.cwd;
|
|
703
755
|
const paths = runPaths(runId);
|
|
704
756
|
ensureRunDir(paths);
|
|
705
|
-
const resumeSession = resolveResume(request.resumeFrom);
|
|
706
757
|
const tools = mergeTools(request.tools, request.parentActiveTools ?? []);
|
|
707
758
|
const draft = buildSpec(runId, request, cwd);
|
|
708
759
|
const child = buildChildCommand({
|
|
@@ -837,7 +888,7 @@ export async function startRun(request: StartRequest): Promise<RunHandle> {
|
|
|
837
888
|
writeJsonAtomic(paths.meta, meta);
|
|
838
889
|
handle.status = "running";
|
|
839
890
|
|
|
840
|
-
watch(runtime, handle, 0);
|
|
891
|
+
watch(runtime, handle, 0, paths.control);
|
|
841
892
|
request.onAdmitted?.(handle);
|
|
842
893
|
|
|
843
894
|
// The window is a deadline, not a timer that outlives it: when the run
|
|
@@ -909,9 +960,20 @@ export function formatOutcome(outcome: RunOutcome): string {
|
|
|
909
960
|
// A blocked run has no evidence and no result: it has a request. Printing that
|
|
910
961
|
// request under "Evidence:" told the parent the opposite of what it was.
|
|
911
962
|
if (outcome.needs) lines.push("", `Needs: ${outcome.needs}`);
|
|
963
|
+
if (outcome.result !== undefined) lines.push("", `Result: ${JSON.stringify(outcome.result)}`);
|
|
912
964
|
lines.push("", verificationLine(outcome));
|
|
913
965
|
if (outcome.sessionFile) lines.push(`Child session: ${outcome.sessionFile}`);
|
|
914
966
|
if (outcome.worktree) lines.push(`Worktree: ${outcome.worktree.path} (branch ${outcome.worktree.branch})`);
|
|
967
|
+
if (outcome.integration) {
|
|
968
|
+
if (outcome.integration.diffStat) lines.push("", "Diff stat:", outcome.integration.diffStat);
|
|
969
|
+
if (outcome.integration.status) lines.push("", "Worktree status:", outcome.integration.status);
|
|
970
|
+
if (outcome.integration.patchPath) {
|
|
971
|
+
lines.push(`Patch: ${outcome.integration.patchPath}`);
|
|
972
|
+
lines.push(`Apply check: ${outcome.integration.applyCheck?.ok ? "passed" : "failed"}`);
|
|
973
|
+
if (outcome.integration.applyCommand) lines.push(`Apply with: ${outcome.integration.applyCommand}`);
|
|
974
|
+
}
|
|
975
|
+
if (outcome.integration.error) lines.push(`Worktree integration error: ${outcome.integration.error}`);
|
|
976
|
+
}
|
|
915
977
|
if (outcome.containmentVerdict) lines.push(`Containment: ${containmentLine(outcome)}`);
|
|
916
978
|
if (outcome.leakedPids?.length) lines.push(`WARNING: descendants survived cancellation: ${outcome.leakedPids.join(", ")}`);
|
|
917
979
|
lines.push(`Run record: ${outcome.runDir}`);
|
|
@@ -953,9 +1015,10 @@ export async function progressOf(paths: RunPaths): Promise<{ progress: RunProgre
|
|
|
953
1015
|
const progress = emptyProgress();
|
|
954
1016
|
let bytes = 0;
|
|
955
1017
|
try {
|
|
956
|
-
const
|
|
1018
|
+
const source = existsSync(paths.control) ? paths.control : paths.events;
|
|
1019
|
+
const size = (await stat(source)).size;
|
|
957
1020
|
if (size <= 0) return { progress, bytes };
|
|
958
|
-
const buffer = await readRange(
|
|
1021
|
+
const buffer = await readRange(source, 0, size);
|
|
959
1022
|
foldText(buffer.toString("utf8"), progress);
|
|
960
1023
|
bytes = buffer.length;
|
|
961
1024
|
} catch {
|
|
@@ -1038,7 +1101,7 @@ export async function attachRun(
|
|
|
1038
1101
|
return { kind: "sealed", handle };
|
|
1039
1102
|
}
|
|
1040
1103
|
if (alive) {
|
|
1041
|
-
watch(runtime, handle, bytes);
|
|
1104
|
+
watch(runtime, handle, bytes, existsSync(paths.control) ? paths.control : paths.events);
|
|
1042
1105
|
return { kind: "attached", handle };
|
|
1043
1106
|
}
|
|
1044
1107
|
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,
|
|
@@ -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
|
@@ -21,6 +21,8 @@ export interface VerifyRequest {
|
|
|
21
21
|
cwd: string;
|
|
22
22
|
timeoutMs?: number;
|
|
23
23
|
signal?: AbortSignal;
|
|
24
|
+
/** Explicit environment, normally filtered with the same policy as the child. */
|
|
25
|
+
env?: NodeJS.ProcessEnv;
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
function tail(text: string): string {
|
|
@@ -63,7 +65,7 @@ export function runVerification(request: VerifyRequest): Promise<VerificationRec
|
|
|
63
65
|
cwd: request.cwd,
|
|
64
66
|
shell: true,
|
|
65
67
|
stdio: ["ignore", "pipe", "pipe"],
|
|
66
|
-
env: process.env,
|
|
68
|
+
env: request.env ?? process.env,
|
|
67
69
|
windowsHide: true,
|
|
68
70
|
});
|
|
69
71
|
} catch (error) {
|