@maheidem/pi-delegate 0.1.4 → 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/README.md +104 -2
- package/application.ts +54 -4
- package/commands.ts +14 -2
- package/config.ts +26 -3
- package/handoff.ts +265 -0
- package/index.ts +109 -10
- package/package.json +68 -66
- package/roles/general.md +24 -18
- package/roles/research.md +9 -19
- package/rpc-jsonl.ts +10 -2
- package/run-store.ts +96 -10
- package/runner.ts +471 -23
- package/types.ts +35 -0
- package/version.ts +28 -0
package/index.ts
CHANGED
|
@@ -22,6 +22,8 @@ import {
|
|
|
22
22
|
import { Text } from "@earendil-works/pi-tui";
|
|
23
23
|
|
|
24
24
|
import { formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
|
|
25
|
+
import { delegateVersion } from "./version.ts";
|
|
26
|
+
import { HandoffToolParams, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
|
|
25
27
|
import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
|
|
26
28
|
import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
|
|
27
29
|
import { STRICT_OVERLAY, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
|
|
@@ -113,9 +115,62 @@ export function formatRunSummary(
|
|
|
113
115
|
return out.join("\n");
|
|
114
116
|
}
|
|
115
117
|
|
|
118
|
+
/**
|
|
119
|
+
* Child-mode surface: the delegated child gets EXACTLY ONE delegate tool —
|
|
120
|
+
* the mandatory structured `handoff`. The child's final report is a
|
|
121
|
+
* protocol step (schema-validated, retried on error, enforced by the
|
|
122
|
+
* runner), never free text the harness hopes has the right shape.
|
|
123
|
+
*/
|
|
124
|
+
function registerChildHandoffTool(pi: ExtensionAPI): void {
|
|
125
|
+
pi.registerTool({
|
|
126
|
+
name: "handoff",
|
|
127
|
+
label: "Handoff",
|
|
128
|
+
description:
|
|
129
|
+
"MANDATORY final report for this delegated run. Your run does not complete until this tool " +
|
|
130
|
+
"has been called with a valid submission; free-text endings are rejected and you will be re-prompted. " +
|
|
131
|
+
"When terminated mid-work, call it immediately with outcome=partial.",
|
|
132
|
+
parameters: HandoffToolParams,
|
|
133
|
+
async execute(_toolCallId, params): Promise<{
|
|
134
|
+
content: Array<{ type: "text"; text: string }>;
|
|
135
|
+
details: { delegateHandoff?: HandoffSubmission; rejected?: boolean; errors?: string[] };
|
|
136
|
+
isError?: boolean;
|
|
137
|
+
}> {
|
|
138
|
+
const validation = validateHandoffSubmission(params);
|
|
139
|
+
if (!validation.ok) {
|
|
140
|
+
return {
|
|
141
|
+
content: [
|
|
142
|
+
{
|
|
143
|
+
type: "text" as const,
|
|
144
|
+
text:
|
|
145
|
+
"handoff REJECTED — fix every field listed below and call the handoff tool again:\n" +
|
|
146
|
+
validation.errors.map((e) => `- ${e}`).join("\n"),
|
|
147
|
+
},
|
|
148
|
+
],
|
|
149
|
+
details: { rejected: true, errors: validation.errors },
|
|
150
|
+
isError: true,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
const value = validation.value!;
|
|
154
|
+
return {
|
|
155
|
+
content: [
|
|
156
|
+
{
|
|
157
|
+
type: "text" as const,
|
|
158
|
+
text: `handoff accepted (${value.outcome}) — you may now end your turn. Do not write another final message.`,
|
|
159
|
+
},
|
|
160
|
+
],
|
|
161
|
+
details: { delegateHandoff: value },
|
|
162
|
+
};
|
|
163
|
+
},
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
116
167
|
export default function delegateExtension(pi: ExtensionAPI) {
|
|
117
|
-
// 1. The child never reactivates
|
|
118
|
-
|
|
168
|
+
// 1. The child never reactivates the parent surface (POL: no recursion) —
|
|
169
|
+
// it registers ONLY the mandatory structured-handoff tool.
|
|
170
|
+
if (process.env.PI_DELEGATE_CHILD === "1") {
|
|
171
|
+
registerChildHandoffTool(pi);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
119
174
|
// 2. Construct state — no child, no timers at load time.
|
|
120
175
|
// PI_DELEGATE_AGENT_DIR is a test override; production uses getAgentDir().
|
|
121
176
|
const agentDir = process.env.PI_DELEGATE_AGENT_DIR || getAgentDir();
|
|
@@ -168,6 +223,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
168
223
|
source: "tool" | "command",
|
|
169
224
|
ctx: ExtensionContext,
|
|
170
225
|
timeoutMs?: number,
|
|
226
|
+
extras?: { model?: string; resumeFrom?: string },
|
|
171
227
|
): DelegateRequest => ({
|
|
172
228
|
task,
|
|
173
229
|
role,
|
|
@@ -178,6 +234,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
178
234
|
projectTrusted: ctx.isProjectTrusted(),
|
|
179
235
|
projectRoot: ctx.cwd ?? process.cwd(),
|
|
180
236
|
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
237
|
+
...(extras?.model ? { model: extras.model } : {}),
|
|
238
|
+
...(extras?.resumeFrom ? { resumeFrom: extras.resumeFrom } : {}),
|
|
181
239
|
});
|
|
182
240
|
|
|
183
241
|
const refreshDoctor = (ctx: ExtensionContext) => {
|
|
@@ -236,10 +294,21 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
236
294
|
: d.state.startsWith("timed_out") ? d.state.replace("_", " ")
|
|
237
295
|
: d.state;
|
|
238
296
|
const secs = Math.round(d.durationMs / 1000);
|
|
239
|
-
const head =
|
|
297
|
+
const head =
|
|
298
|
+
`[delegate v${delegateVersion()} · ${d.runId} · ${d.role} · ${stateLabel} in ${secs}s` +
|
|
299
|
+
`${d.model ? ` · ${d.model}` : ""}${d.timeoutInfo ? ` · ${d.timeoutInfo}` : ""}]`;
|
|
240
300
|
if (!res.ok) {
|
|
301
|
+
const parts = [head];
|
|
241
302
|
const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
|
|
242
|
-
|
|
303
|
+
parts.push(`error: ${err}`);
|
|
304
|
+
// R2: the killed child's own account of its partial work.
|
|
305
|
+
if (res.details.partialHandoff) {
|
|
306
|
+
parts.push("", "partial handoff (captured at kill):", res.details.partialHandoff);
|
|
307
|
+
}
|
|
308
|
+
if (res.modelNote) parts.push(`note: ${res.modelNote}`);
|
|
309
|
+
parts.push(`transcript: ${d.transcriptPath}`);
|
|
310
|
+
if (d.sessionPath) parts.push(`session: ${d.sessionPath} (resumable via resumeFrom: ${d.runId})`);
|
|
311
|
+
return parts.join("\n");
|
|
243
312
|
}
|
|
244
313
|
const parts = [head, "", res.handoff];
|
|
245
314
|
if (d.outputTruncated || d.stderrPath) {
|
|
@@ -268,7 +337,20 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
268
337
|
timeout: Type.Optional(Type.String({
|
|
269
338
|
description:
|
|
270
339
|
"Optional per-run hard timeout, e.g. '90s', '10m', '2h', '1d' or bare ms. " +
|
|
271
|
-
"Use it when the subtask is expected to run longer than the configured default; it overrides the project/user config base."
|
|
340
|
+
"Use it when the subtask is expected to run longer than the configured default; it overrides the project/user config base. " +
|
|
341
|
+
"Effective inactivity = min(config, hard/2); a single tool call longer than that is killed unless the in-flight-tool budget covers it — " +
|
|
342
|
+
"for long validation/benchmark work set timeout at 2x the longest expected tool call.",
|
|
343
|
+
})),
|
|
344
|
+
model: Type.Optional(Type.String({
|
|
345
|
+
description:
|
|
346
|
+
"Optional child model pin as 'provider/model-id'. Without it the child silently inherits the parent's CURRENT model — " +
|
|
347
|
+
"if the parent switches models mid-session (e.g. a usage-limit fallback), children follow. Pin this for model-sensitive work.",
|
|
348
|
+
})),
|
|
349
|
+
resumeFrom: Type.Optional(Type.String({
|
|
350
|
+
description:
|
|
351
|
+
"Resume a prior run's durable child session: pass its runId. The new child re-enters that exact context " +
|
|
352
|
+
"(earlier turns included) with your task as the continuation prompt — no cold re-explanation. " +
|
|
353
|
+
"Works for runs whose receipt records a sessionPath (post-0.2.0) and whose session file still exists.",
|
|
272
354
|
})),
|
|
273
355
|
});
|
|
274
356
|
|
|
@@ -284,6 +366,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
284
366
|
"Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
|
|
285
367
|
"Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
|
|
286
368
|
"Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
|
|
369
|
+
"A timed-out run leaves a partialHandoff, a git checkpoint and a resumable child session: pass resumeFrom: <runId> to continue in the same context instead of re-explaining, and inspect the receipt's gitDelta before repairing anything.",
|
|
370
|
+
"Pin model: 'provider/model-id' when the child must not silently follow the parent's current model (e.g. after a mid-session model fallback).",
|
|
371
|
+
"For long validation/benchmark subtasks set timeout to at least 2x the longest expected single tool call.",
|
|
287
372
|
"While delegation mode is active, all substantive work and verification must use delegate; the parent is coordination-only.",
|
|
288
373
|
],
|
|
289
374
|
parameters: DelegateParams,
|
|
@@ -301,13 +386,17 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
301
386
|
};
|
|
302
387
|
}
|
|
303
388
|
}
|
|
304
|
-
const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs
|
|
389
|
+
const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs, {
|
|
390
|
+
model: typeof params.model === "string" && params.model.trim() ? params.model.trim() : undefined,
|
|
391
|
+
resumeFrom: typeof params.resumeFrom === "string" && params.resumeFrom.trim() ? params.resumeFrom.trim() : undefined,
|
|
392
|
+
});
|
|
305
393
|
refreshDoctor(ctx);
|
|
306
394
|
const hooks = {
|
|
307
395
|
abortSignal: signal ?? undefined,
|
|
308
396
|
onUpdate: (u: RunStreamUpdate) => {
|
|
397
|
+
const modelBit = u.model ? ` · ${u.model}` : "";
|
|
309
398
|
onUpdate?.({
|
|
310
|
-
content: [{ type: "text", text: `[delegate ${u.runId} · ${u.role} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]` }],
|
|
399
|
+
content: [{ type: "text", text: `[delegate v${delegateVersion()} ${u.runId} · ${u.role}${modelBit} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]` }],
|
|
311
400
|
details: { runId: u.runId, phase: u.phase },
|
|
312
401
|
});
|
|
313
402
|
},
|
|
@@ -393,8 +482,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
393
482
|
}
|
|
394
483
|
};
|
|
395
484
|
|
|
396
|
-
const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number): Promise<void> => {
|
|
397
|
-
const request = buildRequest(task, role, "command", ctx, timeoutMs);
|
|
485
|
+
const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string }): Promise<void> => {
|
|
486
|
+
const request = buildRequest(task, role, "command", ctx, timeoutMs, extras);
|
|
398
487
|
refreshDoctor(ctx);
|
|
399
488
|
let lastText = `[delegate] starting ${role} run…`;
|
|
400
489
|
const hooks = {
|
|
@@ -468,7 +557,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
468
557
|
|
|
469
558
|
const statusText = (ctx: ExtensionContext): string => {
|
|
470
559
|
const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
|
|
471
|
-
const lines = ["[delegate]", `mode: ${s.modeEnabled ? "strict" : "normal"}`];
|
|
560
|
+
const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
|
|
472
561
|
lines.push(`parent tools: ${s.modeEnabled ? "delegate only" : "normal active set"}`);
|
|
473
562
|
lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
|
|
474
563
|
if (s.lastRun) {
|
|
@@ -504,6 +593,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
504
593
|
"/delegate research <task> research role",
|
|
505
594
|
"/delegate <task> general-role shorthand",
|
|
506
595
|
"/delegate cancel [run-id] cancel the active run",
|
|
596
|
+
"/delegate resume <run-id> <task> resume a prior run's child session",
|
|
507
597
|
"/delegate inspect [run-id] inspect a run (default: recent/active)",
|
|
508
598
|
"/delegate paths config + run store paths",
|
|
509
599
|
"/delegate doctor diagnostics",
|
|
@@ -590,6 +680,15 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
590
680
|
}
|
|
591
681
|
await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
|
|
592
682
|
return;
|
|
683
|
+
case "resume": {
|
|
684
|
+
const runId = intent.runId?.trim();
|
|
685
|
+
if (!runId || !intent.task) {
|
|
686
|
+
say(ctx, `[delegate] usage: /delegate resume <run-id> <continuation task...>`, "error");
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
await runCommandForeground(intent.task, "general", ctx, intent.timeoutMs, { resumeFrom: runId });
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
593
692
|
case "invalid":
|
|
594
693
|
say(ctx, `[delegate] unrecognized '${intent.token}'.\n${intent.usage}\n${helpText()}`, "error");
|
|
595
694
|
return;
|
package/package.json
CHANGED
|
@@ -1,68 +1,70 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
"
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
2
|
+
"name": "@maheidem/pi-delegate",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "maheidem",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"pi",
|
|
10
|
+
"pi-coding-agent",
|
|
11
|
+
"pi-extension",
|
|
12
|
+
"delegate",
|
|
13
|
+
"subagent",
|
|
14
|
+
"orchestration",
|
|
15
|
+
"coordinator"
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/Maheidem/pi-delegate.git"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/Maheidem/pi-delegate/issues"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/Maheidem/pi-delegate#readme",
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"index.ts",
|
|
30
|
+
"application.ts",
|
|
31
|
+
"commands.ts",
|
|
32
|
+
"config.ts",
|
|
33
|
+
"mode.ts",
|
|
34
|
+
"roles.ts",
|
|
35
|
+
"runner.ts",
|
|
36
|
+
"rpc-jsonl.ts",
|
|
37
|
+
"run-store.ts",
|
|
38
|
+
"types.ts",
|
|
39
|
+
"version.ts",
|
|
40
|
+
"handoff.ts",
|
|
41
|
+
"roles/",
|
|
42
|
+
"ui/",
|
|
43
|
+
"README.md",
|
|
44
|
+
"LICENSE"
|
|
45
|
+
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
48
|
+
"test": "node tests/run.mjs",
|
|
49
|
+
"test:unit": "node tests/run.mjs",
|
|
50
|
+
"test:e2e": "node tests/e2e.mjs",
|
|
51
|
+
"prepack": "npm run typecheck && npm test"
|
|
52
|
+
},
|
|
53
|
+
"peerDependencies": {
|
|
54
|
+
"@earendil-works/pi-coding-agent": ">=0.84.4",
|
|
55
|
+
"@earendil-works/pi-tui": "*",
|
|
56
|
+
"typebox": "*"
|
|
57
|
+
},
|
|
58
|
+
"devDependencies": {
|
|
59
|
+
"@earendil-works/pi-coding-agent": "^0.84.4",
|
|
60
|
+
"@earendil-works/pi-tui": "^0.84.4",
|
|
61
|
+
"@types/node": "^22.0.0",
|
|
62
|
+
"typebox": "^1.0.17",
|
|
63
|
+
"typescript": "^5.9.3"
|
|
64
|
+
},
|
|
65
|
+
"pi": {
|
|
66
|
+
"extensions": [
|
|
67
|
+
"./index.ts"
|
|
68
|
+
]
|
|
69
|
+
}
|
|
68
70
|
}
|
package/roles/general.md
CHANGED
|
@@ -21,21 +21,27 @@ message is the only thing returned to it, bounded and summarized.
|
|
|
21
21
|
- Your tool ceiling is closed: read, bash, edit, write, grep, find, ls.
|
|
22
22
|
There is no browser, no network tool, and no delegate tool.
|
|
23
23
|
|
|
24
|
-
## Output contract
|
|
25
|
-
|
|
26
|
-
Your
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
24
|
+
## Output contract — the mandatory handoff tool
|
|
25
|
+
|
|
26
|
+
Your run is NOT complete until you call the **handoff** tool with a valid
|
|
27
|
+
submission. This is a protocol requirement, not a writing exercise:
|
|
28
|
+
|
|
29
|
+
- `outcome` — `done` | `partial` | `blocked`
|
|
30
|
+
- `summary` — the essential result statement (1–5 lines)
|
|
31
|
+
- `changes` — every path you created/modified/deleted, one entry each
|
|
32
|
+
(`{path, action, note}`); omit or leave empty if none
|
|
33
|
+
- `verification` — the commands you ran and their results
|
|
34
|
+
(`{command, result: pass|fail|not_run, note}`)
|
|
35
|
+
- `remaining` — REQUIRED unless `outcome` is `done`: precise next steps
|
|
36
|
+
- `risks` — residual risk, assumptions, follow-ups; omit if none
|
|
37
|
+
|
|
38
|
+
Rules:
|
|
39
|
+
|
|
40
|
+
- Submit through the tool; do not write the report as a chat message.
|
|
41
|
+
If you settle without submitting, you will be re-prompted until you do.
|
|
42
|
+
- A malformed submission is rejected with the exact field errors — fix them
|
|
43
|
+
and call the tool again.
|
|
44
|
+
- If you are terminated mid-work (termination notice), call the handoff
|
|
45
|
+
tool immediately with `outcome: "partial"` instead of writing prose.
|
|
46
|
+
- After the tool accepts your submission, end your turn; do not write
|
|
47
|
+
another final message.
|
package/roles/research.md
CHANGED
|
@@ -25,22 +25,12 @@ message is the only thing returned to it, bounded and summarized.
|
|
|
25
25
|
mcp__firecrawl, mcp__reddit. There is no bash, no write/edit, and no
|
|
26
26
|
delegate tool.
|
|
27
27
|
|
|
28
|
-
## Output contract
|
|
29
|
-
|
|
30
|
-
Your
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
## Uncertainties
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
- **Recommendation** — the direct answer / recommendation, 1–7 lines.
|
|
41
|
-
- **Evidence** — the key supporting findings, each tied to a source URL;
|
|
42
|
-
mark inference explicitly (e.g. "inference:").
|
|
43
|
-
- **Sources** — the list of URLs actually used, one per line.
|
|
44
|
-
- **Uncertainties** — gaps, conflicting sources, confidence limits; or "none".
|
|
45
|
-
|
|
46
|
-
Do not add other top-level headings. Do not include raw tool transcripts.
|
|
28
|
+
## Output contract — the mandatory handoff tool
|
|
29
|
+
|
|
30
|
+
Your run is NOT complete until you call the **handoff** tool with a valid
|
|
31
|
+
submission (`outcome` done|partial|blocked, `summary`, `changes` — usually
|
|
32
|
+
none for research, `verification` — sources checked, `remaining`, `risks`).
|
|
33
|
+
Same rules as the general role: submit through the tool; malformed
|
|
34
|
+
submissions are rejected with the exact field errors; on a termination
|
|
35
|
+
notice submit immediately with `outcome: "partial"`. Preserve source URLs
|
|
36
|
+
in the fields (summary/verification notes) — they are the audit trail.
|
package/rpc-jsonl.ts
CHANGED
|
@@ -23,7 +23,7 @@ export interface RpcRecord {
|
|
|
23
23
|
export type RpcRecordClassification =
|
|
24
24
|
| { kind: "prompt_response"; ok: boolean; id: string }
|
|
25
25
|
| { kind: "message_end"; stopReason?: string }
|
|
26
|
-
| { kind: "tool_event"; phase: "start" | "update" | "end"; toolName?: string; args?: Record<string, unknown
|
|
26
|
+
| { kind: "tool_event"; phase: "start" | "update" | "end"; id?: string; toolName?: string; args?: Record<string, unknown>; result?: { details?: unknown; isError?: boolean } }
|
|
27
27
|
| { kind: "agent_settled" }
|
|
28
28
|
| { kind: "agent_end" }
|
|
29
29
|
| { kind: "extension_ui_request"; id: string }
|
|
@@ -148,6 +148,7 @@ export function classifyRpcRecord(record: RpcRecord): RpcRecordClassification {
|
|
|
148
148
|
return {
|
|
149
149
|
kind: "tool_event",
|
|
150
150
|
phase: "start",
|
|
151
|
+
id: typeof obj.toolCallId === "string" ? obj.toolCallId : undefined,
|
|
151
152
|
toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
|
|
152
153
|
args: isArgsObject(obj.args) ? (obj.args as Record<string, unknown>) : undefined,
|
|
153
154
|
};
|
|
@@ -155,14 +156,21 @@ export function classifyRpcRecord(record: RpcRecord): RpcRecordClassification {
|
|
|
155
156
|
return {
|
|
156
157
|
kind: "tool_event",
|
|
157
158
|
phase: "update",
|
|
159
|
+
id: typeof obj.toolCallId === "string" ? obj.toolCallId : undefined,
|
|
158
160
|
toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
|
|
159
161
|
};
|
|
160
|
-
case "tool_execution_end":
|
|
162
|
+
case "tool_execution_end": {
|
|
163
|
+
const result = (obj.result ?? {}) as Record<string, unknown>;
|
|
161
164
|
return {
|
|
162
165
|
kind: "tool_event",
|
|
163
166
|
phase: "end",
|
|
167
|
+
id: typeof obj.toolCallId === "string" ? obj.toolCallId : undefined,
|
|
164
168
|
toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
|
|
169
|
+
...(result && typeof result === "object"
|
|
170
|
+
? { result: { details: result.details, isError: result.isError === true } }
|
|
171
|
+
: {}),
|
|
165
172
|
};
|
|
173
|
+
}
|
|
166
174
|
case "agent_settled":
|
|
167
175
|
return { kind: "agent_settled" };
|
|
168
176
|
case "agent_end":
|
package/run-store.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import * as fs from "node:fs";
|
|
12
12
|
import * as path from "node:path";
|
|
13
13
|
import * as crypto from "node:crypto";
|
|
14
|
+
import * as childProcess from "node:child_process";
|
|
14
15
|
import type {
|
|
15
16
|
DelegatePaths,
|
|
16
17
|
DelegateRequest,
|
|
@@ -258,22 +259,107 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
|
|
|
258
259
|
}
|
|
259
260
|
|
|
260
261
|
/**
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
262
|
+
* Signal-0 liveness probe: `process.kill(pid, 0)` sends no signal. EPERM
|
|
263
|
+
* means the pid exists (owned by another user) — treat as alive; ESRCH and
|
|
264
|
+
* any other error mean the pid is gone.
|
|
265
|
+
*/
|
|
266
|
+
export function isPidAlive(pid: number): boolean {
|
|
267
|
+
if (!Number.isInteger(pid) || pid <= 1) return false;
|
|
268
|
+
try {
|
|
269
|
+
process.kill(pid, 0);
|
|
270
|
+
return true;
|
|
271
|
+
} catch (error) {
|
|
272
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Best-effort read of another process's command line:
|
|
278
|
+
* - Linux: /proc/<pid>/cmdline (NUL-separated args);
|
|
279
|
+
* - elsewhere (macOS): `ps -o args= -p <pid>` (single line, no header).
|
|
280
|
+
* Returns null when the pid is dead or the cmdline cannot be read.
|
|
281
|
+
*/
|
|
282
|
+
export function pidCommandLine(pid: number): string | null {
|
|
283
|
+
if (!isPidAlive(pid)) return null;
|
|
284
|
+
if (process.platform === "linux") {
|
|
285
|
+
try {
|
|
286
|
+
const text = fs.readFileSync(`/proc/${pid}/cmdline`, "utf8")
|
|
287
|
+
.replace(/\0+/g, " ")
|
|
288
|
+
.trim();
|
|
289
|
+
return text.length > 0 ? text : null;
|
|
290
|
+
} catch {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
try {
|
|
295
|
+
const out = childProcess.spawnSync("ps", ["-o", "args=", "-p", String(pid)], {
|
|
296
|
+
encoding: "utf8",
|
|
297
|
+
timeout: 2_000,
|
|
298
|
+
});
|
|
299
|
+
if (out.error || out.status !== 0) return null;
|
|
300
|
+
const text = (out.stdout ?? "").trim();
|
|
301
|
+
return text.length > 0 ? text : null;
|
|
302
|
+
} catch {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* True when the command line belongs to a Pi process (a delegate child, or
|
|
309
|
+
* a concurrent pi parent owning a run): any whitespace-split token whose
|
|
310
|
+
* path basename is exactly `pi` (covers `pi --mode rpc ...`,
|
|
311
|
+
* `/opt/homebrew/bin/pi ...`, `node /opt/homebrew/bin/pi ...`), or a path
|
|
312
|
+
* under the pi-coding-agent package (covers
|
|
313
|
+
* `node .../pi-coding-agent/dist/bundle/cli.js ...`).
|
|
314
|
+
*/
|
|
315
|
+
export function commandLineIsPi(cmdline: string): boolean {
|
|
316
|
+
for (const token of cmdline.trim().split(/\s+/)) {
|
|
317
|
+
if (token && path.basename(token) === "pi") return true;
|
|
318
|
+
}
|
|
319
|
+
return cmdline.includes("pi-coding-agent");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Startup orphan recovery (§10.6): nonterminal metadata whose owned process
|
|
324
|
+
* is gone becomes `crashed` with E_ORPHANED_RUN. This process NEVER kills a
|
|
325
|
+
* PID found in stale metadata.
|
|
326
|
+
*
|
|
327
|
+
* P1: a live pi process owns its runs — concurrent multi-session pi (the
|
|
328
|
+
* pattern documented in AGENTS.md) must never clobber a run that another
|
|
329
|
+
* live pi process is actively running or finalizing. Decision table per
|
|
330
|
+
* nonterminal run:
|
|
331
|
+
* - no stored pid, or pid dead → mark crashed (unchanged);
|
|
332
|
+
* - pid alive, cmdline is pi → SKIP (live delegate owner);
|
|
333
|
+
* - pid alive, cmdline known, not pi → mark crashed (recycled PID);
|
|
334
|
+
* - pid alive, cmdline unreadable → SKIP (fail-safe: never clobber on doubt).
|
|
335
|
+
* Returns the touched run IDs.
|
|
264
336
|
*/
|
|
265
337
|
export function markOrphanedRuns(agentDir: string): string[] {
|
|
266
338
|
const touched: string[] = [];
|
|
267
339
|
for (const summary of listRuns(agentDir)) {
|
|
268
340
|
if (isTerminalRunState(summary.state)) continue;
|
|
269
341
|
try {
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
342
|
+
const storedPid = readRunMetadata(agentDir, summary.runId)?.pid;
|
|
343
|
+
if (typeof storedPid === "number" && isPidAlive(storedPid)) {
|
|
344
|
+
const cmdline = pidCommandLine(storedPid);
|
|
345
|
+
if (cmdline === null) continue; // fail-safe: alive but unreadable
|
|
346
|
+
if (commandLineIsPi(cmdline)) continue; // live pi owner
|
|
347
|
+
const next = updateRunMetadata(agentDir, summary.runId, (current) => ({
|
|
348
|
+
state: "crashed",
|
|
349
|
+
errorCode: "E_ORPHANED_RUN",
|
|
350
|
+
errorMessage: `Run store started with this run nonterminal; stored pid ${storedPid} is alive but not a pi process (recycled pid), so the run has no owner.`,
|
|
351
|
+
finishedAt: current.finishedAt ?? new Date().toISOString(),
|
|
352
|
+
}));
|
|
353
|
+
if (next.state === "crashed") touched.push(summary.runId);
|
|
354
|
+
} else {
|
|
355
|
+
const next = updateRunMetadata(agentDir, summary.runId, (current) => ({
|
|
356
|
+
state: "crashed",
|
|
357
|
+
errorCode: "E_ORPHANED_RUN",
|
|
358
|
+
errorMessage: "Run store started with this run nonterminal and no owned child process.",
|
|
359
|
+
finishedAt: current.finishedAt ?? new Date().toISOString(),
|
|
360
|
+
}));
|
|
361
|
+
if (next.state === "crashed") touched.push(summary.runId);
|
|
362
|
+
}
|
|
277
363
|
} catch {
|
|
278
364
|
// skip
|
|
279
365
|
}
|