@xzzpig/pi-subagents 0.20.0 → 0.21.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.
Files changed (140) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -14,7 +14,7 @@ import type {
14
14
  ParallelHandoffManifest,
15
15
  } from "../../shared/types.ts";
16
16
  import { getAgentDir } from "../../shared/utils.ts";
17
- import { isTerminalParallelHandoffChildStatus } from "./parallel-handoff.ts";
17
+ import { isTerminalParallelHandoffChildStatus, readParallelHandoffManifest } from "./parallel-handoff.ts";
18
18
  import { MACHINE_DIFF_OPTIONS, validateWorktreePatchRepresentsCurrentWorktree } from "./worktree.ts";
19
19
 
20
20
  export const WORKTREE_CLEANUP_PLAN_VERSION = 1 as const;
@@ -72,6 +72,8 @@ export interface WorktreeCleanupPlan {
72
72
 
73
73
  export interface BuildWorktreeCleanupPlanInput {
74
74
  repo: string;
75
+ /** Internal maintenance seam: inspect only these paths with the same safety predicates. */
76
+ candidatePaths?: string[];
75
77
  handoffPath?: string;
76
78
  /** Internal test and migration seam for explicitly supplied handoff records. */
77
79
  handoffPaths?: string[];
@@ -99,6 +101,7 @@ interface GitWorktreeRecord {
99
101
  head: string;
100
102
  branch?: string;
101
103
  prunable?: string;
104
+ locked?: boolean;
102
105
  }
103
106
 
104
107
  interface ManifestMetadataRecord {
@@ -194,16 +197,16 @@ function comparablePath(candidate: string): string {
194
197
  return process.platform === "win32" ? normalized.toLowerCase() : normalized;
195
198
  }
196
199
 
197
- function samePath(left: string, right: string): boolean {
200
+ export function samePath(left: string, right: string): boolean {
198
201
  if (comparablePath(left) === comparablePath(right)) return true;
199
202
  if (process.platform !== "win32") return false;
200
203
  // Git for Windows and Node can spell the same temp directory with different
201
204
  // drive/short-name aliases. The directory identity is the final bounded
202
205
  // fallback; never accept aliases when the filesystem cannot prove identity.
203
206
  try {
204
- const leftStat = fs.statSync(left);
205
- const rightStat = fs.statSync(right);
206
- return leftStat.dev !== 0 && leftStat.ino !== 0 && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
207
+ const leftStat = fs.statSync(left, { bigint: true });
208
+ const rightStat = fs.statSync(right, { bigint: true });
209
+ return leftStat.dev !== 0n && leftStat.ino !== 0n && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
207
210
  } catch {
208
211
  return false;
209
212
  }
@@ -239,7 +242,7 @@ function validatePlanId(planId: string): string {
239
242
  return planId;
240
243
  }
241
244
 
242
- function resolveRepoRoot(repo: string): string {
245
+ export function resolveCleanupRepoRoot(repo: string): string {
243
246
  const requested = path.resolve(repo);
244
247
  const toplevel = runGitChecked(requested, ["rev-parse", "--show-toplevel"]);
245
248
  return realpathExisting(toplevel);
@@ -288,6 +291,7 @@ export function parseGitWorktreeList(raw: string): GitWorktreeRecord[] {
288
291
  if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length).trim();
289
292
  else if (line.startsWith("branch refs/heads/")) current.branch = line.slice("branch refs/heads/".length).trim();
290
293
  else if (line === "detached") delete current.branch;
294
+ else if (line === "locked" || line.startsWith("locked ")) current.locked = true;
291
295
  else if (line.startsWith("prunable ")) current.prunable = line.slice("prunable ".length).trim();
292
296
  }
293
297
  flush();
@@ -300,6 +304,10 @@ function listGitWorktrees(repoRoot: string): GitWorktreeRecord[] {
300
304
  return parseGitWorktreeList(result.stdout);
301
305
  }
302
306
 
307
+ export function isRegisteredCleanupWorktree(repoRoot: string, candidate: string): boolean {
308
+ return listGitWorktrees(repoRoot).some((tree) => samePath(tree.path, candidate));
309
+ }
310
+
303
311
  function readJsonFile(filePath: string): unknown {
304
312
  return JSON.parse(fs.readFileSync(filePath, "utf-8")) as unknown;
305
313
  }
@@ -313,11 +321,11 @@ function readManifest(manifestPath: string): ManifestReadResult {
313
321
  const stat = fs.lstatSync(manifestPath);
314
322
  if (stat.isSymbolicLink() || !stat.isFile()) return { error: `parallel handoff manifest is not a regular file: ${manifestPath}` };
315
323
  if (stat.size > MAX_METADATA_FILE_BYTES) return { error: `parallel handoff manifest exceeds the ${MAX_METADATA_FILE_BYTES}-byte limit: ${manifestPath}` };
316
- const parsed = readJsonFile(manifestPath);
317
- if (!isRecord(parsed) || parsed.version !== 1 || !Array.isArray(parsed.groups)) {
324
+ const parsed = readParallelHandoffManifest(manifestPath);
325
+ if (!parsed) {
318
326
  return { error: `invalid parallel handoff manifest version or groups: ${manifestPath}` };
319
327
  }
320
- return { manifest: parsed as unknown as ParallelHandoffManifest };
328
+ return { manifest: parsed };
321
329
  } catch (error) {
322
330
  const code = error && typeof error === "object" && "code" in error ? (error as NodeJS.ErrnoException).code : undefined;
323
331
  if (code === "ENOENT") return { error: `parallel handoff manifest not found: ${manifestPath}` };
@@ -423,11 +431,10 @@ function loadMetadata(input: BuildWorktreeCleanupPlanInput, repoRoot: string): {
423
431
  const discovered = discoverHandoffPaths(repoRoot, input);
424
432
  const records: ManifestMetadataRecord[] = [];
425
433
  const warnings = [...discovered.warnings];
426
- const explicitPath = input.handoffPath ? path.isAbsolute(input.handoffPath) ? path.resolve(input.handoffPath) : path.resolve(repoRoot, input.handoffPath) : undefined;
427
434
  for (const manifestPath of discovered.paths) {
428
435
  const result = readManifest(manifestPath);
429
436
  if (!result.manifest) {
430
- if (explicitPath && comparablePath(manifestPath) === comparablePath(explicitPath)) warnings.push(result.error!);
437
+ warnings.push(result.error!);
431
438
  continue;
432
439
  }
433
440
  const manifestRoot = resolveExistingPath(manifestPath);
@@ -526,7 +533,7 @@ function buildEntryBase(input: {
526
533
  metadata?: ManifestMetadataRecord;
527
534
  targetHead: string;
528
535
  }): WorktreeCleanupPlanEntry {
529
- const recordedBaseDir = path.dirname(input.path);
536
+ const recordedBaseDir = input.metadata?.task.recordedBaseDir;
530
537
  const patchPath = input.metadata ? metadataPatchPath(input.metadata) : undefined;
531
538
  return {
532
539
  path: input.path,
@@ -544,7 +551,7 @@ function buildEntryBase(input: {
544
551
  branch: input.branch,
545
552
  ...(input.git?.head ? { worktreeHead: input.git.head } : {}),
546
553
  ...(input.metadata?.group.baseCommit ? { baseCommit: input.metadata.group.baseCommit } : {}),
547
- recordedBaseDir,
554
+ ...(recordedBaseDir ? { recordedBaseDir } : {}),
548
555
  targetRef: input.targetHead,
549
556
  },
550
557
  };
@@ -626,8 +633,14 @@ function buildManagedEntry(input: {
626
633
  const extensionsDir = path.join(getAgentDir(), "extensions");
627
634
  if (pathInside(extensionsDir, pathInspection.realpath)) return blockedEntry(entry, "ineligible", "keep", `worktree real path is inside Pi extensions directory '${extensionsDir}'`);
628
635
  if (input.containmentInvalid || !pathInside(baseDir, pathInspection.realpath, true)) return blockedEntry(entry, "ineligible", "keep", `worktree real path is outside configured base directory '${baseDir}'`);
636
+ const recordedBaseDir = record.task.recordedBaseDir;
637
+ if (typeof recordedBaseDir !== "string" || !path.isAbsolute(recordedBaseDir)) return blockedEntry(entry, "unknown", "keep", "handoff metadata has no creation-time base directory proof");
638
+ // Compare the saved canonical string, without following a newly replaced ancestor.
639
+ const creationRelative = path.relative(recordedBaseDir, pathInspection.realpath);
640
+ if (!creationRelative || creationRelative === ".." || creationRelative.startsWith(`..${path.sep}`) || path.isAbsolute(creationRelative)) return blockedEntry(entry, "ineligible", "keep", `worktree real path is outside its creation-time recorded base directory '${recordedBaseDir}'`);
629
641
 
630
642
  if (rootPath === comparablePath(pathInspection.realpath)) return blockedEntry(entry, "ineligible", "keep", "worktree is the repository root");
643
+ if (git.locked) return blockedEntry(entry, "ineligible", "keep", "Git worktree is locked");
631
644
  if (!git.branch) return blockedEntry(entry, "unknown", "unknown", "detached worktrees have no metadata-recorded branch");
632
645
  if (record.task.branch !== git.branch) return blockedEntry(entry, "unknown", "unknown", `metadata branch '${record.task.branch}' does not match Git branch '${git.branch}'`);
633
646
  if (record.task.worktreeRemoved) return blockedEntry(entry, "stale", "unknown", "handoff metadata already records this worktree as removed");
@@ -646,6 +659,9 @@ function buildManagedEntry(input: {
646
659
  return blockedEntry(entry, "ineligible", "keep", "metadata-recorded branch is checked out at the repository root");
647
660
  }
648
661
 
662
+ const retainedSession = record.child.sessionPath ?? record.status?.steps?.[record.child.index]?.sessionFile ?? record.status?.sessionFile;
663
+ if (typeof retainedSession === "string" && retainedSession.trim()) return blockedEntry(entry, "ineligible", "keep", "retained child resume still has a recorded session dependency");
664
+
649
665
  const runState = inspectRunState(record, input.now, foregroundRunOwnership);
650
666
  if (runState.kind === "unknown") return blockedEntry(entry, "unknown", "unknown", runState.reason ?? "owning run state is unknown");
651
667
  if (runState.kind === "active") return blockedEntry(entry, "active", "keep", runState.reason ?? "owning run is active");
@@ -668,6 +684,10 @@ function buildManagedEntry(input: {
668
684
  entry.preconditions.statusDigest = status.digest;
669
685
  if (status.output && status.output.trim()) return blockedEntry(entry, "dirty", "keep", "worktree has uncommitted or untracked changes");
670
686
 
687
+ const ignored = runGit(worktreePath, ["ls-files", "--others", "--ignored", "--exclude-standard", "-z"]);
688
+ if (ignored.status !== 0) return blockedEntry(entry, "unknown", "unknown", `ignored-file inspection failed: ${gitFailure(ignored, "git ls-files")}`);
689
+ if (ignored.stdout) return blockedEntry(entry, "ineligible", "keep", "worktree contains ignored files; cleanup preserves them");
690
+
671
691
  const diff = runGit(worktreePath, ["diff", "--quiet", ...MACHINE_DIFF_OPTIONS, resolvedBase.value, "--"]);
672
692
  if (diff.status !== 0 && diff.status !== 1) return blockedEntry(entry, "unknown", "unknown", `git diff safety check failed: ${gitFailure(diff, "git diff")}`);
673
693
  const ancestor = runGit(repoRoot, ["merge-base", "--is-ancestor", git.head, targetHead]);
@@ -704,7 +724,7 @@ function buildManagedEntry(input: {
704
724
 
705
725
  entry.state = "safe";
706
726
  entry.decision = "remove";
707
- entry.willDeleteBranch = branchTipIsAncestor;
727
+ entry.willDeleteBranch = false;
708
728
  entry.reasons.push("extension-owned metadata, terminal run, contained clean worktree, and local divergence checks passed");
709
729
  if (!branchTipIsAncestor) entry.reasons.push("local branch tip is not an ancestor of target HEAD; future apply must retain the branch");
710
730
  return entry;
@@ -723,7 +743,7 @@ function buildMissingMetadataEntry(input: { record: ManifestMetadataRecord; targ
723
743
  return blockedEntry(entry, "stale", "unknown", "handoff metadata records a worktree that is not present in Git worktree state");
724
744
  }
725
745
 
726
- function contentPayload(plan: Omit<WorktreeCleanupPlan, "contentHash" | "planId" | "createdAt" | "expiresAt">): unknown {
746
+ export function worktreeCleanupContentPayload(plan: Omit<WorktreeCleanupPlan, "contentHash" | "planId" | "createdAt" | "expiresAt">): unknown {
727
747
  return {
728
748
  version: plan.version,
729
749
  repoRoot: plan.repoRoot,
@@ -741,7 +761,7 @@ function stableEntrySort(left: WorktreeCleanupPlanEntry, right: WorktreeCleanupP
741
761
 
742
762
  export function buildWorktreeCleanupPlan(input: BuildWorktreeCleanupPlanInput): WorktreeCleanupPlan {
743
763
  if (typeof input.repo !== "string" || !input.repo.trim()) throw new Error("worktree cleanup plan requires a repository path");
744
- const repoRoot = resolveRepoRoot(input.repo);
764
+ const repoRoot = resolveCleanupRepoRoot(input.repo);
745
765
  const now = input.now ?? Date.now();
746
766
  if (!Number.isFinite(now)) throw new Error("worktree cleanup plan timestamp must be finite");
747
767
  const baseDir = resolveCleanupBaseDir(repoRoot, input.worktreeBaseDir);
@@ -762,6 +782,7 @@ export function buildWorktreeCleanupPlan(input: BuildWorktreeCleanupPlanInput):
762
782
  const entries: WorktreeCleanupPlanEntry[] = [];
763
783
  const matchedMetadataRecords = new Set<ManifestMetadataRecord>();
764
784
  for (const git of linkedGit) {
785
+ if (input.candidatePaths && !input.candidatePaths.some((candidate) => samePath(candidate, git.path))) continue;
765
786
  const records = metadataByPath.get(comparablePath(git.path)) ?? (git.branch
766
787
  ? metadata.records.filter((record) => record.task.branch === git.branch && samePath(metadataRecordPath(record), git.path))
767
788
  : []);
@@ -807,7 +828,7 @@ export function buildWorktreeCleanupPlan(input: BuildWorktreeCleanupPlanInput):
807
828
  pruneCandidates,
808
829
  ...(warnings.length ? { warnings: [...new Set(warnings)].sort() } : {}),
809
830
  };
810
- const contentHash = sha256(JSON.stringify(contentPayload(basePlan)));
831
+ const contentHash = sha256(JSON.stringify(worktreeCleanupContentPayload(basePlan)));
811
832
  const planId = validatePlanId(input.planId ?? randomUUID());
812
833
  return {
813
834
  ...basePlan,
@@ -837,7 +858,7 @@ function formatPlanEntry(entry: WorktreeCleanupPlanEntry): string {
837
858
  export function formatWorktreeCleanupPlan(created: CreatedWorktreeCleanupPlan): string {
838
859
  const { plan, planPath } = created;
839
860
  const removable = plan.entries.filter((entry) => entry.decision === "remove");
840
- const branches = removable.filter((entry) => entry.willDeleteBranch === true);
861
+
841
862
  const kept = plan.entries.filter((entry) => entry.decision === "keep");
842
863
  const unknown = plan.entries.filter((entry) => entry.decision === "unknown");
843
864
  const section = (title: string, entries: WorktreeCleanupPlanEntry[], empty: string): string[] => [
@@ -852,7 +873,7 @@ export function formatWorktreeCleanupPlan(created: CreatedWorktreeCleanupPlan):
852
873
  "",
853
874
  ...section("Will remove", removable, "none"),
854
875
  "",
855
- ...section("Will delete local branches", branches, "none (plan-only mode; no branch will be deleted)"),
876
+ "Local branches: all retained, including after apply.",
856
877
  "",
857
878
  ...section("Will keep, with reasons", kept, "none"),
858
879
  "",
@@ -864,6 +885,7 @@ export function formatWorktreeCleanupPlan(created: CreatedWorktreeCleanupPlan):
864
885
  "",
865
886
  `Plan saved: ${planPath}`,
866
887
  "Plan-only mode: no worktrees or branches were removed.",
888
+ `Apply this reviewed plan: subagent({ action: "worktree.cleanup", options: { mode: "apply", repo: ${JSON.stringify(plan.repoRoot)}, planId: ${JSON.stringify(plan.planId)} } })`,
867
889
  ];
868
890
  return lines.join("\n");
869
891
  }
@@ -0,0 +1,29 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { tryLease } from "../../shared/file-lease.ts";
5
+
6
+ export function withHandoffWriteLock<T>(manifestPath: string, action: () => T): T {
7
+ const requested = path.resolve(manifestPath);
8
+ fs.mkdirSync(path.dirname(requested), { recursive: true });
9
+ const absolute = path.join(fs.realpathSync.native(path.dirname(requested)), path.basename(requested));
10
+ const release = tryLease(`${absolute}.write-lock`);
11
+ if (!release) throw new Error(`Handoff is being updated or cleaned: ${absolute}. Retry after the current operation completes.`);
12
+ try { return action(); } finally { release(); }
13
+ }
14
+
15
+ export async function withRepositoryWorktreeLock<T>(repo: string, action: () => T | Promise<T>, options: { signal?: AbortSignal; waitMs?: number } = {}): Promise<T> {
16
+ const git = spawnSync("git", ["-C", repo, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf-8", windowsHide: true });
17
+ if (git.status !== 0) throw new Error(git.error?.message || git.stderr.trim() || "Cannot resolve Git common directory.");
18
+ const lockPath = path.join(fs.realpathSync(git.stdout.trim()), "pi-subagents-worktree.lock");
19
+ const deadline = Date.now() + (options.waitMs ?? 2_000);
20
+ while (true) {
21
+ options.signal?.throwIfAborted();
22
+ const release = tryLease(lockPath);
23
+ if (release) {
24
+ try { return await action(); } finally { release(); }
25
+ }
26
+ if (Date.now() >= deadline) throw new Error("Repository worktree maintenance is busy; retry later.");
27
+ await new Promise<void>((resolve) => setTimeout(resolve, 25));
28
+ }
29
+ }
@@ -57,6 +57,8 @@ export interface WorktreeSetup {
57
57
  }
58
58
 
59
59
  export interface WorktreeInfo {
60
+ /** Canonical parent captured at allocation; never re-resolve this evidence later. */
61
+ recordedBaseDir?: string;
60
62
  path: string;
61
63
  agentCwd: string;
62
64
  branch: string;
@@ -80,6 +82,7 @@ export interface WorktreeDiff {
80
82
  }
81
83
 
82
84
  export interface WorktreeCleanupTask {
85
+ recordedBaseDir?: string;
83
86
  index: number;
84
87
  path: string;
85
88
  branch: string;
@@ -945,9 +948,11 @@ async function createNativeWorktree(
945
948
  if (branch.status !== 1 || pathExists) throw new Error(`worktree path or branch already exists: ${worktreePath}, ${naming.requestedBranch}`);
946
949
  tx.attempt(index, naming.requestedBranch, worktreePath);
947
950
  ensureProjectWorktreeDir(dedicatedRoot, toplevel);
951
+ const recordedBaseDir = normalizeComparableCwd(path.dirname(worktreePath));
948
952
  await tx.git(toplevel, ["worktree", "add", worktreePath, "-b", naming.requestedBranch, baseCommit]);
949
953
  const worktree: WorktreeInfo = {
950
954
  path: worktreePath,
955
+ recordedBaseDir,
951
956
  agentCwd: worktreePath,
952
957
  branch: naming.requestedBranch,
953
958
  index,
@@ -1026,6 +1031,7 @@ async function createWorktrunkWorktree(
1026
1031
  if (returnedHead !== baseCommit) throw new Error("Worktrunk provisioning returned a worktree at a different base commit");
1027
1032
  const worktree: WorktreeInfo = {
1028
1033
  path: worktreePath,
1034
+ recordedBaseDir: normalizeComparableCwd(path.dirname(worktreePath)),
1029
1035
  agentCwd: cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath,
1030
1036
  branch: naming.requestedBranch,
1031
1037
  index,
@@ -1189,6 +1195,7 @@ function cleanupSingleWorktree(
1189
1195
  branch: worktree.branch,
1190
1196
  ...(worktree.provider ? { provider: worktree.provider } : {}),
1191
1197
  ...(worktree.naming ? { naming: worktree.naming } : {}),
1198
+ ...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
1192
1199
  worktreeRemoved: false,
1193
1200
  branchRemoved: false,
1194
1201
  preserved: true,
@@ -1213,6 +1220,7 @@ function cleanupSingleWorktree(
1213
1220
  branch: worktree.branch,
1214
1221
  ...(worktree.provider ? { provider: worktree.provider } : {}),
1215
1222
  ...(worktree.naming ? { naming: worktree.naming } : {}),
1223
+ ...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
1216
1224
  worktreeRemoved: false,
1217
1225
  branchRemoved: false,
1218
1226
  preserved: true,
@@ -1248,6 +1256,7 @@ function cleanupSingleWorktree(
1248
1256
  branch: worktree.branch,
1249
1257
  ...(worktree.provider ? { provider: worktree.provider } : {}),
1250
1258
  ...(worktree.naming ? { naming: worktree.naming } : {}),
1259
+ ...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
1251
1260
  worktreeRemoved: false,
1252
1261
  branchRemoved: false,
1253
1262
  preserved: true,
@@ -1269,6 +1278,7 @@ function cleanupSingleWorktree(
1269
1278
  branch: worktree.branch,
1270
1279
  ...(worktree.provider ? { provider: worktree.provider } : {}),
1271
1280
  ...(worktree.naming ? { naming: worktree.naming } : {}),
1281
+ ...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
1272
1282
  worktreeRemoved: false,
1273
1283
  branchRemoved: false,
1274
1284
  preserved: true,
@@ -1298,6 +1308,7 @@ function cleanupSingleWorktree(
1298
1308
  branch: worktree.branch,
1299
1309
  ...(worktree.provider ? { provider: worktree.provider } : {}),
1300
1310
  ...(worktree.naming ? { naming: worktree.naming } : {}),
1311
+ ...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
1301
1312
  worktreeRemoved,
1302
1313
  branchRemoved,
1303
1314
  ...(errors.length ? { errors } : {}),
@@ -1337,7 +1348,7 @@ async function compensateSetup(tx: SetupTransaction): Promise<WorktreeCleanupRep
1337
1348
  }
1338
1349
  const known = setup.worktrees.find((worktree) => worktree.index === attempt.index);
1339
1350
  const task: WorktreeCleanupTask = { index: attempt.index, path: attempt.path, branch: attempt.branch,
1340
- provider: known?.provider ?? "native", naming: known?.naming, worktreeRemoved: false, branchRemoved: false };
1351
+ provider: known?.provider ?? "native", naming: known?.naming, recordedBaseDir: known?.recordedBaseDir, worktreeRemoved: false, branchRemoved: false };
1341
1352
  report.tasks.push(task);
1342
1353
  try {
1343
1354
  if (normalizeComparableCwd(attempt.path) === normalizeComparableCwd(setup.cwd)) throw new Error("Refusing source-checkout removal");
@@ -39,7 +39,8 @@ function tempBaseName(filePath: string, pid: number, nowMs: number, randomId: st
39
39
  return `.${createHash("sha256").update(path.basename(filePath)).digest("hex")}${suffix}`;
40
40
  }
41
41
 
42
- export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (filePath: string, payload: object) => void {
42
+ /** `beforeRename` runs after the payload is written to its temporary file and before it appears at `filePath`. */
43
+ export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (filePath: string, payload: object, beforeRename?: () => void) => void {
43
44
  const fsImpl = options.fs ?? fs;
44
45
  const now = options.now ?? Date.now;
45
46
  const pid = options.pid ?? process.pid;
@@ -52,7 +53,7 @@ export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (
52
53
  const renameRetryDelaysMs = retryRenameErrors ? retryDelaysMs : [];
53
54
  const directoryRetryDelaysMs = retryDirectoryErrors ? retryDelaysMs : [];
54
55
  const wait = options.wait ?? waitForFileSystemRetry;
55
- return (filePath: string, payload: object): void => {
56
+ return (filePath: string, payload: object, beforeRename?: () => void): void => {
56
57
  runFileSystemOperationWithRetry(() => {
57
58
  fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
58
59
  }, { retryDelaysMs: directoryRetryDelaysMs, wait });
@@ -63,6 +64,7 @@ export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (
63
64
  let writeError: unknown;
64
65
  try {
65
66
  fsImpl.writeFileSync(tempPath, JSON.stringify(payload, null, 2), mode === undefined ? "utf-8" : { encoding: "utf-8", mode });
67
+ beforeRename?.();
66
68
  renameWithRetry(fsImpl, tempPath, filePath, renameRetryDelaysMs, wait);
67
69
  } catch (error) {
68
70
  writeError = error;
@@ -0,0 +1,33 @@
1
+ export function editDistance(left: string, right: string): number {
2
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
3
+ for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
4
+ let diagonal = previous[0]!;
5
+ previous[0] = leftIndex;
6
+ for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
7
+ const above = previous[rightIndex]!;
8
+ previous[rightIndex] = left[leftIndex - 1] === right[rightIndex - 1]
9
+ ? diagonal
10
+ : Math.min(diagonal, above, previous[rightIndex - 1]!) + 1;
11
+ diagonal = above;
12
+ }
13
+ }
14
+ return previous[right.length]!;
15
+ }
16
+
17
+ export function hasSingleAdjacentTransposition(left: string, right: string): boolean {
18
+ if (left.length !== right.length) return false;
19
+ const mismatch = [...left].findIndex((character, index) => character !== right[index]);
20
+ return mismatch >= 0
21
+ && left[mismatch] === right[mismatch + 1]
22
+ && left[mismatch + 1] === right[mismatch]
23
+ && left.slice(mismatch + 2) === right.slice(mismatch + 2);
24
+ }
25
+
26
+ /** The closest candidate that is a likely typo of `requested`, compared case-insensitively. */
27
+ export function closestMatch(requested: string, candidates: Iterable<string>): string | undefined {
28
+ const lower = requested.toLowerCase();
29
+ return [...candidates]
30
+ .map((candidate) => ({ candidate, distance: editDistance(lower, candidate.toLowerCase()) }))
31
+ .filter(({ candidate, distance }) => distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(lower, candidate.toLowerCase()))
32
+ .sort((left, right) => left.distance - right.distance || left.candidate.localeCompare(right.candidate))[0]?.candidate;
33
+ }
@@ -0,0 +1,74 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+ import { waitForFileSystemRetry } from "./file-system-retry.ts";
7
+
8
+ type Owner = { token: string; pid: number; hostname: string; processStart?: string };
9
+
10
+ function startIdentity(pid: number): string | undefined {
11
+ if (process.platform !== "linux") return undefined;
12
+ try {
13
+ const raw = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
14
+ return raw.slice(raw.lastIndexOf(")") + 1).trim().split(/\s+/)[19];
15
+ } catch { return undefined; }
16
+ }
17
+
18
+ function readOwner(lockPath: string): Owner | undefined {
19
+ try {
20
+ const owner = JSON.parse(fs.readFileSync(path.join(lockPath, "owner.json"), "utf-8"));
21
+ if ((typeof owner.token !== "string" || !/^[A-Za-z0-9-]{1,64}$/.test(owner.token)) || typeof owner.hostname !== "string" || !Number.isSafeInteger(owner.pid) || owner.pid <= 0) return undefined;
22
+ return owner;
23
+ } catch { return undefined; }
24
+ }
25
+
26
+ function deadOwner(owner: Owner): boolean {
27
+ if (owner.hostname !== os.hostname()) return false;
28
+ try { process.kill(owner.pid, 0); }
29
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
30
+ const current = startIdentity(owner.pid);
31
+ return owner.processStart !== undefined && current !== undefined && owner.processStart !== current;
32
+ }
33
+
34
+ /** Unknown owners and live processes are never evicted merely because a lock is old. */
35
+ export function tryLease(lockPath: string): (() => void) | undefined {
36
+ const owner: Owner = { token: randomUUID(), pid: process.pid, hostname: os.hostname(), processStart: startIdentity(process.pid) };
37
+ try { fs.mkdirSync(lockPath, { mode: 0o700 }); }
38
+ catch (error) {
39
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
40
+ const previous = readOwner(lockPath);
41
+ if (!previous || !deadOwner(previous)) return undefined;
42
+ // Retain the nonempty old directory as a fence: a delayed reclaimer of
43
+ // this token cannot rename a replacement lease over that destination.
44
+ const retired = `${lockPath}.retired-${previous.token}`;
45
+ try { fs.renameSync(lockPath, retired); }
46
+ catch (error) {
47
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" || readOwner(retired)?.token === previous.token) return undefined;
48
+ throw error;
49
+ }
50
+ if (readOwner(retired)?.token !== previous.token) throw new Error(`Retired lock owner changed during recovery: ${lockPath}`);
51
+ return tryLease(lockPath);
52
+ }
53
+ try { fs.writeFileSync(path.join(lockPath, "owner.json"), JSON.stringify(owner), { flag: "wx", mode: 0o600 }); }
54
+ catch (error) { fs.rmSync(lockPath, { recursive: true, force: true }); throw error; }
55
+ return () => {
56
+ if (readOwner(lockPath)?.token === owner.token) fs.rmSync(lockPath, { recursive: true });
57
+ };
58
+ }
59
+
60
+ /** Hold a lease beside `filePath` for a short synchronous update, waiting at most `waitMs` for another owner. */
61
+ export function withFileLease<T>(filePath: string, action: () => T, waitMs = 200): T {
62
+ const requested = path.resolve(filePath);
63
+ const absolute = path.join(fs.realpathSync.native(path.dirname(requested)), path.basename(requested));
64
+ const lockPath = `${absolute}.write-lock`;
65
+ const deadline = performance.now() + waitMs;
66
+ let release = tryLease(lockPath);
67
+ while (!release) {
68
+ const remaining = deadline - performance.now();
69
+ if (remaining <= 0) throw new Error(`Timed out waiting for another process to finish updating ${absolute}.`);
70
+ waitForFileSystemRetry(Math.min(10, remaining));
71
+ release = tryLease(lockPath);
72
+ }
73
+ try { return action(); } finally { release(); }
74
+ }
@@ -34,13 +34,9 @@ export function formatContextUsage(usage: Pick<TokenUsage, "window" | "windowPea
34
34
 
35
35
  export function formatModelThinking(model?: string, thinking?: string): string {
36
36
  const parsed = model ? splitKnownThinkingSuffix(model) : undefined;
37
- let displayModel = parsed?.baseModel ?? model;
37
+ const displayModel = parsed?.baseModel ?? model;
38
38
  const explicitThinking = THINKING_LEVELS.find((level) => level === thinking?.trim());
39
39
  const displayThinking = parsed?.thinkingSuffix ? parsed.thinkingSuffix.slice(1) : explicitThinking;
40
- if (displayModel) {
41
- const slashIdx = displayModel.lastIndexOf("/");
42
- if (slashIdx !== -1) displayModel = displayModel.slice(slashIdx + 1);
43
- }
44
40
  return [displayModel, displayThinking ? `thinking ${displayThinking}` : undefined].filter(Boolean).join(" · ");
45
41
  }
46
42
 
@@ -80,6 +80,28 @@ export function splitKnownThinkingSuffix(model: string): { baseModel: string; th
80
80
  };
81
81
  }
82
82
 
83
+ /**
84
+ * Combine an observed model id with the provider that served it into `provider/id`.
85
+ * When the registry is available a known id resolves to its canonical `fullId`, so a
86
+ * provider-local id that repeats its provider (OpenRouter's `openrouter/auto-beta`,
87
+ * full id `openrouter/openrouter/auto-beta`) keeps that full form. Without the
88
+ * registry, an id already qualified for this provider is returned unchanged.
89
+ */
90
+ export function qualifyModelWithProvider(
91
+ model: string | undefined,
92
+ provider: string | undefined,
93
+ availableModels?: ReadonlyArray<Pick<ModelInfo, "provider" | "id" | "fullId">>,
94
+ ): string | undefined {
95
+ if (!model) return undefined;
96
+ if (!provider) return model;
97
+ const exactFullId = availableModels?.find((entry) => entry.provider === provider && entry.fullId === model);
98
+ if (exactFullId) return exactFullId.fullId;
99
+ const idMatch = availableModels?.find((entry) => entry.provider === provider && entry.id === model);
100
+ if (idMatch) return idMatch.fullId;
101
+ if (model.startsWith(`${provider}/`)) return model;
102
+ return `${provider}/${model}`;
103
+ }
104
+
83
105
  export function findModelInfo(model: string | undefined, availableModels: ModelInfo[] | undefined, preferredProvider?: string): ModelInfo | undefined {
84
106
  if (!model || !availableModels || availableModels.length === 0) return undefined;
85
107
  const { baseModel } = splitKnownThinkingSuffix(model);
@@ -0,0 +1,17 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const packagePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json");
6
+
7
+ export function readInstalledPackageVersion(): string {
8
+ const parsed = JSON.parse(fs.readFileSync(packagePath, "utf-8")) as { version?: unknown };
9
+ if (typeof parsed.version !== "string" || !parsed.version.trim()) {
10
+ throw new Error(`Invalid package version in '${packagePath}'.`);
11
+ }
12
+ return parsed.version;
13
+ }
14
+
15
+ // Node keeps an imported module for the life of the process, so this stays the
16
+ // version first loaded even after an in-place update and /reload.
17
+ export const loadedPackageVersion = readInstalledPackageVersion();
@@ -0,0 +1,79 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export const PARENT_WAKE_TEXT = "Inspect subagent updates above. Answer pending supervisor requests within your authority. For completed work, read saved results and resume the already-authorized parent task, or report completion. If approval is required, explicitly ask the user. Do not silently yield, rerun completed work, or infer new authorization.";
4
+ // A handled or failed wake prompt emits no agent_start. Past this deadline an idle parent's
5
+ // wake counts as abandoned: its notices are already in the session, only the turn is lost.
6
+ const WAKE_PENDING_MS = 10_000;
7
+
8
+ // Reload replaces extension instances, not Pi's session manager or a wake prompt in preflight.
9
+ // The key and shape are shared with pi-intercom's idle wake: Pi marks a run active only after the
10
+ // prompt's async preflight, so a second extension's wake sent in that gap throws in agent.prompt().
11
+ type WakeReservation = { sessionId: string; sentAt?: number };
12
+ const reservationsSymbol = Symbol.for("pi.idle-wake.v1");
13
+ const wakeGlobal = globalThis as typeof globalThis & { [reservationsSymbol]?: WeakMap<object, WakeReservation> };
14
+ const reservations = wakeGlobal[reservationsSymbol] ?? (wakeGlobal[reservationsSymbol] = new WeakMap<object, WakeReservation>());
15
+
16
+ export interface ParentWake {
17
+ /**
18
+ * pi.sendMessage, except that a turn-triggering message to an idle parent is appended and the
19
+ * turn is started with sendUserMessage. Pi starts a sendMessage-triggered run without
20
+ * before_agent_start (earendil-works/pi#5581), so that run drops every hook-set prompt section.
21
+ * Returns true when the message was appended that way: Pi emits no extension message_start for it.
22
+ */
23
+ sendMessage(...args: Parameters<ExtensionAPI["sendMessage"]>): boolean;
24
+ /** True from an idle wake until its run starts or the session shuts down. Past the deadline it holds only while the parent is busy, which may still be the wake's preflight (for example compacting). */
25
+ isPending(): boolean;
26
+ bindSession(ctx: Pick<ExtensionContext, "isIdle" | "sessionManager">): void;
27
+ agentStarted(): void;
28
+ sessionShutdown(reason: string | undefined): void;
29
+ }
30
+
31
+ export function createParentWake(pi: Pick<ExtensionAPI, "sendMessage" | "sendUserMessage">, now: () => number = Date.now): ParentWake {
32
+ let ctx!: Pick<ExtensionContext, "isIdle">;
33
+ // Captured at bind: Pi's ctx throws once stale, which it can be by session_shutdown.
34
+ let session: { manager: object; id: string } | undefined;
35
+ // Look the reservation up on every access: another extension may have created this session's entry.
36
+ const reservation = (): WakeReservation => {
37
+ // Pi can shut an extension down before session_start binds it; an unbound wake reserved nothing.
38
+ if (!session) return { sessionId: "" };
39
+ const current = reservations.get(session.manager);
40
+ if (current?.sessionId === session.id) return current;
41
+ const next = { sessionId: session.id };
42
+ reservations.set(session.manager, next);
43
+ return next;
44
+ };
45
+ const reserved = () => {
46
+ const { sentAt } = reservation();
47
+ return sentAt !== undefined && now() - sentAt < WAKE_PENDING_MS;
48
+ };
49
+ return {
50
+ sendMessage(message, options) {
51
+ if (options?.triggerTurn !== true) {
52
+ pi.sendMessage(message, options);
53
+ return false;
54
+ }
55
+ if (!ctx.isIdle()) {
56
+ pi.sendMessage(message, options);
57
+ return false;
58
+ }
59
+ pi.sendMessage(message, { triggerTurn: false });
60
+ if (!reserved()) {
61
+ reservation().sentAt = now();
62
+ // Steer queues the wake if another prompt starts the run first.
63
+ pi.sendUserMessage(PARENT_WAKE_TEXT, { deliverAs: "steer" });
64
+ }
65
+ return true;
66
+ },
67
+ isPending: () => reservation().sentAt !== undefined && (reserved() || !ctx.isIdle()),
68
+ bindSession(context) {
69
+ ctx = context;
70
+ session = { manager: context.sessionManager, id: context.sessionManager.getSessionId() };
71
+ },
72
+ agentStarted() {
73
+ reservation().sentAt = undefined;
74
+ },
75
+ sessionShutdown(reason) {
76
+ if (reason !== "reload") reservation().sentAt = undefined;
77
+ },
78
+ };
79
+ }
@@ -6,6 +6,7 @@ import type { TextContent } from "@earendil-works/pi-ai";
6
6
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
7
  import { resolveModelCandidate } from "../runs/shared/model-resolution.ts";
8
8
  import { splitKnownThinkingSuffix, toModelInfo } from "./model-info.ts";
9
+ import { opencodeSessionHeaders } from "./opencode-session-headers.ts";
9
10
  import type { ForkContextConfig } from "./types.ts";
10
11
 
11
12
  const MAX_INHERITED_SESSION_BYTES = 64 * 1024;
@@ -421,7 +422,7 @@ function splitProviderModel(value: string): { provider: string; id: string } | u
421
422
  }
422
423
 
423
424
  export async function createPrunedForkSessionWriter(
424
- ctx: Pick<ExtensionContext, "modelRegistry" | "model">,
425
+ ctx: Pick<ExtensionContext, "modelRegistry" | "model" | "sessionManager">,
425
426
  config: ForkContextConfig | undefined,
426
427
  signal?: AbortSignal,
427
428
  ): Promise<(sessionFile: string) => Promise<void>> {
@@ -435,6 +436,9 @@ export async function createPrunedForkSessionWriter(
435
436
  if (!named) throw new Error(`Pruned fork model '${config.model}' must resolve to provider/model.`);
436
437
  const model = ctx.modelRegistry.find(named.provider, named.id);
437
438
  if (!model) throw new Error(`Pruned fork model '${config.model}' was not found as '${baseModel}'.`);
439
+ // OpenCode rejects requests without its session header (400 MissingSessionID).
440
+ const sessionId = ctx.sessionManager.getSessionId();
441
+ const sessionHeaders = opencodeSessionHeaders(model, sessionId);
438
442
 
439
443
  let sharedSummary: Promise<string> | undefined;
440
444
  const summarize: SummaryFunction = async (payload) => {
@@ -445,6 +449,8 @@ export async function createPrunedForkSessionWriter(
445
449
  }, {
446
450
  maxTokens: Math.min(MAX_SUMMARY_TOKENS, typeof model.maxTokens === "number" && model.maxTokens > 0 ? model.maxTokens : MAX_SUMMARY_TOKENS),
447
451
  signal,
452
+ sessionId,
453
+ ...(sessionHeaders ? { headers: sessionHeaders } : {}),
448
454
  }).result();
449
455
  if (response.stopReason === "error" || response.stopReason === "aborted") {
450
456
  throw new Error(`Pruned fork summarization stopped with ${response.stopReason}${response.errorMessage ? `: ${response.errorMessage}` : ""}`);