@xzzpig/pi-subagents 0.4.2 → 0.6.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 (128) hide show
  1. package/CHANGELOG.md +172 -1
  2. package/README.md +8 -0
  3. package/agents/oracle.md +3 -1
  4. package/agents/reviewer.md +1 -0
  5. package/agents/scout.md +2 -2
  6. package/agents/worker.md +2 -1
  7. package/async-retention-discovery-worker.mjs +180 -0
  8. package/docs/agents.md +79 -2
  9. package/docs/configuration.md +42 -14
  10. package/docs/extension-api.md +45 -2
  11. package/docs/models.md +2 -0
  12. package/docs/observability.md +41 -5
  13. package/docs/tool-reference.md +38 -39
  14. package/docs/workflows.md +173 -3
  15. package/package.json +13 -10
  16. package/prompts/council.md +48 -0
  17. package/skills/council-mode/SKILL.md +230 -0
  18. package/skills/pi-subagents/SKILL.md +8 -4
  19. package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
  20. package/skills/pi-subagents/references/execution-controls.md +40 -15
  21. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  22. package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
  24. package/src/agents/agent-management.ts +158 -357
  25. package/src/agents/agent-serializer.ts +4 -0
  26. package/src/agents/agents.ts +227 -53
  27. package/src/agents/builtin-names.ts +9 -0
  28. package/src/agents/runtime-agent-registry.ts +422 -0
  29. package/src/agents/skills.ts +1 -1
  30. package/src/api/agents.ts +7 -0
  31. package/src/api/external-job-provider.ts +186 -0
  32. package/src/api/preflight.ts +37 -9
  33. package/src/api/shared-types.ts +2 -0
  34. package/src/extension/config.ts +6 -3
  35. package/src/extension/context-injection.ts +118 -0
  36. package/src/extension/doctor.ts +15 -6
  37. package/src/extension/fanout-child.ts +2 -2
  38. package/src/extension/index.ts +224 -90
  39. package/src/extension/public-execution.ts +31 -2
  40. package/src/extension/rpc.ts +41 -1
  41. package/src/extension/schemas.ts +17 -37
  42. package/src/extension/tool-description.ts +35 -24
  43. package/src/inspectors/herdr/actions.ts +2 -2
  44. package/src/inspectors/herdr/inspector-runner.ts +2 -1
  45. package/src/inspectors/herdr/project-panes.ts +2 -2
  46. package/src/intercom/native-supervisor-channel.ts +32 -10
  47. package/src/missions/lifecycle.ts +6 -1
  48. package/src/missions/store.ts +4 -9
  49. package/src/missions/workflow-state.ts +2 -2
  50. package/src/profiles/profiles.ts +3 -1
  51. package/src/runs/background/active-run-index.ts +31 -8
  52. package/src/runs/background/async-execution.ts +70 -41
  53. package/src/runs/background/async-job-tracker.ts +24 -7
  54. package/src/runs/background/async-resume.ts +49 -16
  55. package/src/runs/background/async-retention.ts +886 -0
  56. package/src/runs/background/async-status-snapshot.ts +14 -5
  57. package/src/runs/background/async-status.ts +39 -53
  58. package/src/runs/background/auto-drain.ts +1 -0
  59. package/src/runs/background/chain-append.ts +3 -33
  60. package/src/runs/background/completion-dedupe.ts +5 -1
  61. package/src/runs/background/completion-replay.ts +22 -12
  62. package/src/runs/background/control-channel.ts +14 -68
  63. package/src/runs/background/fleet-view.ts +68 -19
  64. package/src/runs/background/index-segment.ts +59 -0
  65. package/src/runs/background/inspect-rpc.ts +443 -0
  66. package/src/runs/background/notify.ts +31 -5
  67. package/src/runs/background/result-files.ts +158 -90
  68. package/src/runs/background/result-watcher.ts +124 -20
  69. package/src/runs/background/resume-guidance.ts +8 -5
  70. package/src/runs/background/retained-children.ts +13 -3
  71. package/src/runs/background/run-id-query.ts +7 -0
  72. package/src/runs/background/run-id-resolver.ts +11 -9
  73. package/src/runs/background/run-status.ts +27 -18
  74. package/src/runs/background/scheduled-runs.ts +24 -4
  75. package/src/runs/background/stale-run-reconciler.ts +6 -3
  76. package/src/runs/background/steering.ts +11 -1
  77. package/src/runs/background/subagent-runner.ts +260 -144
  78. package/src/runs/background/subagent-wait.ts +17 -13
  79. package/src/runs/background/terminal-run-index.ts +138 -0
  80. package/src/runs/background/wait-completions.ts +21 -4
  81. package/src/runs/background/wait-subscriptions.ts +81 -2
  82. package/src/runs/background/wait-tool.ts +1 -0
  83. package/src/runs/foreground/async-steering-action.ts +21 -14
  84. package/src/runs/foreground/execution.ts +8 -2
  85. package/src/runs/foreground/subagent-executor.ts +816 -1593
  86. package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
  87. package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
  88. package/src/runs/shared/acceptance.ts +48 -5
  89. package/src/runs/shared/chain-outputs.ts +1 -3
  90. package/src/runs/shared/external-job-bridge.ts +444 -0
  91. package/src/runs/shared/external-job-runner.ts +286 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
  93. package/src/runs/shared/model-exclusions.ts +242 -0
  94. package/src/runs/shared/model-fallback.ts +153 -40
  95. package/src/runs/shared/orca-progress-tabs.ts +84 -22
  96. package/src/runs/shared/parallel-handoff.ts +46 -4
  97. package/src/runs/shared/parallel-utils.ts +4 -15
  98. package/src/runs/shared/permissions.ts +5 -1
  99. package/src/runs/shared/pi-args.ts +8 -1
  100. package/src/runs/shared/session-lease.ts +0 -6
  101. package/src/runs/shared/subagent-control.ts +51 -7
  102. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  103. package/src/runs/shared/workflow-graph.ts +1 -23
  104. package/src/runs/shared/worktree.ts +14 -2
  105. package/src/shared/atomic-json.ts +22 -2
  106. package/src/shared/capacity-resilient-json.ts +102 -0
  107. package/src/shared/completion-owner.ts +14 -0
  108. package/src/shared/file-system-retry.ts +49 -1
  109. package/src/shared/fork-context.ts +59 -1
  110. package/src/shared/model-info.ts +20 -0
  111. package/src/shared/prompt-resources.ts +0 -40
  112. package/src/shared/settings.ts +5 -29
  113. package/src/shared/types.ts +110 -26
  114. package/src/shared/utils.ts +8 -0
  115. package/src/shared/watch-strategy.ts +10 -0
  116. package/src/slash/slash-bridge.ts +2 -1
  117. package/src/slash/slash-commands.ts +47 -7
  118. package/src/slash/slash-live-state.ts +3 -3
  119. package/src/tui/fleet-status.ts +86 -1
  120. package/src/tui/fleet.ts +117 -16
  121. package/src/tui/render.ts +73 -3
  122. package/src/watchdog/change-signature.ts +1 -1
  123. package/src/watchdog/lsp-diagnostics.ts +1 -0
  124. package/src/workflows/chat-progress.ts +2 -2
  125. package/src/workflows/scripted-workflow.ts +320 -79
  126. package/src/workflows/workflow-receipt.ts +140 -0
  127. package/src/runs/foreground/chain-clarify.ts +0 -1354
  128. package/src/runs/foreground/chain-execution.ts +0 -1581
