@maheidem/pi-delegate 0.1.5 → 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/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 this extension (POL: no recursion).
118
- if (process.env.PI_DELEGATE_CHILD === "1") return;
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 = `[delegate ${d.runId} · ${d.role} · ${stateLabel} in ${secs}s]`;
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
- return `${head}\nerror: ${err}\ntranscript: ${d.transcriptPath}`;
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
- "name": "@maheidem/pi-delegate",
3
- "version": "0.1.5",
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
- "roles/",
40
- "ui/",
41
- "README.md",
42
- "LICENSE"
43
- ],
44
- "scripts": {
45
- "typecheck": "tsc -p tsconfig.json",
46
- "test": "node tests/run.mjs",
47
- "test:unit": "node tests/run.mjs",
48
- "test:e2e": "node tests/e2e.mjs",
49
- "prepack": "npm run typecheck && npm test"
50
- },
51
- "peerDependencies": {
52
- "@earendil-works/pi-coding-agent": ">=0.84.4",
53
- "@earendil-works/pi-tui": "*",
54
- "typebox": "*"
55
- },
56
- "devDependencies": {
57
- "@earendil-works/pi-coding-agent": "^0.84.4",
58
- "@earendil-works/pi-tui": "^0.84.4",
59
- "@types/node": "^22.0.0",
60
- "typebox": "^1.0.17",
61
- "typescript": "^5.9.3"
62
- },
63
- "pi": {
64
- "extensions": [
65
- "./index.ts"
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 final message MUST use exactly these headings, in this order, as compact
27
- markdown:
28
-
29
- ```markdown
30
- ## Outcome
31
- ## Changes
32
- ## Verification
33
- ## Risks and open questions
34
- ```
35
-
36
- - **Outcome** — what was achieved (or why it could not be), 1–5 lines.
37
- - **Changes** — exact changed paths and a one-line description each; or "none".
38
- - **Verification** — the commands run and their observed results; or "none run — why".
39
- - **Risks and open questions** — residual risk, assumptions, follow-ups; or "none".
40
-
41
- Do not add other top-level headings. Do not include raw tool transcripts.
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 final message MUST use exactly these headings, in this order, as compact
31
- markdown:
32
-
33
- ```markdown
34
- ## Recommendation
35
- ## Evidence
36
- ## Sources
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":