@maheidem/pi-delegate 0.1.5 → 0.2.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/index.ts CHANGED
@@ -22,6 +22,9 @@ import {
22
22
  import { Text } from "@earendil-works/pi-tui";
23
23
 
24
24
  import { formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
25
+ import * as fsSync from "node:fs";
26
+ import { delegateVersion } from "./version.ts";
27
+ import { HandoffToolParams, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
25
28
  import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
26
29
  import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
27
30
  import { STRICT_OVERLAY, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
@@ -37,6 +40,8 @@ import type {
37
40
  } from "./types.ts";
38
41
  import { SettingsPanel, type PanelSnapshot, type PanelActionResult } from "./ui/settings-panel.ts";
39
42
  import { RunningView, type RunningViewState } from "./ui/running-view.ts";
43
+ import { PeekView } from "./ui/peek-view.ts";
44
+ import { FeedRing, feedEventsFromTranscript, renderFeedEvents } from "./transcript-feed.ts";
40
45
 
41
46
  /** Stable command-driven handoff custom message type (§6.4). */
42
47
  const HANDOFF_CUSTOM_TYPE = "delegate-handoff";
@@ -113,9 +118,62 @@ export function formatRunSummary(
113
118
  return out.join("\n");
114
119
  }
115
120
 
121
+ /**
122
+ * Child-mode surface: the delegated child gets EXACTLY ONE delegate tool —
123
+ * the mandatory structured `handoff`. The child's final report is a
124
+ * protocol step (schema-validated, retried on error, enforced by the
125
+ * runner), never free text the harness hopes has the right shape.
126
+ */
127
+ function registerChildHandoffTool(pi: ExtensionAPI): void {
128
+ pi.registerTool({
129
+ name: "handoff",
130
+ label: "Handoff",
131
+ description:
132
+ "MANDATORY final report for this delegated run. Your run does not complete until this tool " +
133
+ "has been called with a valid submission; free-text endings are rejected and you will be re-prompted. " +
134
+ "When terminated mid-work, call it immediately with outcome=partial.",
135
+ parameters: HandoffToolParams,
136
+ async execute(_toolCallId, params): Promise<{
137
+ content: Array<{ type: "text"; text: string }>;
138
+ details: { delegateHandoff?: HandoffSubmission; rejected?: boolean; errors?: string[] };
139
+ isError?: boolean;
140
+ }> {
141
+ const validation = validateHandoffSubmission(params);
142
+ if (!validation.ok) {
143
+ return {
144
+ content: [
145
+ {
146
+ type: "text" as const,
147
+ text:
148
+ "handoff REJECTED — fix every field listed below and call the handoff tool again:\n" +
149
+ validation.errors.map((e) => `- ${e}`).join("\n"),
150
+ },
151
+ ],
152
+ details: { rejected: true, errors: validation.errors },
153
+ isError: true,
154
+ };
155
+ }
156
+ const value = validation.value!;
157
+ return {
158
+ content: [
159
+ {
160
+ type: "text" as const,
161
+ text: `handoff accepted (${value.outcome}) — you may now end your turn. Do not write another final message.`,
162
+ },
163
+ ],
164
+ details: { delegateHandoff: value },
165
+ };
166
+ },
167
+ });
168
+ }
169
+
116
170
  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;
171
+ // 1. The child never reactivates the parent surface (POL: no recursion) —
172
+ // it registers ONLY the mandatory structured-handoff tool.
173
+ if (process.env.PI_DELEGATE_CHILD === "1") {
174
+ registerChildHandoffTool(pi);
175
+ return;
176
+ }
119
177
  // 2. Construct state — no child, no timers at load time.
120
178
  // PI_DELEGATE_AGENT_DIR is a test override; production uses getAgentDir().
121
179
  const agentDir = process.env.PI_DELEGATE_AGENT_DIR || getAgentDir();
@@ -168,6 +226,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
168
226
  source: "tool" | "command",
169
227
  ctx: ExtensionContext,
170
228
  timeoutMs?: number,
229
+ extras?: { model?: string; resumeFrom?: string },
171
230
  ): DelegateRequest => ({
172
231
  task,
173
232
  role,
@@ -178,6 +237,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
178
237
  projectTrusted: ctx.isProjectTrusted(),
179
238
  projectRoot: ctx.cwd ?? process.cwd(),
180
239
  ...(timeoutMs !== undefined ? { timeoutMs } : {}),
240
+ ...(extras?.model ? { model: extras.model } : {}),
241
+ ...(extras?.resumeFrom ? { resumeFrom: extras.resumeFrom } : {}),
181
242
  });
182
243
 
183
244
  const refreshDoctor = (ctx: ExtensionContext) => {
@@ -236,10 +297,21 @@ export default function delegateExtension(pi: ExtensionAPI) {
236
297
  : d.state.startsWith("timed_out") ? d.state.replace("_", " ")
237
298
  : d.state;
238
299
  const secs = Math.round(d.durationMs / 1000);
239
- const head = `[delegate ${d.runId} · ${d.role} · ${stateLabel} in ${secs}s]`;
300
+ const head =
301
+ `[delegate v${delegateVersion()} · ${d.runId} · ${d.role} · ${stateLabel} in ${secs}s` +
302
+ `${d.model ? ` · ${d.model}` : ""}${d.timeoutInfo ? ` · ${d.timeoutInfo}` : ""}]`;
240
303
  if (!res.ok) {
304
+ const parts = [head];
241
305
  const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
242
- return `${head}\nerror: ${err}\ntranscript: ${d.transcriptPath}`;
306
+ parts.push(`error: ${err}`);
307
+ // R2: the killed child's own account of its partial work.
308
+ if (res.details.partialHandoff) {
309
+ parts.push("", "partial handoff (captured at kill):", res.details.partialHandoff);
310
+ }
311
+ if (res.modelNote) parts.push(`note: ${res.modelNote}`);
312
+ parts.push(`transcript: ${d.transcriptPath}`);
313
+ if (d.sessionPath) parts.push(`session: ${d.sessionPath} (resumable via resumeFrom: ${d.runId})`);
314
+ return parts.join("\n");
243
315
  }
244
316
  const parts = [head, "", res.handoff];
245
317
  if (d.outputTruncated || d.stderrPath) {
@@ -268,7 +340,20 @@ export default function delegateExtension(pi: ExtensionAPI) {
268
340
  timeout: Type.Optional(Type.String({
269
341
  description:
270
342
  "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.",
343
+ "Use it when the subtask is expected to run longer than the configured default; it overrides the project/user config base. " +
344
+ "Effective inactivity = min(config, hard/2); a single tool call longer than that is killed unless the in-flight-tool budget covers it — " +
345
+ "for long validation/benchmark work set timeout at 2x the longest expected tool call.",
346
+ })),
347
+ model: Type.Optional(Type.String({
348
+ description:
349
+ "Optional child model pin as 'provider/model-id'. Without it the child silently inherits the parent's CURRENT model — " +
350
+ "if the parent switches models mid-session (e.g. a usage-limit fallback), children follow. Pin this for model-sensitive work.",
351
+ })),
352
+ resumeFrom: Type.Optional(Type.String({
353
+ description:
354
+ "Resume a prior run's durable child session: pass its runId. The new child re-enters that exact context " +
355
+ "(earlier turns included) with your task as the continuation prompt — no cold re-explanation. " +
356
+ "Works for runs whose receipt records a sessionPath (post-0.2.0) and whose session file still exists.",
272
357
  })),
273
358
  });
274
359
 
@@ -284,6 +369,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
284
369
  "Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
285
370
  "Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
286
371
  "Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
372
+ "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.",
373
+ "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).",
374
+ "For long validation/benchmark subtasks set timeout to at least 2x the longest expected single tool call.",
287
375
  "While delegation mode is active, all substantive work and verification must use delegate; the parent is coordination-only.",
288
376
  ],
289
377
  parameters: DelegateParams,
@@ -301,13 +389,17 @@ export default function delegateExtension(pi: ExtensionAPI) {
301
389
  };
302
390
  }
303
391
  }
304
- const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs);
392
+ const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs, {
393
+ model: typeof params.model === "string" && params.model.trim() ? params.model.trim() : undefined,
394
+ resumeFrom: typeof params.resumeFrom === "string" && params.resumeFrom.trim() ? params.resumeFrom.trim() : undefined,
395
+ });
305
396
  refreshDoctor(ctx);
