@xzzpig/pi-subagents 0.19.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 (153) hide show
  1. package/CHANGELOG.md +214 -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 +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  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 +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -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 +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -1,7 +1,3 @@
1
- import type { EntryRenderOptions, MessageRenderOptions, Theme } from "@earendil-works/pi-coding-agent";
2
- import { truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
3
- import { safeTerminalText } from "../shared/display-text.ts";
4
-
5
1
  export const SUPERVISOR_REQUEST_MESSAGE_TYPE = "subagent_supervisor_request";
6
2
  export const SUPERVISOR_REPLY_ENTRY_TYPE = "subagent_supervisor_reply";
7
3
 
@@ -32,68 +28,10 @@ export interface SupervisorReplyEntryData {
32
28
  createdAt: number;
33
29
  }
34
30
 
35
- interface SupervisorMessageLike {
36
- content: unknown;
37
- details?: unknown;
38
- }
39
-
40
- interface SupervisorEntryLike {
41
- data?: unknown;
42
- }
43
-
44
- const MAX_FIELD_CHARS = 512;
45
- const MAX_BODY_CHARS = 8_000;
46
- const MAX_INTERVIEW_CHARS = 4_000;
47
- const MAX_RENDER_LINES = 36;
48
- const TRUNCATION_MARKER = "[truncated]";
49
-
50
31
  export function supervisorReplyHint(requestId: string): string {
51
32
  return `subagent_supervisor({ action: "reply", replyTo: "${requestId}", message: "..." })`;
52
33
  }
53
34
 
54
- function boundedText(value: string, maxChars: number): string {
55
- const safe = safeTerminalText(value);
56
- if (safe.length <= maxChars) return safe;
57
- const prefixLength = Math.max(0, maxChars - TRUNCATION_MARKER.length - 1);
58
- let prefix = "";
59
- for (const character of safe) {
60
- if (prefix.length + character.length > prefixLength) break;
61
- prefix += character;
62
- }
63
- return `${prefix} ${TRUNCATION_MARKER}`;
64
- }
65
-
66
- function displayText(value: string, maxChars: number, expanded: boolean): string {
67
- return expanded ? safeTerminalText(value) : boundedText(value, maxChars);
68
- }
69
-
70
- function boundedField(value: unknown, fallback = "unknown"): string {
71
- return boundedText(typeof value === "string" ? value : value === undefined ? fallback : String(value), MAX_FIELD_CHARS);
72
- }
73
-
74
- function contentText(content: unknown): string {
75
- if (typeof content === "string") return content;
76
- if (!Array.isArray(content)) return "";
77
- return content
78
- .map((part) => {
79
- if (!part || typeof part !== "object") return "";
80
- const text = (part as { text?: unknown }).text;
81
- return typeof text === "string" ? text : "";
82
- })
83
- .filter(Boolean)
84
- .join("\n");
85
- }
86
-
87
- function interviewText(interview: unknown, expanded: boolean): string {
88
- let serialized: string;
89
- try {
90
- serialized = JSON.stringify(interview, null, 2) ?? String(interview);
91
- } catch {
92
- serialized = "[unavailable]";
93
- }
94
- return displayText(serialized, MAX_INTERVIEW_CHARS, expanded);
95
- }
96
-
97
35
  function isRecord(value: unknown): value is Record<string, unknown> {
98
36
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
99
37
  }
@@ -106,7 +44,7 @@ function optionalString(value: unknown): boolean {
106
44
  return value === undefined || typeof value === "string";
107
45
  }
108
46
 
109
- function requestDetails(value: unknown): SupervisorRequestMessageDetails | undefined {
47
+ export function parseSupervisorRequestDetails(value: unknown): SupervisorRequestMessageDetails | undefined {
110
48
  if (!isRecord(value)) return undefined;
111
49
  if (!optionalString(value.id) || !optionalString(value.requestId) || !optionalString(value.replyHint) || !optionalString(value.requestBody) || !optionalString(value.runId) || !optionalString(value.agent) || !optionalString(value.childTarget)) return undefined;
112
50
  if (value.reason !== undefined && !isSupervisorReason(value.reason)) return undefined;
@@ -115,7 +53,7 @@ function requestDetails(value: unknown): SupervisorRequestMessageDetails | undef
115
53
  return value;
116
54
  }
117
55
 
118
- function replyData(value: unknown): SupervisorReplyEntryData | undefined {
56
+ export function parseSupervisorReplyData(value: unknown): SupervisorReplyEntryData | undefined {
119
57
  if (!isRecord(value)) return undefined;
120
58
  if (typeof value.requestId !== "string" || typeof value.runId !== "string" || typeof value.agent !== "string" || typeof value.message !== "string") return undefined;
121
59
  if (value.reason !== undefined && !isSupervisorReason(value.reason)) return undefined;
@@ -132,113 +70,3 @@ function replyData(value: unknown): SupervisorReplyEntryData | undefined {
132
70
  createdAt: value.createdAt,
133
71
  };
134
72
  }
135
-
136
- function withRequestId(details: SupervisorRequestMessageDetails): string {
137
- return boundedField(details.requestId ?? details.id);
138
- }
139
-
140
- function requestHeading(reason: SupervisorReason | undefined): string {
141
- if (reason === "interview_request") return "⚠ Supervisor interview request";
142
- if (reason === "progress_update") return "ℹ Supervisor progress update";
143
- return "⚠ Supervisor decision request";
144
- }
145
-
146
- function requestLines(message: SupervisorMessageLike, details: SupervisorRequestMessageDetails, expanded: boolean): string[] {
147
- const requestId = withRequestId(details);
148
- const lines = [
149
- `Reason: ${boundedField(details.reason)}`,
150
- `Run: ${boundedField(details.runId)}`,
151
- `Agent: ${boundedField(details.agent)}`,
152
- `Child index: ${boundedField(details.childIndex)}`,
153
- ];
154
- if (details.childTarget) lines.push(`Child target: ${boundedField(details.childTarget)}`);
155
- lines.push(`Request ID: ${requestId}`);
156
- if (details.expectsReply) lines.push(`Reply with: ${displayText(details.replyHint ?? supervisorReplyHint(requestId), MAX_BODY_CHARS, expanded)}`);
157
- lines.push("", "Request:", displayText((details.requestBody ?? contentText(message.content)) || "(no request body)", MAX_BODY_CHARS, expanded));
158
- if (details.interview !== undefined) lines.push("", "Interview shape:", interviewText(details.interview, expanded));
159
- return lines;
160
- }
161
-
162
- function replyLines(data: SupervisorReplyEntryData, expanded: boolean): string[] {
163
- const requestId = boundedField(data.requestId);
164
- const lines = [
165
- ...(data.reason ? [`Reason: ${boundedField(data.reason)}`] : []),
166
- `Run: ${boundedField(data.runId)}`,
167
- `Agent: ${boundedField(data.agent)}`,
168
- `Child index: ${boundedField(data.childIndex)}`,
169
- ];
170
- if (data.childTarget) lines.push(`Child target: ${boundedField(data.childTarget)}`);
171
- lines.push(`Reply to: ${requestId}`, "", "Reply:", displayText(data.message || "(empty reply)", MAX_BODY_CHARS, expanded));
172
- return lines;
173
- }
174
-
175
- function renderCard(lines: string[], heading: string, theme: Theme, width: number, expanded: boolean): string[] {
176
- const safeWidth = Math.max(0, Math.floor(width));
177
- if (safeWidth < 3) return [truncateToWidth(heading, safeWidth, "")];
178
- const bodyWidth = safeWidth - 2;
179
- const headerText = truncateToWidth(` ${heading} `, bodyWidth, "");
180
- const headerPadding = Math.max(0, bodyWidth - visibleWidth(headerText));
181
- const border = (text: string) => theme.fg("accent", text);
182
- const rendered = [border(`╭${headerText}${"─".repeat(headerPadding)}╮`)];
183
- let hidden = false;
184
- let interiorLines = 0;
185
- for (const line of lines) {
186
- const wrapped = wrapTextWithAnsi(line, Math.max(1, bodyWidth));
187
- for (const wrappedLine of wrapped.length > 0 ? wrapped : [""]) {
188
- if (!expanded && interiorLines >= MAX_RENDER_LINES) {
189
- hidden = true;
190
- break;
191
- }
192
- const text = truncateToWidth(wrappedLine, bodyWidth, "");
193
- rendered.push(border(`│${text}${" ".repeat(Math.max(0, bodyWidth - visibleWidth(text)))}│`));
194
- interiorLines++;
195
- }
196
- if (hidden) break;
197
- }
198
- if (hidden) {
199
- const text = truncateToWidth(TRUNCATION_MARKER, bodyWidth, "");
200
- rendered.push(border(`│${text}${" ".repeat(Math.max(0, bodyWidth - visibleWidth(text)))}│`));
201
- }
202
- rendered.push(border(`╰${"─".repeat(bodyWidth)}╯`));
203
- return rendered;
204
- }
205
-
206
- class SupervisorCardComponent implements Component {
207
- private readonly expanded: boolean;
208
- private readonly heading: string;
209
- private readonly lines: string[];
210
- private readonly theme: Theme;
211
-
212
- constructor(heading: string, lines: string[], theme: Theme, expanded: boolean) {
213
- this.expanded = expanded;
214
- this.heading = heading;
215
- this.lines = lines;
216
- this.theme = theme;
217
- }
218
-
219
- invalidate(): void {}
220
-
221
- render(width: number): string[] {
222
- return renderCard(this.lines, this.heading, this.theme, width, this.expanded);
223
- }
224
- }
225
-
226
- export function renderSupervisorRequest(
227
- message: SupervisorMessageLike,
228
- options: MessageRenderOptions,
229
- theme: Theme,
230
- ): Component | undefined {
231
- const details = requestDetails(message.details);
232
- if (!details) return undefined;
233
- return new SupervisorCardComponent(requestHeading(details.reason), requestLines(message, details, options.expanded), theme, options.expanded);
234
- }
235
-
236
- export function renderSupervisorReply(
237
- entry: SupervisorEntryLike,
238
- options: EntryRenderOptions,
239
- theme: Theme,
240
- ): Component | undefined {
241
- const data = replyData(entry.data);
242
- if (!data) return undefined;
243
- return new SupervisorCardComponent("↩ Supervisor reply to child", replyLines(data, options.expanded), theme, options.expanded);
244
- }
@@ -31,7 +31,14 @@ function readLinkedRun(run: MissionRunLink): MissionRunLink {
31
31
  if (!run.asyncDir) return run;
32
32
  const statusPath = path.join(run.asyncDir, "status.json");
33
33
  if (!fs.existsSync(statusPath)) return run;
34
- const status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as Record<string, unknown>;
34
+ let parsed: unknown;
35
+ try {
36
+ parsed = JSON.parse(fs.readFileSync(statusPath, "utf-8"));
37
+ } catch (error) {
38
+ throw new Error(`Failed to read linked run status '${statusPath}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
39
+ }
40
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`Linked run status '${statusPath}' must be an object`);
41
+ const status = parsed as Record<string, unknown>;
35
42
  if (typeof status.state !== "string" || !status.state.trim()) throw new Error(`Linked run status '${statusPath}' is missing state`);
36
43
  const tokens = tokenUsage(status.totalTokens)
37
44
  ?? (Array.isArray(status.steps)
@@ -123,42 +130,48 @@ export function collectGoalContinuationNotices(input: {
123
130
  retainedChildren: RetainedChild[];
124
131
  turnId: number;
125
132
  now?: number;
133
+ onError?: (missionId: string, error: unknown) => void;
126
134
  }): GoalContinuationNotice[] {
127
135
  const notices: GoalContinuationNotice[] = [];
128
136
  const seen = new Set<string>();
137
+ const onError = input.onError ?? ((missionId: string, error: unknown) => console.error("Failed to evaluate goal mission", missionId, error));
129
138
  for (const listed of listMissions(input.location).records) {
130
139
  if (listed.ownerSessionId !== input.ownerSessionId || !listed.goal || TERMINAL_MISSION_STATUSES.has(listed.status)) continue;
131
- let record = refreshGoalMission(input.location, readMission(input.location, listed.id));
132
- if (!record.goal || record.goal.status !== "active" || !record.budget) continue;
133
- if ((record.usage?.tokens ?? 0) >= record.budget.tokens) {
134
- record = updateMission(input.location, record.id, { usage: record.usage ?? { tokens: 0 } });
135
- if (record.goal?.status === "budget-exhausted") continue;
136
- }
137
- if (record.runs.some((run) => run.status && ACTIVE_RUN_STATUSES.has(run.status))) continue;
138
- if (seen.has(record.id) || !record.budget) continue;
139
- seen.add(record.id);
140
- const budget = record.budget.tokens;
141
- const used = record.usage?.tokens ?? 0;
142
- const remaining = Math.max(0, budget - used);
143
- const message = [
144
- `Goal mission needs attention: ${bounded(record.title)}`,
145
- `Mission: ${record.id}`,
146
- `Remaining budget: ${remaining} tokens (${used}/${budget} used)`,
147
- `Next ready action: ${nextReadyAction(input.location, record, input.retainedChildren)}`,
148
- ].join("\n");
149
- notices.push({
150
- missionId: record.id,
151
- message,
152
- event: {
153
- type: "needs_attention",
154
- to: "needs_attention",
155
- ts: input.now ?? Date.now(),
156
- runId: `goal-${record.id}-turn-${input.turnId}`,
157
- agent: "goal mission",
140
+ try {
141
+ let record = refreshGoalMission(input.location, readMission(input.location, listed.id));
142
+ if (!record.goal || record.goal.status !== "active" || !record.budget) continue;
143
+ if ((record.usage?.tokens ?? 0) >= record.budget.tokens) {
144
+ record = updateMission(input.location, record.id, { usage: record.usage ?? { tokens: 0 } });
145
+ if (record.goal?.status === "budget-exhausted") continue;
146
+ }
147
+ if (record.runs.some((run) => run.status && ACTIVE_RUN_STATUSES.has(run.status))) continue;
148
+ if (seen.has(record.id) || !record.budget) continue;
149
+ seen.add(record.id);
150
+ const budget = record.budget.tokens;
151
+ const used = record.usage?.tokens ?? 0;
152
+ const remaining = Math.max(0, budget - used);
153
+ const message = [
154
+ `Goal mission needs attention: ${bounded(record.title)}`,
155
+ `Mission: ${record.id}`,
156
+ `Remaining budget: ${remaining} tokens (${used}/${budget} used)`,
157
+ `Next ready action: ${nextReadyAction(input.location, record, input.retainedChildren)}`,
158
+ ].join("\n");
159
+ notices.push({
160
+ missionId: record.id,
158
161
  message,
159
- reason: "idle",
160
- },
161
- });
162
+ event: {
163
+ type: "needs_attention",
164
+ to: "needs_attention",
165
+ ts: input.now ?? Date.now(),
166
+ runId: `goal-${record.id}-turn-${input.turnId}`,
167
+ agent: "goal mission",
168
+ message,
169
+ reason: "idle",
170
+ },
171
+ });
172
+ } catch (error) {
173
+ onError(listed.id, error);
174
+ }
162
175
  }
163
176
  return notices;
164
177
  }
@@ -282,18 +282,38 @@ export function validateMissionStoreConfig(value: unknown, label = "config.missi
282
282
  };
283
283
  }
284
284
 
285
+ // Resolve the existing prefix and keep the missing components in the store key.
286
+ function canonicalProjectRoot(root: string): string {
287
+ const missing: string[] = [];
288
+ let current = root;
289
+ for (;;) {
290
+ try {
291
+ return path.join(fs.realpathSync.native(current), ...missing.reverse());
292
+ } catch (error) {
293
+ // Only a missing component walks upward; EACCES, ELOOP and the rest must surface.
294
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
295
+ const parent = path.dirname(current);
296
+ if (parent === current) return root;
297
+ missing.push(path.basename(current));
298
+ current = parent;
299
+ }
300
+ }
301
+ }
302
+
285
303
  export function resolveMissionStoreLocation(input: {
286
304
  projectRoot: string;
287
305
  config?: MissionStoreConfig;
288
306
  agentDir?: string;
289
307
  }): MissionStoreLocation {
290
- const projectRoot = path.resolve(input.projectRoot);
308
+ const givenRoot = path.resolve(input.projectRoot);
309
+ const configuredDir = input.config?.directory;
310
+ // The default store is keyed by a hash of the root, so two paths to one directory
311
+ // must hash the same. Configured paths keep expanding against the root as given.
312
+ const projectRoot = configuredDir ? givenRoot : canonicalProjectRoot(givenRoot);
291
313
  const agentDir = input.agentDir ?? getAgentDir();
292
- const missionDir = input.config?.directory
293
- ? expandConfiguredPath(input.config.directory, projectRoot)
294
- : projectMissionDirectory(agentDir, projectRoot);
314
+ const missionDir = configuredDir ? expandConfiguredPath(configuredDir, givenRoot) : projectMissionDirectory(agentDir, projectRoot);
295
315
  const globalIndexDir = input.config?.globalIndexDir
296
- ? expandConfiguredPath(input.config.globalIndexDir, projectRoot)
316
+ ? expandConfiguredPath(input.config.globalIndexDir, givenRoot)
297
317
  : path.join(agentDir, "missions", "index");
298
318
  return {
299
319
  projectRoot,
@@ -562,7 +582,16 @@ export function listGlobalMissions(globalIndexDir: string): GlobalMissionListRes
562
582
  try {
563
583
  const record = parseMissionRecord(JSON.parse(fs.readFileSync(entry.recordPath, "utf-8")), entry.recordPath);
564
584
  if (record.id !== entry.missionId) throw new Error(`record id '${record.id}' does not match index id '${entry.missionId}'`);
565
- entries.push({ ...entry, stale: false });
585
+ const projection: MissionIndexEntry = {
586
+ ...entry,
587
+ title: record.title,
588
+ status: record.status,
589
+ updatedAt: record.updatedAt,
590
+ };
591
+ delete projection.lastRunId;
592
+ const lastRunId = record.runs.at(-1)?.runId;
593
+ if (lastRunId) projection.lastRunId = lastRunId;
594
+ entries.push({ ...projection, stale: false });
566
595
  } catch (error) {
567
596
  if ((error as NodeJS.ErrnoException).code === "ENOENT") {
568
597
  try {
@@ -2,9 +2,10 @@ import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
- import { BUILTIN_AGENT_NAMES } from "../agents/agents.ts";
5
+ import { BUILTIN_AGENT_NAMES, validateOptionalMachine } from "../agents/agents.ts";
6
6
  import { getPiSpawnCommand } from "../runs/shared/pi-spawn.ts";
7
7
  import { findModelInfo, getSupportedThinkingLevels, splitKnownThinkingSuffix, toModelInfo } from "../shared/model-info.ts";
8
+ import { withSettingsFileLease } from "../shared/settings-file-lease.ts";
8
9
  import { getAgentDir } from "../shared/utils.ts";
9
10
 
10
11
  export const DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS = 7;
@@ -20,7 +21,7 @@ export type RecommendedRoleTier = "cheap" | "medium" | "strong";
20
21
  interface ProfileAgentOverride {
21
22
  model?: string;
22
23
  thinking?: string | false;
23
- machine?: string;
24
+ machine?: string | false;
24
25
  }
25
26
 
26
27
  export interface SubagentProfileFile {
@@ -144,6 +145,9 @@ function validateSubagentProfile(filePath: string, parsed: Record<string, unknow
144
145
  if (thinking !== undefined && thinking !== false && typeof thinking !== "string") {
145
146
  throw new Error(`Profile '${filePath}' has invalid thinking for '${name}'; expected a string or false.`);
146
147
  }
148
+ if (override.machine !== undefined && override.machine !== false) {
149
+ override.machine = validateOptionalMachine(override.machine, `Profile '${filePath}' has invalid machine for '${name}'`);
150
+ }
147
151
  if ((override as Record<string, unknown>).fallbackModels !== undefined) throw new Error(`Profile '${filePath}' uses removed field fallbackModels for '${name}'; configure one model instead.`);
148
152
  }
149
153
  const disableBuiltins = (subagents as Record<string, unknown>).disableBuiltins;
@@ -480,27 +484,29 @@ export function readSubagentProfile(name: string): { filePath: string; profile:
480
484
  export function applySubagentProfile(name: string): { filePath: string; settingsPath: string } {
481
485
  const { filePath, profile } = readSubagentProfile(name);
482
486
  const settingsPath = getUserSettingsPath();
483
- const settings = readSettingsFile(settingsPath);
484
- const existing = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
485
- ? settings.subagents as Record<string, unknown>
486
- : {};
487
- // A profile owns the complete agent mapping, but unrelated subagent settings
488
- // (notably disableBuiltins, modelScope, watchdog, etc.) survive profile switches.
489
- // Machine placement is not a model choice, so an existing pin survives a profile switch too.
490
- const agentOverrides: Record<string, ProfileAgentOverride> = { ...profile.subagents.agentOverrides };
491
- const existingOverrides = existing.agentOverrides && typeof existing.agentOverrides === "object" && !Array.isArray(existing.agentOverrides)
492
- ? existing.agentOverrides as Record<string, unknown>
493
- : {};
494
- for (const [name, value] of Object.entries(existingOverrides)) {
495
- const machine = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>).machine : undefined;
496
- if (typeof machine === "string" && agentOverrides[name]?.machine === undefined) agentOverrides[name] = { ...agentOverrides[name], machine };
497
- }
498
- settings.subagents = {
499
- ...existing,
500
- ...profile.subagents,
501
- agentOverrides,
502
- };
503
- writeJsonFile(settingsPath, settings);
487
+ withSettingsFileLease(settingsPath, () => {
488
+ const settings = readSettingsFile(settingsPath);
489
+ const existing = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
490
+ ? settings.subagents as Record<string, unknown>
491
+ : {};
492
+ // A profile owns the complete agent mapping, but unrelated subagent settings
493
+ // (notably disableBuiltins, modelScope, watchdog, etc.) survive profile switches.
494
+ // Machine placement is not a model choice, so an existing pin survives a profile switch too.
495
+ const agentOverrides: Record<string, ProfileAgentOverride> = { ...profile.subagents.agentOverrides };
496
+ const existingOverrides = existing.agentOverrides && typeof existing.agentOverrides === "object" && !Array.isArray(existing.agentOverrides)
497
+ ? existing.agentOverrides as Record<string, unknown>
498
+ : {};
499
+ for (const [name, value] of Object.entries(existingOverrides)) {
500
+ const machine = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>).machine : undefined;
501
+ if (typeof machine === "string" && agentOverrides[name]?.machine === undefined) agentOverrides[name] = { ...agentOverrides[name], machine };
502
+ }
503
+ settings.subagents = {
504
+ ...existing,
505
+ ...profile.subagents,
506
+ agentOverrides,
507
+ };
508
+ writeJsonFile(settingsPath, settings);
509
+ });
504
510
  return { filePath, settingsPath };
505
511
  }
506
512
 
@@ -5,8 +5,9 @@ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
5
5
  import { TEMP_ROOT_DIR, type ActiveAsyncCapacitySnapshot, type AsyncStatus } from "../../shared/types.ts";
6
6
  import { readStatus } from "../../shared/utils.ts";
7
7
  import { checkPidLiveness, type PidLiveness } from "./stale-run-reconciler.ts";
8
+ import { currentPidNamespaceScope } from "./pid-namespace.ts";
8
9
  import { readProcessTerminal } from "./process-terminal.ts";
9
- import { isTerminalAsyncState as terminalState, readWorkflowChildProcessEvidence } from "./workflow-terminal-proof.ts";
10
+ import { isTerminalAsyncState as terminalState, readWorkflowChildEvidence, readWorkflowChildProcessEvidence } from "./workflow-terminal-proof.ts";
10
11
 
11
12
  export const ACTIVE_ASYNC_CAPACITY_DIR = path.join(TEMP_ROOT_DIR, "session-active-async-capacity");
12
13
  export const DEFAULT_ABANDONED_SLOT_RELEASE_AFTER_MS = 20 * 60 * 1000;
@@ -44,11 +45,12 @@ interface CapacityOptions {
44
45
  token?: () => string;
45
46
  abandonedSlotReleaseAfterMs?: number | false;
46
47
  pidLiveness?: (pid: number) => PidLiveness;
48
+ pidNamespaceScope?: () => string | undefined;
47
49
  afterSlotRename?: (releasedDir: string) => void;
48
50
  writeOwner?: (filePath: string, owner: ActiveAsyncCapacityOwner) => void;
49
51
  }
50
52
 
51
- export interface ActiveAsyncCapacityReleaseEvidence {
53
+ interface AbandonedRunnerEvidence {
52
54
  releasedBy: "abandoned-timeout";
53
55
  processProof: "unknown";
54
56
  runnerPid: "gone";
@@ -56,6 +58,18 @@ export interface ActiveAsyncCapacityReleaseEvidence {
56
58
  abandonedSlotReleaseAfterMs: number;
57
59
  }
58
60
 
61
+ /** A workflow's own status PID is the parent Pi host, so workflow evidence names its dead child runners instead. */
62
+ interface AbandonedWorkflowEvidence {
63
+ releasedBy: "abandoned-timeout";
64
+ processProof: "unknown";
65
+ controller: "unregistered";
66
+ workflowEndedAgeMs: number;
67
+ abandonedChildren: Array<{ runId: string; lastActivityAgeMs: number }>;
68
+ abandonedSlotReleaseAfterMs: number;
69
+ }
70
+
71
+ export type ActiveAsyncCapacityReleaseEvidence = AbandonedRunnerEvidence | AbandonedWorkflowEvidence;
72
+
59
73
  export type ActiveAsyncCapacityReleaseVerdict =
60
74
  | { state: "releasable"; reason: string; evidence?: ActiveAsyncCapacityReleaseEvidence }
61
75
  | { state: "retained"; reason: string }
@@ -232,12 +246,14 @@ function runnerReleaseVerdict(owner: ActiveAsyncCapacityOwner, status: AsyncStat
232
246
  : abandonedRunnerReleaseVerdict(status, proof?.state ?? "missing", options);
233
247
  }
234
248
 
235
- function abandonedRunnerReleaseVerdict(status: AsyncStatus, proofState: string, options: CapacityOptions): ActiveAsyncCapacityReleaseVerdict {
249
+ function abandonedRunnerReleaseVerdict(status: AsyncStatus, proofState: string, options: CapacityOptions): { state: "retained"; reason: string } | { state: "releasable"; reason: string; evidence: AbandonedRunnerEvidence } {
236
250
  const proofReason = `process-terminal proof is ${proofState}`;
237
251
  const thresholdMs = resolveAbandonedSlotReleaseAfterMs(options.abandonedSlotReleaseAfterMs);
238
252
  if (thresholdMs === false) return { state: "retained", reason: `${proofReason}; abandoned-timeout policy is disabled` };
239
253
  if (status.state !== "failed") return { state: "retained", reason: `${proofReason}; abandoned-timeout policy requires a failed run, not ${status.state}` };
240
254
  if (typeof status.pid !== "number" || !Number.isInteger(status.pid) || status.pid < 1) return { state: "retained", reason: `${proofReason}; runner PID is missing or invalid` };
255
+ // A PID from another namespace can look dead here while the runner is alive.
256
+ if (status.pidNamespaceScope !== undefined && status.pidNamespaceScope !== (options.pidNamespaceScope ?? currentPidNamespaceScope)()) return { state: "retained", reason: `${proofReason}; runner PID namespace differs from this process, so liveness is unknown` };
241
257
  const liveness = (options.pidLiveness ?? checkPidLiveness)(status.pid);
242
258
  if (liveness !== "dead") return { state: "retained", reason: `${proofReason}; runner PID liveness is ${liveness}` };
243
259
  const lastActivityAt = status.lastActivityAt ?? status.lastUpdate ?? status.endedAt;
@@ -245,7 +261,7 @@ function abandonedRunnerReleaseVerdict(status: AsyncStatus, proofState: string,
245
261
  const now = options.now?.() ?? Date.now();
246
262
  const lastActivityAgeMs = Math.max(0, now - lastActivityAt);
247
263
  if (lastActivityAgeMs <= thresholdMs) return { state: "retained", reason: `${proofReason}; last activity age ${lastActivityAgeMs}ms has not exceeded abandoned-timeout ${thresholdMs}ms` };
248
- const evidence: ActiveAsyncCapacityReleaseEvidence = {
264
+ const evidence: AbandonedRunnerEvidence = {
249
265
  releasedBy: "abandoned-timeout",
250
266
  processProof: "unknown",
251
267
  runnerPid: "gone",
@@ -259,7 +275,7 @@ function abandonedRunnerReleaseVerdict(status: AsyncStatus, proofState: string,
259
275
  };
260
276
  }
261
277
 
262
- function workflowReleaseVerdict(owner: ActiveAsyncCapacityOwner, status: AsyncStatus | null, liveWorkflowRunIds: ReadonlySet<string>): ActiveAsyncCapacityReleaseVerdict {
278
+ function workflowReleaseVerdict(owner: ActiveAsyncCapacityOwner, status: AsyncStatus | null, liveWorkflowRunIds: ReadonlySet<string>, options: CapacityOptions): ActiveAsyncCapacityReleaseVerdict {
263
279
  if (!status) return { state: "retained", reason: "status file is missing or unreadable" };
264
280
  if (status.sessionId !== owner.ownerSessionId) return { state: "retained", reason: `status session ${status.sessionId ?? "unknown"} does not match owner session ${owner.ownerSessionId}` };
265
281
  if (status.runId !== owner.runId) return { state: "retained", reason: `status run ${status.runId} does not match owner run ${owner.runId}` };
@@ -267,15 +283,49 @@ function workflowReleaseVerdict(owner: ActiveAsyncCapacityOwner, status: AsyncSt
267
283
  if (!terminalState(status.state)) return { state: "retained", reason: `workflow is still ${status.state}` };
268
284
  if (liveWorkflowRunIds.has(owner.runId)) return { state: "retained", reason: "workflow controller is still live" };
269
285
  const evidence = readWorkflowChildProcessEvidence(owner.asyncDir, status.steps);
270
- if (evidence.state !== "observed") return { state: "retained", reason: evidence.reason };
271
- return { state: "releasable", reason: "workflow is terminal, controller is gone, and async children have observed proof" };
286
+ if (evidence.state === "observed") return { state: "releasable", reason: "workflow is terminal, controller is gone, and async children have observed proof" };
287
+ return abandonedWorkflowReleaseVerdict(owner, status, evidence.reason, options);
288
+ }
289
+
290
+ /** Every unresolved async child must itself pass the abandoned runner policy; any other unresolved child keeps the slot. */
291
+ function abandonedWorkflowReleaseVerdict(owner: ActiveAsyncCapacityOwner, status: AsyncStatus, proofReason: string, options: CapacityOptions): ActiveAsyncCapacityReleaseVerdict {
292
+ const thresholdMs = resolveAbandonedSlotReleaseAfterMs(options.abandonedSlotReleaseAfterMs);
293
+ if (thresholdMs === false) return { state: "retained", reason: `${proofReason}; abandoned-timeout policy is disabled` };
294
+ if (!status.steps) return { state: "retained", reason: proofReason };
295
+ if (typeof status.endedAt !== "number" || !Number.isFinite(status.endedAt)) return { state: "retained", reason: `${proofReason}; workflow end timestamp is missing or invalid` };
296
+ const workflowEndedAgeMs = (options.now?.() ?? Date.now()) - status.endedAt;
297
+ if (workflowEndedAgeMs <= thresholdMs) return { state: "retained", reason: `${proofReason}; workflow ended ${workflowEndedAgeMs}ms ago, within abandoned-timeout ${thresholdMs}ms` };
298
+ const abandonedChildren: AbandonedWorkflowEvidence["abandonedChildren"] = [];
299
+ for (const step of status.steps) {
300
+ const child = readWorkflowChildEvidence(owner.asyncDir, step);
301
+ if (!child || child.state === "resolved") continue;
302
+ const unresolved = child.unresolvedProof;
303
+ if (!unresolved) return { state: "retained", reason: child.reason };
304
+ if (unresolved.status.sessionId !== owner.ownerSessionId) return { state: "retained", reason: `${child.reason}; child session ${unresolved.status.sessionId ?? "unknown"} does not match owner session ${owner.ownerSessionId}` };
305
+ const verdict = abandonedRunnerReleaseVerdict(unresolved.status, unresolved.proofState, options);
306
+ if (verdict.state !== "releasable") return { state: "retained", reason: `async workflow child ${unresolved.status.runId}: ${verdict.reason}` };
307
+ abandonedChildren.push({ runId: unresolved.status.runId, lastActivityAgeMs: verdict.evidence.lastActivityAgeMs });
308
+ }
309
+ const evidence: AbandonedWorkflowEvidence = {
310
+ releasedBy: "abandoned-timeout",
311
+ processProof: "unknown",
312
+ controller: "unregistered",
313
+ workflowEndedAgeMs,
314
+ abandonedChildren,
315
+ abandonedSlotReleaseAfterMs: thresholdMs,
316
+ };
317
+ return {
318
+ state: "releasable",
319
+ reason: `${evidence.releasedBy}: ${proofReason}; workflow controller is unregistered; failed async children ${abandonedChildren.map((child) => child.runId).join(", ")} have dead runner PIDs; process proof unknown; workflow ended ${workflowEndedAgeMs}ms ago, over ${thresholdMs}ms`,
320
+ evidence,
321
+ };
272
322
  }
273
323
 
274
324
  function ownerReleaseVerdict(owner: ActiveAsyncCapacityOwner, liveWorkflowRunIds: ReadonlySet<string>, options: CapacityOptions): ActiveAsyncCapacityReleaseVerdict {
275
325
  const status = readStatus(owner.asyncDir);
276
326
  return owner.kind === "runner"
277
327
  ? runnerReleaseVerdict(owner, status, options)
278
- : workflowReleaseVerdict(owner, status, liveWorkflowRunIds);
328
+ : workflowReleaseVerdict(owner, status, liveWorkflowRunIds, options);
279
329
  }
280
330
 
281
331
  function capacitySessionDirs(rootDir: string, sessionId?: string): string[] {