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/contract.ts
CHANGED
|
@@ -23,6 +23,54 @@ export const MAX_MAX_TURNS = 500;
|
|
|
23
23
|
export const DEFAULT_TIMEOUT_MINUTES = 60;
|
|
24
24
|
export const MAX_TIMEOUT_MINUTES = 240;
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* The ceiling on a tool-call wait: the ceiling on a delegation itself.
|
|
28
|
+
*
|
|
29
|
+
* A wait that outlives the run it waits for is a wait that cannot report a
|
|
30
|
+
* result, so the two limits are the same number. `codemode` scripts accept
|
|
31
|
+
* `timeout_ms` up to 2^31-1, so nothing above this module had to cap it.
|
|
32
|
+
*/
|
|
33
|
+
export const MAX_WAIT_MS = MAX_TIMEOUT_MINUTES * 60_000;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Delegation depth is the number of further child levels a run tree may create.
|
|
37
|
+
* Zero preserves the original one-level default. An explicit cap enables task
|
|
38
|
+
* decomposition without replacing budget control with unbounded recursion.
|
|
39
|
+
*/
|
|
40
|
+
export const DEFAULT_MAX_DEPTH = 0;
|
|
41
|
+
export const MAX_MAX_DEPTH = 3;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Why a nested run may not set these limits, or undefined when it may.
|
|
45
|
+
*
|
|
46
|
+
* A child inherits the depth and spend budget of the run that started it.
|
|
47
|
+
* Raising one is indistinguishable from removing the bound its parent set, so
|
|
48
|
+
* the rule is one function rather than a copy in each entry point: two copies of
|
|
49
|
+
* "how much of its budget may a child spend" are two answers to one question.
|
|
50
|
+
*/
|
|
51
|
+
export function attenuationRefusal(
|
|
52
|
+
parent: { depth?: number; maxDepth?: number; maxCostUsd?: number },
|
|
53
|
+
request: { maxDepth: number; maxCostUsd: number },
|
|
54
|
+
): string | undefined {
|
|
55
|
+
// A run that no delegation started has no parent budget to honour.
|
|
56
|
+
if (parent.depth === undefined) return undefined;
|
|
57
|
+
const allowedDepth = parent.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
58
|
+
if (request.maxDepth > allowedDepth) {
|
|
59
|
+
return `maxDepth must be at most ${allowedDepth} in this delegation.`;
|
|
60
|
+
}
|
|
61
|
+
const allowedCost = parent.maxCostUsd ?? 0;
|
|
62
|
+
if (allowedCost > 0 && (request.maxCostUsd <= 0 || request.maxCostUsd > allowedCost)) {
|
|
63
|
+
return `maxCostUsd must be greater than 0 and at most ${allowedCost} in this delegation.`;
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** One completion message should normally contain the whole verdict. */
|
|
69
|
+
export const COMPLETION_MESSAGE_LIMIT = 24_000;
|
|
70
|
+
/** A structured result must remain a bounded, model- and codemode-readable value. */
|
|
71
|
+
export const MAX_STRUCTURED_RESULT_CHARS = 64_000;
|
|
72
|
+
export const DEFAULT_VERIFY_TIMEOUT_MS = 120_000;
|
|
73
|
+
|
|
26
74
|
/**
|
|
27
75
|
* How many delegations one session may keep live at once.
|
|
28
76
|
*
|
|
@@ -131,6 +179,9 @@ export type ContainmentVerdict = "gone" | "leaked" | "unproven";
|
|
|
131
179
|
/** What a verify command proved about a completion claim. */
|
|
132
180
|
export type VerificationVerdict = true | false | "not-run";
|
|
133
181
|
|
|
182
|
+
/** JSON data crosses the child/parent protocol; functions and class instances do not. */
|
|
183
|
+
export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
|
|
184
|
+
|
|
134
185
|
/** The recorded result of running a run's verify command in the parent. */
|
|
135
186
|
export interface VerificationRecord {
|
|
136
187
|
command: string;
|
|
@@ -178,14 +229,24 @@ export interface RunSpec {
|
|
|
178
229
|
/** The child ran without ambient extensions, skills, MCP servers or context files. */
|
|
179
230
|
isolated?: boolean;
|
|
180
231
|
/**
|
|
181
|
-
* A command
|
|
182
|
-
*
|
|
232
|
+
* A command that gates the child's completion claim and is then independently
|
|
233
|
+
* re-run by the parent. A failed child-side check returns to the child as a
|
|
234
|
+
* tool result; it does not terminate the run. The parent uses the same
|
|
235
|
+
* PI_DELEGATE_ENV_DROP policy as the child.
|
|
183
236
|
*/
|
|
184
237
|
verify?: { command: string };
|
|
238
|
+
/** Optional JSON Schema for the structured value passed to delegate_complete. */
|
|
239
|
+
resultSchema?: Record<string, unknown>;
|
|
240
|
+
/** Zero-based position in the delegation tree. */
|
|
241
|
+
depth?: number;
|
|
242
|
+
/** Maximum absolute depth for this run tree; zero disables nested delegation. */
|
|
243
|
+
maxDepth?: number;
|
|
185
244
|
/** Session to continue instead of starting from the goal alone. */
|
|
186
245
|
resumeSession?: string;
|
|
246
|
+
/** The previous run whose session and, when present, worktree this run continues. */
|
|
247
|
+
resumedFrom?: string;
|
|
187
248
|
/** The child's workspace, when it was created as a git worktree. */
|
|
188
|
-
worktree?: { path: string; branch: string; repo: string };
|
|
249
|
+
worktree?: { path: string; branch: string; repo: string; base?: string };
|
|
189
250
|
/** Cumulative spend cap in USD. 0 disables it. */
|
|
190
251
|
maxCostUsd: number;
|
|
191
252
|
/**
|
|
@@ -297,6 +358,10 @@ export interface RunProgress {
|
|
|
297
358
|
/** Tail of the last assistant text, bounded. */
|
|
298
359
|
lastText: string;
|
|
299
360
|
lastError?: string;
|
|
361
|
+
/** Parent-side copy of the shared circuit-breaker state. */
|
|
362
|
+
breaker: BreakerState;
|
|
363
|
+
toolCallsThisTurn: number;
|
|
364
|
+
noProgressReason?: string;
|
|
300
365
|
/** The child's session header was seen. */
|
|
301
366
|
started: boolean;
|
|
302
367
|
/** The child reached its idle boundary at least once. */
|
|
@@ -311,6 +376,8 @@ export function emptyProgress(): RunProgress {
|
|
|
311
376
|
toolErrors: 0,
|
|
312
377
|
usage: emptyUsage(),
|
|
313
378
|
lastText: "",
|
|
379
|
+
breaker: emptyBreaker(),
|
|
380
|
+
toolCallsThisTurn: 0,
|
|
314
381
|
started: false,
|
|
315
382
|
settledOnce: false,
|
|
316
383
|
};
|
|
@@ -397,6 +464,39 @@ export type BreakerVerdict =
|
|
|
397
464
|
| { kind: "warn"; reason: string }
|
|
398
465
|
| { kind: "stop"; status: RunStatus; reason: string };
|
|
399
466
|
|
|
467
|
+
type Canonical = string | number | boolean | null | Canonical[] | { [key: string]: Canonical };
|
|
468
|
+
|
|
469
|
+
/** Canonical tool-call identity shared by the child and the parent's event observer. */
|
|
470
|
+
export function canonicalCallSignature(toolName: unknown, input: unknown): string {
|
|
471
|
+
const seen = new WeakSet<object>();
|
|
472
|
+
const walk = (value: unknown): Canonical => {
|
|
473
|
+
if (value === null || value === undefined) return null;
|
|
474
|
+
if (Array.isArray(value)) return value.map(walk);
|
|
475
|
+
switch (typeof value) {
|
|
476
|
+
case "string":
|
|
477
|
+
case "boolean":
|
|
478
|
+
return value;
|
|
479
|
+
case "number":
|
|
480
|
+
return Number.isFinite(value) ? value : String(value);
|
|
481
|
+
case "object": {
|
|
482
|
+
if (seen.has(value)) return "[circular]";
|
|
483
|
+
seen.add(value);
|
|
484
|
+
const source = value as Record<string, unknown>;
|
|
485
|
+
const sorted: Record<string, Canonical> = {};
|
|
486
|
+
for (const key of Object.keys(source).sort()) sorted[key] = walk(source[key]);
|
|
487
|
+
return sorted;
|
|
488
|
+
}
|
|
489
|
+
default:
|
|
490
|
+
return String(value);
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
try {
|
|
494
|
+
return `${String(toolName ?? "?")}:${JSON.stringify(walk(input ?? {}))}`;
|
|
495
|
+
} catch {
|
|
496
|
+
return `${String(toolName ?? "?")}:unserialisable`;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
400
500
|
/** Fold one tool result. A success clears the error streak. */
|
|
401
501
|
export function noteToolResult(state: BreakerState, failed: boolean): BreakerVerdict {
|
|
402
502
|
state.consecutiveErrors = failed ? state.consecutiveErrors + 1 : 0;
|
|
@@ -455,6 +555,13 @@ export function noteIdleTurn(state: BreakerState, text: string, toolCallsThisTur
|
|
|
455
555
|
};
|
|
456
556
|
}
|
|
457
557
|
|
|
558
|
+
/** Minutes a run really has: its own cap, or the parent's deadline if nearer. */
|
|
559
|
+
function budgetMinutes(spec: RunSpec): number {
|
|
560
|
+
if (!Number.isFinite(spec.deadline)) return spec.timeoutMinutes;
|
|
561
|
+
const remaining = Math.ceil((spec.deadline - Date.now()) / 60_000);
|
|
562
|
+
return Math.max(1, Math.min(spec.timeoutMinutes, remaining));
|
|
563
|
+
}
|
|
564
|
+
|
|
458
565
|
export function buildGoalPrompt(spec: RunSpec): string {
|
|
459
566
|
const doneWhen = spec.doneWhen?.trim() || "You decide the concrete completion criteria, state them, then meet them.";
|
|
460
567
|
const context = spec.context?.trim() || "(none provided; discover what you need from the repository and the environment)";
|
|
@@ -470,19 +577,31 @@ export function buildGoalPrompt(spec: RunSpec): string {
|
|
|
470
577
|
"",
|
|
471
578
|
"## How this session works",
|
|
472
579
|
"You are a delegated sub-agent working alone on this goal. The user is not present and cannot answer questions.",
|
|
473
|
-
"- Keep working until the goal is verifiably done, then call delegate_complete
|
|
580
|
+
"- Keep working until the goal is verifiably done, then call delegate_complete with summary, evidence, and any requested structured result.",
|
|
474
581
|
"- Evidence means the commands you ran, the files you changed, and the checks that pass. Without evidence the delegation is only a claim.",
|
|
475
582
|
"- Call delegate_blocked(reason, needs) when you cannot proceed without a decision, credential, or fact you cannot obtain.",
|
|
476
583
|
"- If an automatic continuation arrives, do not restate progress: continue the work.",
|
|
477
584
|
"- Keep changes scoped to the goal. Do not start unrelated work.",
|
|
478
585
|
"- Do not ask questions. Either make a defensible decision and note it, or call delegate_blocked.",
|
|
479
|
-
|
|
586
|
+
// A nested run inherits its parent's deadline, so timeoutMinutes is what
|
|
587
|
+
// the parent asked for, not what this child actually has left. Telling a
|
|
588
|
+
// child it has an hour when it has two minutes spends the budget on a
|
|
589
|
+
// plan it cannot finish.
|
|
590
|
+
`- Budget: at most ${spec.maxTurns} model turns and ${budgetMinutes(spec)} minutes.`,
|
|
480
591
|
...(spec.verify
|
|
481
592
|
? [
|
|
482
|
-
`-
|
|
593
|
+
`- Completion is gated by: \`${spec.verify.command}\` in this directory. delegate_complete runs it before ending. If it fails, fix the cause and retry; the parent independently re-runs it after your final claim.`,
|
|
483
594
|
]
|
|
484
595
|
: []),
|
|
485
|
-
|
|
596
|
+
...(spec.resultSchema
|
|
597
|
+
? [
|
|
598
|
+
"- delegate_complete requires a structured `result` value satisfying this JSON Schema:",
|
|
599
|
+
"```json",
|
|
600
|
+
JSON.stringify(spec.resultSchema),
|
|
601
|
+
"```",
|
|
602
|
+
]
|
|
603
|
+
: []),
|
|
604
|
+
"(A steering message from the parent is delivered between turns. Treat it as direction for the work, not as a new goal.)",
|
|
486
605
|
].join("\n");
|
|
487
606
|
}
|
|
488
607
|
|
|
@@ -493,12 +612,19 @@ export function buildGoalPrompt(spec: RunSpec): string {
|
|
|
493
612
|
* only party that knows the goal changed, and a child that keeps working on last
|
|
494
613
|
* turn's instructions wastes the budget it was given.
|
|
495
614
|
*/
|
|
615
|
+
export function buildSteeringMessage(steering: readonly string[]): string {
|
|
616
|
+
return [
|
|
617
|
+
"# Message from the delegating agent",
|
|
618
|
+
...steering.map((entry) => `- ${entry}`),
|
|
619
|
+
"",
|
|
620
|
+
"Treat this as direction for the work you are already doing. It does not replace the goal.",
|
|
621
|
+
].join("\n");
|
|
622
|
+
}
|
|
623
|
+
|
|
496
624
|
export function buildContinuation(spec: RunSpec, turn: number, steering: readonly string[] = []): string {
|
|
497
625
|
const doneWhen = spec.doneWhen?.trim() || "the stated completion criteria are met";
|
|
498
626
|
return [
|
|
499
|
-
...(steering.length > 0
|
|
500
|
-
? ["# Message from the delegating agent", ...steering.map((entry) => `- ${entry}`), "", "Treat this as direction for the work you are already doing. It does not replace the goal.", ""]
|
|
501
|
-
: []),
|
|
627
|
+
...(steering.length > 0 ? [buildSteeringMessage(steering), ""] : []),
|
|
502
628
|
`Continue working toward the goal. Turn ${turn} of at most ${spec.maxTurns}.`,
|
|
503
629
|
"",
|
|
504
630
|
"# Goal",
|
|
@@ -507,6 +633,6 @@ export function buildContinuation(spec: RunSpec, turn: number, steering: readonl
|
|
|
507
633
|
"# Done when",
|
|
508
634
|
doneWhen,
|
|
509
635
|
"",
|
|
510
|
-
"Rules: keep working until the goal is verifiably done, then call delegate_complete
|
|
636
|
+
"Rules: keep working until the goal is verifiably done, then call delegate_complete with summary, evidence, and any requested structured result. If you are blocked, call delegate_blocked(reason, needs). Do not ask questions.",
|
|
511
637
|
].join("\n");
|
|
512
638
|
}
|
package/src/doctor.ts
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doctor.ts - the installation and health self-check.
|
|
3
|
+
*
|
|
4
|
+
* Three failures motivated this module, and all three were silent:
|
|
5
|
+
*
|
|
6
|
+
* 1. The extension was installed through a symlink whose target moved. Pi
|
|
7
|
+
* dropped the extension, no tool existed, and nothing said so for six days.
|
|
8
|
+
* 2. The run-record root became unwritable. A start would fail, but only when
|
|
9
|
+
* somebody tried one, and the message was about a path rather than a cause.
|
|
10
|
+
* 3. Records were removed by retention, which is observable only after the fact:
|
|
11
|
+
* a run was "gone" and nobody knew whether it had ever existed.
|
|
12
|
+
*
|
|
13
|
+
* Every check answers one question with `ok`, `warn` or `fail`. A `fail` is an
|
|
14
|
+
* installation that will not work; a `warn` is a working installation with
|
|
15
|
+
* something to know. The same checks run at `session_start` for the one failure
|
|
16
|
+
* that has to be announced before it costs anything.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { randomUUID } from "node:crypto";
|
|
20
|
+
import { closeSync, existsSync, lstatSync, openSync, readFileSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
21
|
+
import { dirname, join, resolve } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { formatDuration, isTerminal, MAX_MAX_LIVE, MAX_TIMEOUT_MINUTES, SPEC_ENV } from "./contract.ts";
|
|
24
|
+
import { observability, supportsFence } from "./identity.ts";
|
|
25
|
+
import { maxCostUsd, maxLive, type RunRegistry } from "./registry.ts";
|
|
26
|
+
import { scanRetention } from "./retention.ts";
|
|
27
|
+
import { delegateRoot, piCommand } from "./spawn.ts";
|
|
28
|
+
import { gitAvailable } from "./worktree.ts";
|
|
29
|
+
|
|
30
|
+
export type CheckLevel = "ok" | "warn" | "fail";
|
|
31
|
+
|
|
32
|
+
export interface DoctorCheck {
|
|
33
|
+
/** Stable short name, padded into the report. */
|
|
34
|
+
name: string;
|
|
35
|
+
level: CheckLevel;
|
|
36
|
+
/** What was measured, on one line. */
|
|
37
|
+
detail: string;
|
|
38
|
+
/** What to do about a warn or a fail. */
|
|
39
|
+
hint?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface DoctorReport {
|
|
43
|
+
checks: DoctorCheck[];
|
|
44
|
+
/** No check failed. A warning is a working installation. */
|
|
45
|
+
ok: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface DoctorInput {
|
|
49
|
+
/** The session registry, when this runs inside a session. */
|
|
50
|
+
registry?: RunRegistry;
|
|
51
|
+
sessionId?: string;
|
|
52
|
+
cwd?: string;
|
|
53
|
+
/** This process is a delegated child rather than a session. */
|
|
54
|
+
isChild?: boolean;
|
|
55
|
+
/** The run root to check. Defaults to the environment's delegate root. */
|
|
56
|
+
root?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Where this module lives, and therefore where the package it belongs to lives. */
|
|
60
|
+
function packageRoot(): string {
|
|
61
|
+
return resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Whether a directory accepts the same create, write and unlink a start needs.
|
|
66
|
+
*
|
|
67
|
+
* The name is unique and opened exclusively: a health check must never truncate
|
|
68
|
+
* or remove an existing file, including a probe left by another process.
|
|
69
|
+
*/
|
|
70
|
+
function probeWritable(root: string): { ok: boolean; detail: string } {
|
|
71
|
+
try {
|
|
72
|
+
// Follow a symlink to a directory: the start path follows it too.
|
|
73
|
+
const stats = statSync(root);
|
|
74
|
+
if (!stats.isDirectory()) return { ok: false, detail: root + " is not a directory" };
|
|
75
|
+
} catch (error) {
|
|
76
|
+
return { ok: false, detail: "cannot inspect " + root + ": " + (error as Error).message };
|
|
77
|
+
}
|
|
78
|
+
const probe = join(root, ".doctor-probe-" + process.pid + "-" + randomUUID());
|
|
79
|
+
let fd: number | undefined;
|
|
80
|
+
let created = false;
|
|
81
|
+
let problem: string | undefined;
|
|
82
|
+
try {
|
|
83
|
+
fd = openSync(probe, "wx", 0o600);
|
|
84
|
+
created = true;
|
|
85
|
+
writeFileSync(fd, "probe");
|
|
86
|
+
} catch (error) {
|
|
87
|
+
problem = "cannot create and write a record: " + (error as Error).message;
|
|
88
|
+
}
|
|
89
|
+
if (fd !== undefined) {
|
|
90
|
+
try {
|
|
91
|
+
closeSync(fd);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
problem ??= "cannot close the probe: " + (error as Error).message;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (created) {
|
|
97
|
+
try {
|
|
98
|
+
unlinkSync(probe);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
problem ??= "cannot remove the probe: " + (error as Error).message;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (problem) return { ok: false, detail: problem };
|
|
104
|
+
return { ok: true, detail: "probed with an exclusive create and an unlink" };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Probe the nearest existing path entry when the run root itself is missing. */
|
|
108
|
+
function probeCreatable(root: string): { ok: boolean; detail: string } {
|
|
109
|
+
let candidate = resolve(root);
|
|
110
|
+
while (true) {
|
|
111
|
+
try {
|
|
112
|
+
// lstat detects a broken symlink as an existing but unusable path entry.
|
|
113
|
+
lstatSync(candidate);
|
|
114
|
+
return probeWritable(candidate);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
117
|
+
if (code !== "ENOENT") {
|
|
118
|
+
return { ok: false, detail: "cannot inspect " + candidate + ": " + (error as Error).message };
|
|
119
|
+
}
|
|
120
|
+
const parent = dirname(candidate);
|
|
121
|
+
if (parent === candidate) return { ok: false, detail: "no existing ancestor of " + root + " can be inspected" };
|
|
122
|
+
candidate = parent;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function probeRunRoot(root: string): { ok: boolean; detail: string } {
|
|
128
|
+
return existsSync(root) ? probeWritable(root) : probeCreatable(root);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The package manifest, and whether the entries it declares still resolve. */
|
|
132
|
+
function checkManifest(): DoctorCheck {
|
|
133
|
+
const root = packageRoot();
|
|
134
|
+
const path = join(root, "package.json");
|
|
135
|
+
let manifest: {
|
|
136
|
+
name?: unknown;
|
|
137
|
+
version?: unknown;
|
|
138
|
+
pi?: { extensions?: unknown; skills?: unknown };
|
|
139
|
+
};
|
|
140
|
+
try {
|
|
141
|
+
manifest = JSON.parse(readFileSync(path, "utf8"));
|
|
142
|
+
} catch (error) {
|
|
143
|
+
return { name: "manifest", level: "fail", detail: "package.json is unreadable: " + (error as Error).message };
|
|
144
|
+
}
|
|
145
|
+
const name = typeof manifest.name === "string" ? manifest.name : "(unnamed)";
|
|
146
|
+
const version = typeof manifest.version === "string" ? manifest.version : "(no version)";
|
|
147
|
+
const extensions = Array.isArray(manifest.pi?.extensions) ? manifest.pi.extensions : [];
|
|
148
|
+
const skills = Array.isArray(manifest.pi?.skills) ? manifest.pi.skills : [];
|
|
149
|
+
const missing = [...extensions, ...skills]
|
|
150
|
+
.filter((entry): entry is string => typeof entry === "string")
|
|
151
|
+
.map((entry) => resolve(root, entry))
|
|
152
|
+
.filter((entry) => !existsSync(entry));
|
|
153
|
+
if (missing.length > 0) {
|
|
154
|
+
return {
|
|
155
|
+
name: "manifest",
|
|
156
|
+
level: "fail",
|
|
157
|
+
detail: name + " " + version + " declares " + missing.map((entry) => resolve(root, entry)).join(", ") + " which do not exist",
|
|
158
|
+
hint: "reinstall the package; this is the shape of a symlinked checkout whose target moved",
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
return { name: "manifest", level: "ok", detail: name + " " + version + " · " + extensions.length + " extension, " + skills.length + " skill path" };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The command that starts a child, and the file it runs. */
|
|
165
|
+
function checkLauncher(): DoctorCheck {
|
|
166
|
+
const { command, prefix } = piCommand();
|
|
167
|
+
const entry = prefix[0];
|
|
168
|
+
// A bare name is resolved through PATH by the spawn, so nothing here can
|
|
169
|
+
// answer for it; a path is a file, and a file that is not there is the bug.
|
|
170
|
+
const isPath = command.includes("/") || command.includes("\\");
|
|
171
|
+
if (isPath && !existsSync(command)) {
|
|
172
|
+
return {
|
|
173
|
+
name: "launcher",
|
|
174
|
+
level: "fail",
|
|
175
|
+
detail: "the child launcher does not exist: " + command,
|
|
176
|
+
hint: "set PI_DELEGATE_PI_COMMAND (or PI_DELEGATE_PI_ENTRY) to the command that starts Pi",
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
if (entry && !existsSync(entry)) {
|
|
180
|
+
return {
|
|
181
|
+
name: "launcher",
|
|
182
|
+
level: "fail",
|
|
183
|
+
detail: "the Pi entry point does not exist: " + entry,
|
|
184
|
+
hint: "set PI_DELEGATE_PI_ENTRY to the JavaScript entry of this Pi install",
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
name: "launcher",
|
|
189
|
+
level: "ok",
|
|
190
|
+
detail: command + (entry ? " " + entry : "") + " · child runs in --mode json",
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function checkRunRoot(root: string): DoctorCheck {
|
|
195
|
+
const exists = existsSync(root);
|
|
196
|
+
const writable = probeRunRoot(root);
|
|
197
|
+
if (!writable.ok) {
|
|
198
|
+
return {
|
|
199
|
+
name: "run root",
|
|
200
|
+
level: "fail",
|
|
201
|
+
detail: root + " is not writable: " + writable.detail,
|
|
202
|
+
hint: "PI_DELEGATE_HOME selects another root",
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
if (!exists) {
|
|
206
|
+
return {
|
|
207
|
+
name: "run root",
|
|
208
|
+
level: "warn",
|
|
209
|
+
detail: root + " does not exist yet · no delegation has run",
|
|
210
|
+
hint: "it is created with the first delegate_start",
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const scan = scanRetention({ root });
|
|
214
|
+
const size = formatBytes(scan.bytes);
|
|
215
|
+
return { name: "run root", level: "ok", detail: root + " · " + scan.total + " records · " + size };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function checkRetention(root: string, registry: RunRegistry | undefined): DoctorCheck {
|
|
219
|
+
const scan = scanRetention({ root, isLive: (runId) => Boolean(registry?.get(runId) && !registry.get(runId)?.outcome) });
|
|
220
|
+
if (scan.total === 0) return { name: "retention", level: "ok", detail: "no records to reclaim" };
|
|
221
|
+
if (scan.removable.length === 0) {
|
|
222
|
+
const policy = scan.policy;
|
|
223
|
+
const bytes = policy.maxBytes > 0 ? formatBytes(policy.maxBytes) : "no byte cap";
|
|
224
|
+
const age = policy.maxAgeDays > 0 ? policy.maxAgeDays + " days" : "no age rule";
|
|
225
|
+
return {
|
|
226
|
+
name: "retention",
|
|
227
|
+
level: "ok",
|
|
228
|
+
detail: scan.total + " records, " + formatBytes(scan.bytes) + " · keep " + policy.keepRuns + " / " + age + " / " + bytes + " · nothing to remove",
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
name: "retention",
|
|
233
|
+
level: "warn",
|
|
234
|
+
detail: scan.removable.length + " of " + scan.total + " records would be removed by the next prune: " + scan.removable.slice(0, 5).join(", "),
|
|
235
|
+
hint: "PI_DELEGATE_MAX_RUNS, PI_DELEGATE_RETENTION_DAYS and PI_DELEGATE_MAX_BYTES set the policy",
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function checkLive(registry: RunRegistry | undefined): DoctorCheck {
|
|
240
|
+
if (!registry) return { name: "live", level: "ok", detail: "no session registry (a child or a headless check)" };
|
|
241
|
+
// The predicate that decides what "live" means lives in contract.ts, so this
|
|
242
|
+
// check and the admission gate cannot disagree about a run that is not done.
|
|
243
|
+
const live = registry
|
|
244
|
+
.list()
|
|
245
|
+
.filter((handle) => !isTerminal(handle.status))
|
|
246
|
+
.map((handle) => handle.runId);
|
|
247
|
+
const limit = maxLive();
|
|
248
|
+
if (live.length === 0) return { name: "live", level: "ok", detail: "nothing running · limit " + limit };
|
|
249
|
+
const detail = live.length + " live of " + limit + " · " + live.slice(0, 3).join(", ");
|
|
250
|
+
return { name: "live", level: live.length >= limit ? "warn" : "ok", detail, hint: live.length >= limit ? "a new start is refused until one settles" : undefined };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function checkGit(): DoctorCheck {
|
|
254
|
+
if (!gitAvailable()) {
|
|
255
|
+
return { name: "git", level: "warn", detail: "git did not run · worktree: true is unavailable", hint: "install git to give parallel children their own checkout" };
|
|
256
|
+
}
|
|
257
|
+
return { name: "git", level: "ok", detail: "available · worktree: true usable" };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function checkLimits(): DoctorCheck {
|
|
261
|
+
const spend = maxCostUsd();
|
|
262
|
+
const verifyTimeout = Number(process.env.PI_DELEGATE_VERIFY_TIMEOUT_MS ?? 120_000);
|
|
263
|
+
return {
|
|
264
|
+
name: "limits",
|
|
265
|
+
level: "ok",
|
|
266
|
+
detail:
|
|
267
|
+
"max live " + maxLive() + " of " + MAX_MAX_LIVE + " · " +
|
|
268
|
+
(spend > 0 ? "$" + spend + " per run" : "spend cap off") +
|
|
269
|
+
" · verify timeout " + (Number.isFinite(verifyTimeout) ? Math.round(verifyTimeout / 1000) + "s" : "default") +
|
|
270
|
+
" · run cap " + MAX_TIMEOUT_MINUTES + " minutes",
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function checkSession(input: DoctorInput): DoctorCheck {
|
|
275
|
+
const where = input.cwd ?? process.cwd();
|
|
276
|
+
const session = input.sessionId ? input.sessionId : "(no session id)";
|
|
277
|
+
const mode = input.isChild ? "delegated child" : "top-level session";
|
|
278
|
+
if (input.isChild && !process.env[SPEC_ENV]) {
|
|
279
|
+
return { name: "session", level: "warn", detail: session + " in " + where + " · " + mode + " with no spec path" };
|
|
280
|
+
}
|
|
281
|
+
return { name: "session", level: "ok", detail: session + " in " + where + " · " + mode };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function checkContainment(): DoctorCheck {
|
|
285
|
+
const level = observability();
|
|
286
|
+
if (supportsFence()) {
|
|
287
|
+
return { name: "containment", level: "ok", detail: "linux: procfs identity, tag scan, group fence" };
|
|
288
|
+
}
|
|
289
|
+
if (level === "partial") {
|
|
290
|
+
return { name: "containment", level: "ok", detail: "process group only: cancellation works, absence is proven by signal 0" };
|
|
291
|
+
}
|
|
292
|
+
return {
|
|
293
|
+
name: "containment",
|
|
294
|
+
level: "warn",
|
|
295
|
+
detail: "no process table: a cancel reports unproven, never gone",
|
|
296
|
+
hint: "expected on Windows; the tree is asked to die and the verdict says so",
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function formatBytes(bytes: number): string {
|
|
301
|
+
if (bytes < 1024) return bytes + " B";
|
|
302
|
+
if (bytes < 1024 * 1024) return Math.round(bytes / 102.4) / 10 + " KiB";
|
|
303
|
+
if (bytes < 1024 * 1024 * 1024) return Math.round(bytes / 1024 / 102.4) / 10 + " MiB";
|
|
304
|
+
return Math.round(bytes / 1024 / 1024 / 102.4) / 10 + " GiB";
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Run every check. Nothing here throws: a check that cannot answer says so. */
|
|
308
|
+
export function runDoctor(input: DoctorInput = {}): DoctorReport {
|
|
309
|
+
const root = input.root ?? delegateRoot();
|
|
310
|
+
const checks: DoctorCheck[] = [];
|
|
311
|
+
const guarded = (name: string, run: () => DoctorCheck) => {
|
|
312
|
+
try {
|
|
313
|
+
checks.push(run());
|
|
314
|
+
} catch (error) {
|
|
315
|
+
checks.push({ name, level: "fail", detail: "the check itself failed: " + (error as Error).message });
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
guarded("manifest", () => checkManifest());
|
|
319
|
+
guarded("run root", () => checkRunRoot(root));
|
|
320
|
+
guarded("git", () => checkGit());
|
|
321
|
+
guarded("launcher", () => checkLauncher());
|
|
322
|
+
guarded("live", () => checkLive(input.registry));
|
|
323
|
+
guarded("retention", () => checkRetention(root, input.registry));
|
|
324
|
+
guarded("limits", () => checkLimits());
|
|
325
|
+
guarded("session", () => checkSession(input));
|
|
326
|
+
guarded("containment", () => checkContainment());
|
|
327
|
+
return { checks, ok: checks.every((check) => check.level !== "fail") };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** The report as a human reads it: one line per check, aligned. */
|
|
331
|
+
export function formatDoctor(report: DoctorReport): string {
|
|
332
|
+
const width = Math.max(...report.checks.map((check) => check.name.length));
|
|
333
|
+
const lines = ["delegate doctor"];
|
|
334
|
+
for (const check of report.checks) {
|
|
335
|
+
lines.push(" " + check.name.padEnd(width) + " " + check.level.padEnd(4) + " " + check.detail);
|
|
336
|
+
if (check.hint) lines.push(" " + " ".repeat(width) + " " + check.hint);
|
|
337
|
+
}
|
|
338
|
+
lines.push("");
|
|
339
|
+
lines.push(report.ok ? "Every check passed." : "At least one check failed; delegations will not work until it does.");
|
|
340
|
+
return lines.join("\n");
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* The one problem worth announcing at `session_start`.
|
|
345
|
+
*
|
|
346
|
+
* A run root that cannot be written is the failure mode that used to surface
|
|
347
|
+
* days later as a start that failed for an unrelated-looking reason. Every other
|
|
348
|
+
* check is on demand, because a warning on every session is a warning nobody
|
|
349
|
+
* reads.
|
|
350
|
+
*/
|
|
351
|
+
export function startupWarning(root: string = delegateRoot()): string | undefined {
|
|
352
|
+
const probe = probeRunRoot(root);
|
|
353
|
+
if (probe.ok) return undefined;
|
|
354
|
+
return "delegate: the run-record root " + root + " is not writable (" + probe.detail + "). Delegations will fail; run /delegate doctor.";
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Age of the oldest record, for a caller that wants it without the full scan. */
|
|
358
|
+
export function oldestRecordAge(root: string = delegateRoot()): string | undefined {
|
|
359
|
+
const scan = scanRetention({ root });
|
|
360
|
+
return scan.oldestAgeMs === undefined ? undefined : formatDuration(scan.oldestAgeMs);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** The paths a support request needs, in one string. */
|
|
364
|
+
export function describePaths(root: string = delegateRoot()): string {
|
|
365
|
+
const real = (() => {
|
|
366
|
+
try {
|
|
367
|
+
return realpathSync(root);
|
|
368
|
+
} catch {
|
|
369
|
+
return root;
|
|
370
|
+
}
|
|
371
|
+
})();
|
|
372
|
+
let entries = 0;
|
|
373
|
+
try {
|
|
374
|
+
entries = readdirSync(root).length;
|
|
375
|
+
} catch {
|
|
376
|
+
entries = 0;
|
|
377
|
+
}
|
|
378
|
+
let mode = "missing";
|
|
379
|
+
try {
|
|
380
|
+
mode = "0" + (statSync(root).mode & 0o777).toString(8);
|
|
381
|
+
} catch {
|
|
382
|
+
// a root that does not exist has no mode
|
|
383
|
+
}
|
|
384
|
+
return "root " + real + " (" + mode + ", " + entries + " entries) · extension " + packageRoot();
|
|
385
|
+
}
|
package/src/events.ts
CHANGED
|
@@ -11,7 +11,19 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import { open } from "node:fs/promises";
|
|
14
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
addUsage,
|
|
16
|
+
canonicalCallSignature,
|
|
17
|
+
noteIdleTurn,
|
|
18
|
+
noteToolCall,
|
|
19
|
+
noteToolResult,
|
|
20
|
+
type BreakerVerdict,
|
|
21
|
+
type RunProgress,
|
|
22
|
+
} from "./contract.ts";
|
|
23
|
+
|
|
24
|
+
function noteBreaker(progress: RunProgress, verdict: BreakerVerdict): void {
|
|
25
|
+
if (verdict.kind === "stop") progress.noProgressReason = verdict.reason;
|
|
26
|
+
}
|
|
15
27
|
|
|
16
28
|
const MAX_TEXT = 4000;
|
|
17
29
|
const MAX_LINE = 4 * 1024 * 1024;
|
|
@@ -60,14 +72,22 @@ export function foldEvent(progress: RunProgress, record: unknown): void {
|
|
|
60
72
|
}
|
|
61
73
|
case "turn_start": {
|
|
62
74
|
progress.turns += 1;
|
|
75
|
+
progress.toolCallsThisTurn = 0;
|
|
63
76
|
return;
|
|
64
77
|
}
|
|
65
78
|
case "tool_execution_start": {
|
|
66
79
|
progress.toolCalls += 1;
|
|
80
|
+
progress.toolCallsThisTurn += 1;
|
|
81
|
+
const toolName = typeof event.toolName === "string" ? event.toolName : "";
|
|
82
|
+
const signature = typeof event.signature === "string"
|
|
83
|
+
? event.signature
|
|
84
|
+
: canonicalCallSignature(toolName, event.args);
|
|
85
|
+
noteBreaker(progress, noteToolCall(progress.breaker, signature, toolName));
|
|
67
86
|
return;
|
|
68
87
|
}
|
|
69
88
|
case "tool_execution_end": {
|
|
70
89
|
if (event.isError === true) progress.toolErrors += 1;
|
|
90
|
+
noteBreaker(progress, noteToolResult(progress.breaker, event.isError === true));
|
|
71
91
|
return;
|
|
72
92
|
}
|
|
73
93
|
case "message_end": {
|
|
@@ -101,6 +121,7 @@ export function foldEvent(progress: RunProgress, record: unknown): void {
|
|
|
101
121
|
}
|
|
102
122
|
case "agent_settled": {
|
|
103
123
|
progress.settledOnce = true;
|
|
124
|
+
noteBreaker(progress, noteIdleTurn(progress.breaker, progress.lastText, progress.toolCallsThisTurn));
|
|
104
125
|
return;
|
|
105
126
|
}
|
|
106
127
|
default:
|