306
397
  const hooks = {
307
398
  abortSignal: signal ?? undefined,
308
399
  onUpdate: (u: RunStreamUpdate) => {
400
+ const modelBit = u.model ? ` · ${u.model}` : "";
309
401
  onUpdate?.({
310
- content: [{ type: "text", text: `[delegate ${u.runId} · ${u.role} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]` }],
402
+ content: [{ type: "text", text: `[delegate v${delegateVersion()} ${u.runId} · ${u.role}${modelBit} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]` }],
311
403
  details: { runId: u.runId, phase: u.phase },
312
404
  });
313
405
  },
@@ -393,8 +485,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
393
485
  }
394
486
  };
395
487
 
396
- const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number): Promise<void> => {
397
- const request = buildRequest(task, role, "command", ctx, timeoutMs);
488
+ const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string }): Promise<void> => {
489
+ const request = buildRequest(task, role, "command", ctx, timeoutMs, extras);
398
490
  refreshDoctor(ctx);
399
491
  let lastText = `[delegate] starting ${role} run…`;
400
492
  const hooks = {
@@ -409,7 +501,20 @@ export default function delegateExtension(pi: ExtensionAPI) {
409
501
  role: request.role,
410
502
  phase: "starting",
411
503
  elapsedMs: 0,
412
- lastActions: [],
504
+ feedLines: [],
505
+ };
506
+ // Live feed: every child event lands in the ring; the panel renders
507
+ // the bounded tail on each host refresh (1 s + event-driven).
508
+ const feed = new FeedRing(120);
509
+ let feedStartMs = 0;
510
+ let hardMs: number | undefined;
511
+ const feedLines = (): string[] => {
512
+ if (feed.all().length === 0) return [];
513
+ return renderFeedEvents([...feed.all()], {
514
+ startMs: feedStartMs || Date.now(),
515
+ maxChars: 150,
516
+ maxEvents: 14,
517
+ });
413
518
  };
414
519
  const runPromise = app.run(request, {
415
520
  ...hooks,
@@ -419,18 +524,44 @@ export default function delegateExtension(pi: ExtensionAPI) {
419
524
  viewState.role = u.role;
420
525
  viewState.phase = u.phase;
421
526
  viewState.elapsedMs = u.elapsedMs;
422
- viewState.lastActions = u.lastActions;
527
+ viewState.model = u.model;
528
+ viewState.openTools = u.openTools;
529
+ viewState.turns = u.usage?.turns;
530
+ viewState.tokens = { input: u.usage?.input, output: u.usage?.output };
531
+ if (!feedStartMs) feedStartMs = Date.now() - u.elapsedMs;
532
+ },
533
+ onEvent: (event) => {
534
+ feed.push(event);
423
535
  },
424
536
  });
537
+ // Effective hard cap for the progress bar: per-run > project > user.
538
+ try {
539
+ const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
540
+ hardMs = request.timeoutMs ?? s.timeouts.hardMs;
541
+ } catch {
542
+ hardMs = undefined;
543
+ }
544
+ viewState.hardMs = hardMs;
545
+ let refreshTimer: ReturnType<typeof setInterval> | undefined;
425
546
  const outcome = await ctx.ui.custom<{ cancelled?: boolean } | undefined>(
426
- (tui, theme, keybindings, done) =>
427
- new RunningView({
547
+ (tui, theme, keybindings, done) => {
548
+ refreshTimer = setInterval(() => {
549
+ viewState.elapsedMs = feedStartMs ? Date.now() - feedStartMs : viewState.elapsedMs;
550
+ viewState.feedLines = feedLines();
551
+ tui.requestRender();
552
+ }, 1000);
553
+ return new RunningView({
428
554
  theme,
429
555
  keybindings,
430
- state: () => viewState,
556
+ state: () => {
557
+ viewState.feedLines = feedLines();
558
+ return viewState;
559
+ },
431
560
  done,
432
- }),
561
+ });
562
+ },
433
563
  );
564
+ if (refreshTimer) clearInterval(refreshTimer);
434
565
  if (outcome?.cancelled) {
435
566
  await app.cancel();
436
567
  say(ctx, `[delegate] cancellation requested; the run finalizes with its terminal receipt.`);
@@ -468,7 +599,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
468
599
 
469
600
  const statusText = (ctx: ExtensionContext): string => {
470
601
  const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
471
- const lines = ["[delegate]", `mode: ${s.modeEnabled ? "strict" : "normal"}`];
602
+ const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
472
603
  lines.push(`parent tools: ${s.modeEnabled ? "delegate only" : "normal active set"}`);
473
604
  lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
474
605
  if (s.lastRun) {
@@ -504,6 +635,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
504
635
  "/delegate research <task> research role",
505
636
  "/delegate <task> general-role shorthand",
506
637
  "/delegate cancel [run-id] cancel the active run",
638
+ "/delegate resume <run-id> <task> resume a prior run's child session",
507
639
  "/delegate inspect [run-id] inspect a run (default: recent/active)",
508
640
  "/delegate paths config + run store paths",
509
641
  "/delegate doctor diagnostics",
@@ -590,6 +722,70 @@ export default function delegateExtension(pi: ExtensionAPI) {
590
722
  }
591
723
  await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
592
724
  return;
725
+ case "peek": {
726
+ const id = intent.runId?.trim() || app.mostRecentRunId();
727
+ if (!id) {
728
+ say(ctx, "[delegate] no runs to peek at.", "warning");
729
+ return;
730
+ }
731
+ let meta;
732
+ try {
733
+ meta = app.inspect(id).metadata;
734
+ } catch {
735
+ say(ctx, `[delegate] unknown run '${id}'.`, "error");
736
+ return;
737
+ }
738
+ if (!fsSync.existsSync(meta.transcriptPath)) {
739
+ say(ctx, `[delegate] no transcript captured for ${id}.`, "warning");
740
+ return;
741
+ }
742
+ if (ctx.mode === "tui") {
743
+ await ctx.ui.custom<{ closed?: boolean } | undefined>((tui, theme, keybindings, done) => {
744
+ const state = () => {
745
+ let live = false;
746
+ try {
747
+ live = !["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(app.inspect(id).metadata.state);
748
+ } catch {
749
+ live = false;
750
+ }
751
+ const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
752
+ return {
753
+ title: `${id.slice(-16)} · ${meta.role}${meta.model ? ` · ${meta.model}` : ""} · ${meta.state}`,
754
+ summary: meta.transcriptPath,
755
+ lines: renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 150 }),
756
+ live,
757
+ };
758
+ };
759
+ // Live-follow refresh timer; cleared the moment the
760
+ // overlay closes (done wrapper) — never leaks.
761
+ let timer: ReturnType<typeof setInterval> | undefined;
762
+ const wrappedDone = (result: { closed?: boolean }) => {
763
+ if (timer) clearInterval(timer);
764
+ done(result);
765
+ };
766
+ const view = new PeekView({ theme, keybindings, state, done: wrappedDone });
767
+ timer = setInterval(() => tui.requestRender(), 1000);
768
+ return view;
769
+ });
770
+ } else {
771
+ const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
772
+ const lines = renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 200 });
773
+ say(
774
+ ctx,
775
+ `[delegate peek ${id} · ${meta.role} · ${meta.state}]\n${meta.transcriptPath}\n${lines.slice(-40).join("\n")}`,
776
+ );
777
+ }
778
+ return;
779
+ }
780
+ case "resume": {
781
+ const runId = intent.runId?.trim();
782
+ if (!runId || !intent.task) {
783
+ say(ctx, `[delegate] usage: /delegate resume <run-id> <continuation task...>`, "error");
784
+ return;
785
+ }
786
+ await runCommandForeground(intent.task, "general", ctx, intent.timeoutMs, { resumeFrom: runId });
787
+ return;
788
+ }
593
789
  case "invalid":
594
790
  say(ctx, `[delegate] unrecognized '${intent.token}'.\n${intent.usage}\n${helpText()}`, "error");
595
791
  return;
package/package.json CHANGED
@@ -1,68 +1,71 @@
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.1",
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
+ "transcript-feed.ts",
42
+ "roles/",
43
+ "ui/",
44
+ "README.md",
45
+ "LICENSE"
46
+ ],
47
+ "scripts": {
48
+ "typecheck": "tsc -p tsconfig.json",
49
+ "test": "node tests/run.mjs",
50
+ "test:unit": "node tests/run.mjs",
51
+ "test:e2e": "node tests/e2e.mjs",
52
+ "prepack": "npm run typecheck && npm test"
53
+ },
54
+ "peerDependencies": {
55
+ "@earendil-works/pi-coding-agent": ">=0.84.4",
56
+ "@earendil-works/pi-tui": "*",
57
+ "typebox": "*"
58
+ },
59
+ "devDependencies": {
60
+ "@earendil-works/pi-coding-agent": "^0.84.4",
61
+ "@earendil-works/pi-tui": "^0.84.4",
62
+ "@types/node": "^22.0.0",
63
+ "typebox": "^1.0.17",
64
+ "typescript": "^5.9.3"
65
+ },
66
+ "pi": {
67
+ "extensions": [
68
+ "./index.ts"
69
+ ]
70
+ }
68
71
  }
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; textHead?: string } }
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,29 @@ 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>;
164
+ const content = Array.isArray(result.content) ? (result.content as Array<Record<string, unknown>>) : [];
165
+ let textHead = "";
166
+ for (const b of content) {
167
+ if (b?.type === "text" && typeof b.text === "string" && b.text.trim()) {
168
+ textHead = b.text.trim().slice(0, 240);
169
+ break;
170
+ }
171
+ }
161
172
  return {
162
173
  kind: "tool_event",
163
174
  phase: "end",
175
+ id: typeof obj.toolCallId === "string" ? obj.toolCallId : undefined,
164
176
  toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
177
+ ...(result && typeof result === "object"
178
+ ? { result: { details: result.details, isError: result.isError === true, ...(textHead ? { textHead } : {}) } }
179
+ : {}),
165
180
  };
181
+ }
166
182
  case "agent_settled":
167
183
  return { kind: "agent_settled" };
168
184
  case "agent_end":