@@ -1,5 +1,6 @@
1
1
  import type { ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
2
2
  import type { Usage } from "../../shared/types.ts";
3
+ import { filterFallbackCandidates, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
3
4
  import { checkModelScope, type ModelScopeConfig, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
4
5
 
5
6
  export type { AvailableModelInfo };
@@ -41,7 +42,7 @@ export function normalizeParentModel(model: unknown): ParentModel | undefined {
41
42
  /**
42
43
  * Normalize a model id or provider segment for fuzzy comparison: case-fold,
43
44
  * treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse
44
- * repeated separators. Pure.
45
+ * repeated separators.
45
46
  */
46
47
  export function normalizeModelSegment(segment: string): string {
47
48
  return segment
@@ -58,7 +59,7 @@ function isPlausibleDateStamp(year: string, month: string, day: string): boolean
58
59
  return yyyy >= 1900 && yyyy <= 2099 && mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31;
59
60
  }
60
61
 
61
- /** Drop a trailing date stamp (`-20251001` or `-2025-10-01`) so dated and undated ids match. Pure. */
62
+ /** Drop a trailing date stamp (`-20251001` or `-2025-10-01`) so dated and undated ids match. */
62
63
  function stripTrailingDateStamp(segment: string): string {
63
64
  const dashed = /^(.*)-(\d{4})-(\d{2})-(\d{2})$/.exec(segment);
64
65
  if (dashed && isPlausibleDateStamp(dashed[2]!, dashed[3]!, dashed[4]!)) return dashed[1]!;
@@ -67,21 +68,65 @@ function stripTrailingDateStamp(segment: string): string {
67
68
  return segment;
68
69
  }
69
70
 
71
+ function isRegisteredProvider(provider: string, availableModels: AvailableModelInfo[]): boolean {
72
+ const normalized = normalizeModelSegment(provider);
73
+ return availableModels.some((entry) => normalizeModelSegment(entry.provider) === normalized);
74
+ }
75
+
76
+ /**
77
+ * Split `provider/id` only when the first path segment is a registered provider.
78
+ * Hugging Face-style `owner/name` ids therefore stay intact unless `owner` is
79
+ * itself a provider in the active registry. `:` and `.` keep the same rule.
80
+ */
81
+ function splitQualifiedModelQuery(
82
+ baseModel: string,
83
+ availableModels: AvailableModelInfo[],
84
+ ): { queryProvider?: string; queryIdRaw: string } {
85
+ const slashIdx = baseModel.indexOf("/");
86
+ if (slashIdx !== -1) {
87
+ const providerPart = baseModel.slice(0, slashIdx);
88
+ if (isRegisteredProvider(providerPart, availableModels)) {
89
+ return { queryProvider: normalizeModelSegment(providerPart), queryIdRaw: baseModel.slice(slashIdx + 1) };
90
+ }
91
+ return { queryIdRaw: baseModel };
92
+ }
93
+ const providerSeparators = [":", "."];
94
+ for (const separator of providerSeparators) {
95
+ const separatorIdx = baseModel.indexOf(separator);
96
+ if (separatorIdx <= 0) continue;
97
+ const providerPart = baseModel.slice(0, separatorIdx);
98
+ if (!isRegisteredProvider(providerPart, availableModels)) continue;
99
+ return { queryProvider: normalizeModelSegment(providerPart), queryIdRaw: baseModel.slice(separatorIdx + 1) };
100
+ }
101
+ return { queryIdRaw: baseModel };
102
+ }
103
+
104
+ function resolveExactIdMatches(
105
+ baseModel: string,
106
+ availableModels: AvailableModelInfo[],
107
+ preferredProvider?: string,
108
+ ): string | undefined {
109
+ const exactMatches = availableModels.filter((entry) => entry.id === baseModel);
110
+ if (preferredProvider) {
111
+ const preferredMatch = exactMatches.find((entry) => entry.provider === preferredProvider);
112
+ if (preferredMatch) return preferredMatch.fullId;
113
+ }
114
+ if (exactMatches.length === 1) return exactMatches[0]!.fullId;
115
+ return undefined;
116
+ }
117
+
70
118
  function resolveBaseModelCandidate(
71
119
  baseModel: string,
72
120
  availableModels: AvailableModelInfo[],
73
121
  preferredProvider?: string,
74
122
  ): string | undefined {
75
- if (baseModel.includes("/")) {
76
- const exact = availableModels.find((entry) => entry.fullId === baseModel);
77
- if (exact) return exact.fullId;
78
- } else {
79
- const exactMatches = availableModels.filter((entry) => entry.id === baseModel);
80
- if (preferredProvider) {
81
- const preferredMatch = exactMatches.find((entry) => entry.provider === preferredProvider);
82
- if (preferredMatch) return preferredMatch.fullId;
83
- }
84
- if (exactMatches.length === 1) return exactMatches[0]!.fullId;
123
+ const exact = availableModels.find((entry) => entry.fullId === baseModel);
124
+ if (exact) return exact.fullId;
125
+
126
+ const { queryProvider } = splitQualifiedModelQuery(baseModel, availableModels);
127
+ if (queryProvider === undefined) {
128
+ const exactId = resolveExactIdMatches(baseModel, availableModels, preferredProvider);
129
+ if (exactId) return exactId;
85
130
  }
86
131
 
87
132
  return fuzzyResolveModel(baseModel, availableModels, preferredProvider);
@@ -90,35 +135,20 @@ function resolveBaseModelCandidate(
90
135
  /**
91
136
  * Fuzzy-resolve a base model id (thinking suffix already stripped) against the
92
137
  * registry, tolerating separator, case, and optional date-stamp differences so
93
- * users do not have to spell provider/model exactly. A qualified `provider/id`
138
+ * users do not have to spell provider/model exactly. A slash is a provider
139
+ * prefix only when that prefix is a registered provider; otherwise the whole
140
+ * string is the model id (Hugging Face `owner/name`). A qualified provider
94
141
  * query only matches within the named provider — this never silently switches
95
142
  * providers for security/cost-sensitive configs. Returns the matched `fullId`,
96
143
  * or `undefined` when there is no match or the match is ambiguous across
97
- * providers (and no `preferredProvider` disambiguates). Pure.
144
+ * providers (and no `preferredProvider` disambiguates).
98
145
  */
99
146
  export function fuzzyResolveModel(
100
147
  baseModel: string,
101
148
  availableModels: AvailableModelInfo[],
102
149
  preferredProvider?: string,
103
150
  ): string | undefined {
104
- let queryProvider: string | undefined;
105
- let queryIdRaw = baseModel;
106
- const slashIdx = baseModel.indexOf("/");
107
- if (slashIdx !== -1) {
108
- queryProvider = normalizeModelSegment(baseModel.slice(0, slashIdx));
109
- queryIdRaw = baseModel.slice(slashIdx + 1);
110
- } else {
111
- const providerSeparators = [":", "."];
112
- for (const separator of providerSeparators) {
113
- const separatorIdx = baseModel.indexOf(separator);
114
- if (separatorIdx <= 0) continue;
115
- const providerPart = normalizeModelSegment(baseModel.slice(0, separatorIdx));
116
- if (!availableModels.some((entry) => normalizeModelSegment(entry.provider) === providerPart)) continue;
117
- queryProvider = providerPart;
118
- queryIdRaw = baseModel.slice(separatorIdx + 1);
119
- break;
120
- }
121
- }
151
+ const { queryProvider, queryIdRaw } = splitQualifiedModelQuery(baseModel, availableModels);
122
152
  const queryId = normalizeModelSegment(queryIdRaw);
123
153
  const queryIdNoDate = stripTrailingDateStamp(queryId);
124
154
 
@@ -143,7 +173,7 @@ export function fuzzyResolveModel(
143
173
  * thinking suffix). Exact registry matches win; fuzzy normalization
144
174
  * (separator/case/date-stamp via {@link fuzzyResolveModel}) is a fallback so
145
175
  * spelling differences still resolve. Never switches providers for a qualified
146
- * query. Pure.
176
+ * query.
147
177
  */
148
178
  export function resolveModelCandidate(
149
179
  model: string | undefined,
@@ -163,18 +193,45 @@ export function resolveModelCandidate(
163
193
  return model;
164
194
  }
165
195
 
166
- function resolveRequiredSubagentModelCandidate(
196
+ function resolveSubagentModelCandidate(
167
197
  model: string,
168
198
  availableModels: AvailableModelInfo[] | undefined,
169
199
  preferredProvider?: string,
170
- ): string {
200
+ ): string | undefined {
171
201
  if (!availableModels || availableModels.length === 0) return model;
172
202
  const resolvedWhole = resolveBaseModelCandidate(model, availableModels, preferredProvider);
173
203
  if (resolvedWhole) return resolvedWhole;
174
204
  const { baseModel, thinkingSuffix } = splitThinkingSuffix(model);
175
205
  const resolvedBase = thinkingSuffix ? resolveBaseModelCandidate(baseModel, availableModels, preferredProvider) : undefined;
176
- if (resolvedBase) return `${resolvedBase}${thinkingSuffix}`;
177
- throw new Error(`Unknown subagent model '${model}' in the active Pi model registry.`);
206
+ return resolvedBase ? `${resolvedBase}${thinkingSuffix}` : undefined;
207
+ }
208
+
209
+ function suggestAlternateProviderModel(
210
+ model: string,
211
+ availableModels: AvailableModelInfo[] | undefined,
212
+ ): string | undefined {
213
+ if (!availableModels || availableModels.length === 0) return undefined;
214
+ const { baseModel, thinkingSuffix } = splitThinkingSuffix(model);
215
+ const { queryProvider, queryIdRaw } = splitQualifiedModelQuery(baseModel, availableModels);
216
+ if (queryProvider === undefined) return undefined;
217
+ const suggestion = resolveBaseModelCandidate(queryIdRaw, availableModels);
218
+ if (!suggestion) return undefined;
219
+ const matched = availableModels.find((entry) => entry.fullId === suggestion);
220
+ if (!matched || normalizeModelSegment(matched.provider) === queryProvider) return undefined;
221
+ return `${suggestion}${thinkingSuffix}`;
222
+ }
223
+
224
+ function resolveRequiredSubagentModelCandidate(
225
+ model: string,
226
+ availableModels: AvailableModelInfo[] | undefined,
227
+ preferredProvider?: string,
228
+ ): string {
229
+ const resolved = resolveSubagentModelCandidate(model, availableModels, preferredProvider);
230
+ if (resolved) return resolved;
231
+ const suggestion = suggestAlternateProviderModel(model, availableModels);
232
+ throw new Error(
233
+ `Unknown subagent model '${model}' in the active Pi model registry.${suggestion ? ` Did you mean '${suggestion}'?` : ""}`,
234
+ );
178
235
  }
179
236
 
180
237
  export interface ResolveSubagentModelOverrideOptions {
@@ -263,6 +320,18 @@ export interface BuildModelCandidatesOptions {
263
320
  /** Fallback models warn by default and throw when strict scope enforcement is enabled. */
264
321
  scope?: ModelScopeConfig;
265
322
  onWarn?: (violation: ModelScopeViolation) => void;
323
+ /** The primary model came from the running parent session, not configuration. */
324
+ primaryModelFromParent?: boolean;
325
+ }
326
+
327
+ export function inheritsParentModel(
328
+ explicitModel: string | boolean | undefined,
329
+ agentModel: string | boolean | undefined,
330
+ parentModel: ParentModel | undefined,
331
+ ): boolean {
332
+ const requestedModel = explicitModel ?? agentModel;
333
+ const trimmed = typeof requestedModel === "string" ? requestedModel.trim() : "";
334
+ return Boolean(parentModel && (!trimmed || trimmed === INHERIT_MODEL));
266
335
  }
267
336
 
268
337
  export function buildModelCandidates(
@@ -278,8 +347,17 @@ export function buildModelCandidates(
278
347
  for (let index = 0; index < rawCandidates.length; index++) {
279
348
  const raw = rawCandidates[index];
280
349
  if (!raw) continue;
281
- const normalized = resolveRequiredSubagentModelCandidate(raw.trim(), availableModels, preferredProvider);
282
- if (!normalized || seen.has(normalized)) continue;
350
+ const model = raw.trim();
351
+ const normalized = index === 0
352
+ ? options?.primaryModelFromParent
353
+ ? model
354
+ : resolveRequiredSubagentModelCandidate(model, availableModels, preferredProvider)
355
+ : resolveSubagentModelCandidate(model, availableModels, preferredProvider);
356
+ if (!normalized) {
357
+ console.warn(`[pi-subagents] Skipping fallback model '${model}' because it is unavailable in this environment.`);
358
+ continue;
359
+ }
360
+ if (seen.has(normalized)) continue;
283
361
  if ((index > 0 || options?.scope?.strict === true) && options?.scope?.enforce) {
284
362
  const violation = checkModelScope(normalized, options.scope, "inherited");
285
363
  if (violation) {
@@ -290,11 +368,12 @@ export function buildModelCandidates(
290
368
  seen.add(normalized);
291
369
  candidates.push(normalized);
292
370
  }
293
- return candidates;
371
+ return filterFallbackCandidates(candidates);
294
372
  }
295
373
 
296
374
  const RETRYABLE_MODEL_FAILURE_PATTERNS = [
297
375
  /rate\s*limit/i,
376
+ /usage\s*limit/i,
298
377
  /too many requests/i,
299
378
  /\b429\b/,
300
379
  /quota/i,
@@ -346,6 +425,40 @@ export function isRetryableModelFailure(error: string | undefined): boolean {
346
425
  return RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));
347
426
  }
348
427
 
428
+ export function recordRetryableModelFailure(model: string | undefined, error: string | undefined): void {
429
+ if (!model || !isRetryableModelFailure(error)) return;
430
+ const { provider, modelId } = parseModelKey(model);
431
+ recordModelFailure({ modelId, reason: error, ...(provider ? { provider } : {}) });
432
+ }
433
+
434
+ /**
435
+ * Context-overflow signals. These are deliberately NOT part of
436
+ * {@link RETRYABLE_MODEL_FAILURE_PATTERNS}: an overflow means the input was too
437
+ * large for the model's context window, so retrying the same input on another
438
+ * model (or the same model again) cannot succeed. Callers should treat overflow
439
+ * as a terminal, non-retryable failure and surface a clear "input too large"
440
+ * error instead of burning fallback attempts on a guaranteed failure.
441
+ */
442
+ const CONTEXT_OVERFLOW_PATTERNS = [
443
+ /context(?: length| window| limit)? (?:exceed|overflow|too long)/i,
444
+ /maximum context length/i,
445
+ /too many tokens/i,
446
+ /token limit/i,
447
+ /context_length_exceeded/i,
448
+ /length_required/i,
449
+ /maximum.*tokens/i,
450
+ /prompt.*too long/i,
451
+ /input.*too long/i,
452
+ /exceeded.*context/i,
453
+ /context.*overflow/i,
454
+ ];
455
+
456
+ export function isContextOverflow(error: string | undefined): boolean {
457
+ if (!error) return false;
458
+ if (TOOL_FAILURE_PREFIX.test(error.trim())) return false;
459
+ return CONTEXT_OVERFLOW_PATTERNS.some((pattern) => pattern.test(error));
460
+ }
461
+
349
462
  export function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {
350
463
  const failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? 1}`;
351
464
  return nextModel
@@ -17,16 +17,29 @@ const MIRROR_FOOTER_RESERVE_BYTES = 16 * 1024;
17
17
  const COUNTER_LOCK_STALE_MS = 30_000;
18
18
  const COUNTER_LOCK_RETRIES = 200;
19
19
  const COUNTER_LOCK_RETRY_MS = 10;
20
+ const ORCA_CREATE_WAIT_TIMEOUT_MS = ORCA_CREATE_TIMEOUT_MS + ORCA_KILL_GRACE_MS + 3_000;
20
21
 
21
22
  const ORCA_CREATE_WATCHDOG_SCRIPT = [
22
23
  "const {spawn}=require('node:child_process');",
23
- "const timeout=Number(process.argv[1]),grace=Number(process.argv[2]),command=process.argv[3],args=process.argv.slice(4);",
24
- "const child=spawn(command,args,{stdio:'ignore',windowsHide:true});",
25
- "let hardKill;",
26
- "const timer=setTimeout(()=>{child.kill('SIGTERM');hardKill=setTimeout(()=>child.kill('SIGKILL'),grace)},timeout);",
27
- "const clear=()=>{clearTimeout(timer);if(hardKill)clearTimeout(hardKill)};",
28
- "child.once('error',()=>{clear();process.exitCode=1});",
29
- "child.once('close',code=>{clear();process.exitCode=code===0?0:1});",
24
+ "const fs=require('node:fs');",
25
+ "const timeout=Number(process.argv[1]),grace=Number(process.argv[2]),waitTimeout=Number(process.argv[3]);",
26
+ "const previous=process.argv[4],done=process.argv[5],command=process.argv[6],args=process.argv.slice(7);",
27
+ "function mark(){try{fs.writeFileSync(done.replace(/\\.pending$/,'.ready'),'')}catch{}}",
28
+ "function exists(file){try{return fs.existsSync(file)}catch{return false}}",
29
+ "function keepQueued(){try{const now=new Date();fs.utimesSync(done,now,now)}catch{}}",
30
+ "function predecessorReady(){if(previous==='-')return true;if(exists(previous.replace(/\\.pending$/,'.ready')))return true;try{return Date.now()-fs.statSync(previous).mtimeMs>=waitTimeout}catch{return true}}",
31
+ "function start(){",
32
+ " try{",
33
+ " const child=spawn(command,args,{stdio:'ignore',windowsHide:true});",
34
+ " let hardKill;",
35
+ " const timer=setTimeout(()=>{child.kill('SIGTERM');hardKill=setTimeout(()=>child.kill('SIGKILL'),grace)},timeout);",
36
+ " const clear=()=>{clearTimeout(timer);if(hardKill)clearTimeout(hardKill);mark()};",
37
+ " child.once('error',()=>{clear();process.exitCode=1});",
38
+ " child.once('close',code=>{clear();process.exitCode=code===0?0:1});",
39
+ " }catch{mark();process.exitCode=1}",
40
+ "}",
41
+ "if(predecessorReady())start();",
42
+ "else{(function waitPrev(){keepQueued();if(predecessorReady())return start();setTimeout(waitPrev,20)})();}",
30
43
  ].join("");
31
44
 
32
45
  const ORCA_CLEANUP_WATCHDOG_SCRIPT = [
@@ -114,7 +127,7 @@ function progressRoot(): string {
114
127
  function pruneStaleProgressFiles(root: string, now = Date.now()): void {
115
128
  try {
116
129
  for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
117
- if (!entry.isFile() || (!entry.name.endsWith(".log") && !entry.name.endsWith(".done"))) continue;
130
+ if (!entry.isFile() || (!entry.name.endsWith(".log") && !entry.name.endsWith(".done") && !entry.name.endsWith(".ready") && !entry.name.endsWith(".pending"))) continue;
118
131
  const file = path.join(root, entry.name);
119
132
  try {
120
133
  if (now - fs.statSync(file).mtimeMs > STALE_PROGRESS_MAX_AGE_MS) fs.rmSync(file, { force: true });
@@ -148,10 +161,12 @@ function resolveSequenceScope(cwd: string): string {
148
161
  }
149
162
  }
150
163
 
151
- function reserveTabSequence(root: string, cwd: string): number | undefined {
152
- const key = createHash("sha256").update(resolveSequenceScope(cwd)).digest("hex").slice(0, 20);
153
- const counterPath = path.join(root, `counter-${key}`);
154
- const lockPath = `${counterPath}.lock`;
164
+ function sequenceKey(cwd: string): string {
165
+ return createHash("sha256").update(resolveSequenceScope(cwd)).digest("hex").slice(0, 20);
166
+ }
167
+
168
+ function withSequenceLock<T>(root: string, key: string, fn: () => T): T | undefined {
169
+ const lockPath = path.join(root, `counter-${key}.lock`);
155
170
  let locked = false;
156
171
  for (let attempt = 0; attempt < COUNTER_LOCK_RETRIES; attempt++) {
157
172
  try {
@@ -171,21 +186,44 @@ function reserveTabSequence(root: string, cwd: string): number | undefined {
171
186
  }
172
187
  if (!locked) return undefined;
173
188
  try {
189
+ return fn();
190
+ } finally {
191
+ try { fs.rmSync(lockPath, { recursive: true, force: true }); } catch { /* stale lock cleanup handles crashes */ }
192
+ }
193
+ }
194
+
195
+ function predecessorMarker(pathValue: string | undefined): string | undefined {
196
+ if (!pathValue) return undefined;
197
+ const ready = pathValue.endsWith(".pending") ? pathValue.replace(/\.pending$/, ".ready") : pathValue;
198
+ const pending = ready.replace(/\.ready$/, ".pending");
199
+ if (fs.existsSync(ready) || fs.existsSync(pending)) return pending;
200
+ return undefined;
201
+ }
202
+
203
+ function reserveTabSequence(root: string, cwd: string): { sequence: number; previousCreateDone?: string; createDone: string } | undefined {
204
+ const key = sequenceKey(cwd);
205
+ const counterPath = path.join(root, `counter-${key}`);
206
+ const createDone = path.join(root, `create-${key}-${randomUUID()}.pending`);
207
+ return withSequenceLock(root, key, () => {
174
208
  let current = 0;
209
+ let previousCreateDone: string | undefined;
175
210
  try {
176
- const parsed = Number.parseInt(fs.readFileSync(counterPath, "utf-8"), 10);
211
+ const raw = fs.readFileSync(counterPath, "utf-8");
212
+ const [countLine, previousLine] = raw.split("\n");
213
+ const parsed = Number.parseInt(countLine ?? "", 10);
177
214
  if (Number.isSafeInteger(parsed) && parsed >= 0) current = parsed;
215
+ previousCreateDone = predecessorMarker(previousLine?.trim());
178
216
  } catch { /* first tab for this worktree */ }
179
217
  const next = current + 1;
180
218
  try {
181
- fs.writeFileSync(counterPath, `${next}\n`, { encoding: "utf-8", mode: 0o600 });
182
- return next;
219
+ fs.writeFileSync(createDone, "", { encoding: "utf-8", mode: 0o600 });
220
+ fs.writeFileSync(counterPath, `${next}\n${createDone}\n`, { encoding: "utf-8", mode: 0o600 });
221
+ return { sequence: next, previousCreateDone, createDone };
183
222
  } catch {
223
+ try { fs.rmSync(createDone, { force: true }); } catch { /* best effort */ }
184
224
  return undefined;
185
225
  }
186
- } finally {
187
- try { fs.rmSync(lockPath, { recursive: true, force: true }); } catch { /* stale lock cleanup handles crashes */ }
188
- }
226
+ });
189
227
  }
190
228
 
191
229
  export function resolvePiSessionId(sessionFile: string | undefined): string | undefined {
@@ -263,16 +301,21 @@ export function createOrcaProgressTab(input: {
263
301
  const agent = safeSegment(input.agent, "subagent");
264
302
  const index = typeof input.index === "number" && Number.isInteger(input.index) && input.index >= 0 ? input.index : 0;
265
303
  const cwd = typeof input.cwd === "string" && input.cwd ? input.cwd : process.cwd();
266
- const tabSequence = reserveTabSequence(root, cwd);
267
- if (tabSequence === undefined) return undefined;
304
+ const reservation = reserveTabSequence(root, cwd);
305
+ if (reservation === undefined) return undefined;
306
+ const tabSequence = reservation.sequence;
268
307
  const stem = `${runId}-${index}-${randomUUID()}`;
269
308
  const logPath = path.join(root, `${stem}.log`);
270
309
  const donePath = path.join(root, `${stem}.done`);
271
310
  const title = `subagent · ${agent} · ${tabSequence}`;
311
+ const markCreateReady = () => {
312
+ try { fs.writeFileSync(reservation.createDone.replace(/\.pending$/, ".ready"), ""); } catch { /* unblock later tabs */ }
313
+ };
272
314
  try {
273
315
  fs.writeFileSync(logPath, `pi-subagents / ${agent}\nrun ${runId} · child ${index + 1}\n${"─".repeat(48)}\n`, { encoding: "utf-8", mode: 0o600 });
274
316
  fs.rmSync(donePath, { force: true });
275
317
  } catch {
318
+ markCreateReady();
276
319
  return undefined;
277
320
  }
278
321
 
@@ -303,11 +346,21 @@ export function createOrcaProgressTab(input: {
303
346
  failObserver();
304
347
  }
305
348
  };
349
+ let createSettled = false;
350
+ let cleanupPaths: string[] | undefined;
351
+ const scheduleDeferredCleanup = () => {
352
+ if (!createSettled || cleanupPaths === undefined) return;
353
+ scheduleCleanup(nodeExecutable, cleanupPaths);
354
+ cleanupPaths = undefined;
355
+ };
306
356
  try {
307
357
  const watchdog = spawn(nodeExecutable, [
308
358
  "-e", ORCA_CREATE_WATCHDOG_SCRIPT,
309
359
  String(ORCA_CREATE_TIMEOUT_MS),
310
360
  String(ORCA_KILL_GRACE_MS),
361
+ String(ORCA_CREATE_WAIT_TIMEOUT_MS),
362
+ reservation.previousCreateDone ?? "-",
363
+ reservation.createDone,
311
364
  command,
312
365
  "terminal", "create",
313
366
  "--worktree", `path:${path.resolve(cwd)}`,
@@ -322,11 +375,19 @@ export function createOrcaProgressTab(input: {
322
375
  env: input.env ?? process.env,
323
376
  });
324
377
  watchdog.once("close", (code) => {
378
+ createSettled = true;
325
379
  if (code !== 0) failObserver();
380
+ scheduleDeferredCleanup();
381
+ });
382
+ watchdog.once("error", () => {
383
+ markCreateReady();
384
+ createSettled = true;
385
+ failObserver();
386
+ scheduleDeferredCleanup();
326
387
  });
327
- watchdog.once("error", failObserver);
328
388
  watchdog.unref();
329
389
  } catch {
390
+ markCreateReady();
330
391
  failObserver();
331
392
  return undefined;
332
393
  }
@@ -368,7 +429,8 @@ export function createOrcaProgressTab(input: {
368
429
  logStream.end(footer, () => {
369
430
  if (!available) return;
370
431
  try { fs.writeFileSync(donePath, `${status}\n`, { encoding: "utf-8", mode: 0o600 }); } catch { /* best effort */ }
371
- scheduleCleanup(nodeExecutable, [logPath, donePath]);
432
+ cleanupPaths = [logPath, donePath];
433
+ scheduleDeferredCleanup();
372
434
  });
373
435
  },
374
436
  };
@@ -34,6 +34,48 @@ function readManifest(manifestPath: string): ParallelHandoffManifest | undefined
34
34
  return parsed;
35
35
  }
36
36
 
37
+ function resolveExistingPath(candidate: string): string {
38
+ try {
39
+ return fs.realpathSync(candidate);
40
+ } catch {
41
+ return path.resolve(candidate);
42
+ }
43
+ }
44
+
45
+ function pathInside(root: string, candidate: string): boolean {
46
+ const relative = path.relative(root, candidate);
47
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
48
+ }
49
+
50
+ export function resolveRetainedWorktreeCwd(manifestPath: string, runId: string, childIndex: number): string | undefined {
51
+ const manifest = readManifest(manifestPath);
52
+ if (!manifest) return undefined;
53
+ if (manifest.runId !== runId) throw new Error(`Managed worktree handoff belongs to run '${manifest.runId}', not '${runId}'.`);
54
+ const match = manifest.groups
55
+ .flatMap((group) => group.children.map((child) => ({ group, child })))
56
+ .find(({ child }) => child.index === childIndex);
57
+ if (!match) return undefined;
58
+ const cleanup = match.group.cleanup.tasks.find((task) => task.index === match.child.taskIndex);
59
+ if (!cleanup) throw new Error(`Async run '${runId}' child ${childIndex} has no managed worktree cleanup record.`);
60
+ const relativeCwd = path.relative(resolveExistingPath(match.group.repoRoot), resolveExistingPath(manifest.cwd));
61
+ if (path.isAbsolute(relativeCwd) || relativeCwd === ".." || relativeCwd.startsWith(`..${path.sep}`)) throw new Error(`Async run '${runId}' has an invalid managed worktree cwd.`);
62
+ const requiredCwd = path.join(cleanup.path, relativeCwd);
63
+ if (cleanup.worktreeRemoved || cleanup.branchRemoved) throw new Error(`Async run '${runId}' required managed worktree was removed: ${requiredCwd}`);
64
+ let worktreeRoot = "";
65
+ let resolvedRequiredCwd = "";
66
+ try {
67
+ const rootStat = fs.lstatSync(cleanup.path);
68
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error("worktree root is not a directory");
69
+ worktreeRoot = fs.realpathSync(cleanup.path);
70
+ if (!fs.statSync(requiredCwd).isDirectory()) throw new Error("path is not a directory");
71
+ resolvedRequiredCwd = fs.realpathSync(requiredCwd);
72
+ } catch (error) {
73
+ throw new Error(`Async run '${runId}' required managed worktree cwd is missing: ${requiredCwd}`, { cause: error instanceof Error ? error : undefined });
74
+ }
75
+ if (!pathInside(worktreeRoot, resolvedRequiredCwd)) throw new Error(`Async run '${runId}' has an invalid managed worktree cwd.`);
76
+ return requiredCwd;
77
+ }
78
+
37
79
  function referenceFor(manifestPath: string, manifest: ParallelHandoffManifest): ParallelHandoffReference {
38
80
  const children = manifest.groups.flatMap((group) => group.children);
39
81
  return {
@@ -74,7 +116,7 @@ function missingDiff(input: { manifestPath: string; stepIndex: number; taskIndex
74
116
  export function writeParallelHandoffGroup(input: {
75
117
  manifestPath: string;
76
118
  runId: string;
77
- mode: "parallel" | "chain";
119
+ mode: "single" | "parallel" | "chain";
78
120
  source: "foreground" | "async";
79
121
  cwd: string;
80
122
  stepIndex: number;
@@ -162,7 +204,7 @@ export function parallelHandoffPath(baseDir: string, runId?: string): string {
162
204
  export function writePendingParallelHandoff(input: {
163
205
  manifestPath: string;
164
206
  runId: string;
165
- mode: "parallel" | "chain";
207
+ mode: "single" | "parallel" | "chain";
166
208
  source: "foreground" | "async";
167
209
  cwd: string;
168
210
  stepIndex: number;
@@ -173,11 +215,11 @@ export function writePendingParallelHandoff(input: {
173
215
  }
174
216
 
175
217
  export function formatParallelHandoffReference(reference: ParallelHandoffReference): string {
176
- return `Parallel handoff: ${reference.path} (${reference.childCount} children, ${reference.changedPatches} changed patches, cleanup ${reference.cleanupState})`;
218
+ return `Worktree handoff: ${reference.path} (${reference.childCount} children, ${reference.changedPatches} changed patches, cleanup ${reference.cleanupState})`;
177
219
  }
178
220
 
179
221
  export function formatParallelHandoffError(error: unknown): string {
180
- return `Parallel handoff unavailable: ${error instanceof Error ? error.message : String(error)}`;
222
+ return `Worktree handoff unavailable: ${error instanceof Error ? error.message : String(error)}`;
181
223
  }
182
224
 
183
225
  export function discardPreservedWorktrees(
@@ -65,13 +65,8 @@ export interface RunnerSubagentStep {
65
65
  capabilityAudit?: import("./capability-ceiling.ts").SubagentCapabilityAudit;
66
66
  /** Private stable logical-child path for inherited run fan-out accounting. */
67
67
  runFanoutPath?: string;
68
- }
69
-
70
- export interface RunnerCheckpointStep {
71
- checkpoint: string;
72
- message?: string;
73
- phase?: string;
74
- label?: string;
68
+ /** Run this single child in one managed worktree. */
69
+ worktree?: boolean;
75
70
  }
76
71
 
77
72
  export interface ParallelStepGroup {
@@ -100,11 +95,7 @@ export interface DynamicRunnerGroup {
100
95
  capabilityAudit?: import("./capability-ceiling.ts").SubagentCapabilityAudit;
101
96
  }
102
97
 
103
- export type RunnerStep = RunnerSubagentStep | ParallelStepGroup | DynamicRunnerGroup | RunnerCheckpointStep;
104
-
105
- export function isCheckpointRunnerStep(step: RunnerStep): step is RunnerCheckpointStep {
106
- return "checkpoint" in step;
107
- }
98
+ export type RunnerStep = RunnerSubagentStep | ParallelStepGroup | DynamicRunnerGroup;
108
99
 
109
100
  export function isParallelGroup(step: RunnerStep): step is ParallelStepGroup {
110
101
  return "parallel" in step && Array.isArray(step.parallel);
@@ -117,9 +108,7 @@ export function isDynamicRunnerGroup(step: RunnerStep): step is DynamicRunnerGro
117
108
  export function flattenSteps(steps: RunnerStep[]): RunnerSubagentStep[] {
118
109
  const flat: RunnerSubagentStep[] = [];
119
110
  for (const step of steps) {
120
- if (isCheckpointRunnerStep(step)) {
121
- continue;
122
- } else if (isParallelGroup(step)) {
111
+ if (isParallelGroup(step)) {
123
112
  for (const task of step.parallel) flat.push(task);
124
113
  } else if (isDynamicRunnerGroup(step)) {
125
114
  continue;
@@ -14,6 +14,10 @@ const MAX_PREVIEW_BYTES = 2048;
14
14
  const SECRET_KEY = /(?:authorization|cookie|credential|password|secret|token|api[-_]?key)/i;
15
15
  const SECRET_VALUE = /\b(?:Bearer\s+\S+|(?:sk|ghp|github_pat|xox[baprs])[-_A-Za-z0-9]{8,})\b/gi;
16
16
 
17
+ export function redactSecretValues(value: string): string {
18
+ return value.replace(SECRET_VALUE, "[redacted]");
19
+ }
20
+
17
21
  export function validatePermissionRules(value: unknown, label: string): PermissionRules | undefined {
18
22
  if (value === undefined) return undefined;
19
23
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object mapping tool names to allow, ask, or deny.`);
@@ -66,7 +70,7 @@ function redact(value: unknown, key = "", depth = 0): unknown {
66
70
  if (Array.isArray(value)) return value.slice(0, 10).map((item) => redact(item, "", depth + 1));
67
71
  if (value && typeof value === "object") return Object.fromEntries(Object.entries(value as Record<string, unknown>).slice(0, 20).map(([entryKey, entryValue]) => [entryKey, redact(entryValue, entryKey, depth + 1)]));
68
72
  if (typeof value === "string") {
69
- const redacted = value.replace(SECRET_VALUE, "[redacted]");
73
+ const redacted = redactSecretValues(value);
70
74
  return redacted.length > 500 ? `${redacted.slice(0, 500)}…` : redacted;
71
75
  }
72
76
  return value;
@@ -443,13 +443,20 @@ export function resolvePiLaunchToolPlan(
443
443
  ...internalTools,
444
444
  ]),
445
445
  ];
446
+ // Supervisor-coordination names stay in the --tools allowlist but are never
447
+ // strict requirements: children register contact_supervisor at runtime through
448
+ // the native supervisor channel (or pi-intercom). The pre-0.50 bridge always
449
+ // appended intercom alongside contact_supervisor, so that exact pairing is
450
+ // legacy plumbing, not a user demand for an external intercom provider;
451
+ // a lone intercom entry stays strictly required (#1207).
452
+ const legacySupervisorPairing = declaredBuiltinTools.includes("contact_supervisor");
446
453
  const requiredChildTools = explicitToolAllowlist
447
454
  ? [
448
455
  ...new Set([
449
456
  ...(input.tools !== undefined ? declaredBuiltinTools : []),
450
457
  ...(input.mcpDirectTools?.length ? effectiveMcpTools : []),
451
458
  ...internalTools,
452
- ]),
459
+ ].filter((tool) => tool !== "contact_supervisor" && (!legacySupervisorPairing || tool !== "intercom"))),
453
460
  ]
454
461
  : [];
455
462
  const permSystemExt = capabilityCeiling?.denyExtensions
@@ -1,4 +1,3 @@
1
- import { spawnSync } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
2
  import * as fs from "node:fs";
4
3
  import * as os from "node:os";
@@ -79,11 +78,6 @@ function getProcessStartIdentity(pid: number): string | undefined {
79
78
  return undefined;
80
79
  }
81
80
  }
82
- if (process.platform === "darwin" || process.platform === "freebsd") {
83
- const result = spawnSync("/bin/ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf-8" });
84
- const started = result.status === 0 ? result.stdout.trim() : "";
85
- return started ? `${process.platform}:${started}` : undefined;
86
- }
87
81
  return undefined;
88
82
  }
89
83