@oh-my-pi/pi-coding-agent 17.0.4 → 17.0.6

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 (143) hide show
  1. package/CHANGELOG.md +209 -0
  2. package/dist/cli.js +3616 -3676
  3. package/dist/types/advisor/advise-tool.d.ts +3 -0
  4. package/dist/types/advisor/runtime.d.ts +7 -1
  5. package/dist/types/async/job-manager.d.ts +2 -0
  6. package/dist/types/config/model-registry.d.ts +7 -0
  7. package/dist/types/config/model-resolver.d.ts +8 -0
  8. package/dist/types/config/models-config-schema.d.ts +10 -0
  9. package/dist/types/config/models-config.d.ts +6 -0
  10. package/dist/types/dap/client.d.ts +10 -0
  11. package/dist/types/dap/types.d.ts +6 -5
  12. package/dist/types/exec/bash-executor.d.ts +1 -0
  13. package/dist/types/extensibility/extensions/load-errors.d.ts +3 -0
  14. package/dist/types/extensibility/extensions/runner.d.ts +4 -2
  15. package/dist/types/extensibility/legacy-pi-coding-agent-shim.d.ts +16 -0
  16. package/dist/types/extensibility/plugins/legacy-pi-compat.d.ts +8 -0
  17. package/dist/types/launch/spawn-options.d.ts +10 -0
  18. package/dist/types/launch/spawn-options.test.d.ts +1 -0
  19. package/dist/types/modes/components/status-line/component.d.ts +10 -3
  20. package/dist/types/modes/components/status-line/types.d.ts +3 -1
  21. package/dist/types/modes/components/tool-execution.d.ts +2 -0
  22. package/dist/types/modes/components/transcript-container.d.ts +4 -3
  23. package/dist/types/modes/components/tree-selector.d.ts +6 -2
  24. package/dist/types/modes/components/usage-row.d.ts +1 -1
  25. package/dist/types/modes/interactive-mode.d.ts +2 -0
  26. package/dist/types/modes/print-mode.d.ts +4 -0
  27. package/dist/types/modes/rpc/rpc-client.d.ts +1 -1
  28. package/dist/types/modes/rpc/rpc-frame.d.ts +9 -0
  29. package/dist/types/modes/rpc/rpc-input.d.ts +5 -0
  30. package/dist/types/modes/rpc/rpc-mode.d.ts +1 -1
  31. package/dist/types/modes/setup-wizard/index.d.ts +1 -1
  32. package/dist/types/modes/setup-wizard/scenes/model.d.ts +3 -0
  33. package/dist/types/modes/types.d.ts +2 -0
  34. package/dist/types/sdk.d.ts +2 -0
  35. package/dist/types/session/agent-session.d.ts +42 -6
  36. package/dist/types/session/messages.d.ts +6 -0
  37. package/dist/types/session/session-paths.d.ts +21 -4
  38. package/dist/types/tools/browser/aria/aria-snapshot.d.ts +17 -7
  39. package/dist/types/tools/browser/cmux/socket-client.d.ts +2 -0
  40. package/dist/types/tools/browser/tab-protocol.d.ts +2 -0
  41. package/dist/types/tools/browser/tab-worker.d.ts +2 -0
  42. package/dist/types/tools/gh.d.ts +5 -3
  43. package/dist/types/tools/hub/index.d.ts +1 -1
  44. package/dist/types/tools/hub/jobs.d.ts +1 -0
  45. package/dist/types/tools/hub/types.d.ts +2 -0
  46. package/dist/types/tools/tool-timeouts.d.ts +1 -1
  47. package/dist/types/tools/xdev.d.ts +5 -3
  48. package/dist/types/utils/git.d.ts +33 -0
  49. package/dist/types/vibe/__tests__/token-rate.test.d.ts +1 -0
  50. package/dist/types/vibe/runtime.d.ts +23 -0
  51. package/dist/types/web/search/providers/codex.d.ts +1 -1
  52. package/package.json +12 -12
  53. package/src/advisor/__tests__/advisor.test.ts +150 -0
  54. package/src/advisor/advise-tool.ts +4 -0
  55. package/src/advisor/runtime.ts +38 -14
  56. package/src/async/job-manager.ts +3 -0
  57. package/src/cli/bench-cli.ts +8 -2
  58. package/src/cli/dry-balance-cli.ts +1 -0
  59. package/src/config/model-registry.ts +89 -8
  60. package/src/config/model-resolver.ts +78 -14
  61. package/src/config/models-config-schema.ts +1 -0
  62. package/src/config/settings.ts +3 -1
  63. package/src/dap/client.ts +168 -1
  64. package/src/dap/config.ts +51 -1
  65. package/src/dap/session.ts +575 -234
  66. package/src/dap/types.ts +6 -5
  67. package/src/discovery/agents.ts +2 -2
  68. package/src/exec/bash-executor.ts +68 -8
  69. package/src/extensibility/extensions/load-errors.ts +13 -0
  70. package/src/extensibility/extensions/runner.ts +6 -4
  71. package/src/extensibility/legacy-pi-coding-agent-shim.ts +26 -0
  72. package/src/extensibility/plugins/legacy-pi-compat.ts +41 -6
  73. package/src/launch/broker.ts +34 -31
  74. package/src/launch/client.ts +7 -1
  75. package/src/launch/spawn-options.test.ts +31 -0
  76. package/src/launch/spawn-options.ts +17 -0
  77. package/src/lsp/types.ts +5 -1
  78. package/src/main.ts +25 -4
  79. package/src/mcp/transports/stdio.test.ts +9 -1
  80. package/src/modes/components/ask-dialog.ts +137 -73
  81. package/src/modes/components/chat-transcript-builder.ts +10 -1
  82. package/src/modes/components/status-line/component.ts +57 -3
  83. package/src/modes/components/status-line/segments.ts +20 -3
  84. package/src/modes/components/status-line/types.ts +3 -1
  85. package/src/modes/components/tool-execution.ts +5 -0
  86. package/src/modes/components/transcript-container.ts +23 -122
  87. package/src/modes/components/tree-selector.ts +10 -4
  88. package/src/modes/components/usage-row.ts +17 -1
  89. package/src/modes/controllers/command-controller.ts +41 -1
  90. package/src/modes/controllers/event-controller.ts +7 -3
  91. package/src/modes/controllers/input-controller.ts +1 -1
  92. package/src/modes/controllers/selector-controller.ts +29 -8
  93. package/src/modes/interactive-mode.ts +102 -60
  94. package/src/modes/noninteractive-dispose.test.ts +14 -1
  95. package/src/modes/print-mode.ts +81 -9
  96. package/src/modes/rpc/rpc-client.ts +76 -35
  97. package/src/modes/rpc/rpc-frame.ts +156 -0
  98. package/src/modes/rpc/rpc-input.ts +38 -0
  99. package/src/modes/rpc/rpc-mode.ts +11 -4
  100. package/src/modes/setup-wizard/index.ts +2 -0
  101. package/src/modes/setup-wizard/scenes/model.ts +134 -0
  102. package/src/modes/setup-wizard/scenes/sign-in.ts +3 -1
  103. package/src/modes/types.ts +2 -0
  104. package/src/modes/utils/ui-helpers.ts +9 -3
  105. package/src/prompts/system/workflow-notice.md +89 -74
  106. package/src/prompts/tools/browser.md +3 -2
  107. package/src/prompts/tools/debug.md +2 -7
  108. package/src/prompts/tools/github.md +6 -1
  109. package/src/prompts/tools/hub.md +4 -2
  110. package/src/prompts/tools/task-async-contract.md +1 -0
  111. package/src/prompts/tools/task.md +9 -2
  112. package/src/sdk.ts +38 -6
  113. package/src/session/agent-session.ts +484 -188
  114. package/src/session/messages.test.ts +91 -0
  115. package/src/session/messages.ts +248 -110
  116. package/src/session/session-manager.ts +34 -3
  117. package/src/session/session-paths.ts +38 -9
  118. package/src/slash-commands/builtin-registry.ts +1 -0
  119. package/src/task/executor.ts +104 -33
  120. package/src/task/index.ts +46 -9
  121. package/src/task/worktree.ts +10 -0
  122. package/src/tools/browser/aria/aria-snapshot.ts +36 -8
  123. package/src/tools/browser/cmux/cmux-tab.ts +2 -1
  124. package/src/tools/browser/cmux/socket-client.ts +139 -3
  125. package/src/tools/browser/run-cancellation.ts +4 -0
  126. package/src/tools/browser/tab-protocol.ts +2 -0
  127. package/src/tools/browser/tab-supervisor.ts +21 -11
  128. package/src/tools/browser/tab-worker.ts +199 -33
  129. package/src/tools/debug.ts +3 -0
  130. package/src/tools/gh.ts +40 -2
  131. package/src/tools/hub/index.ts +4 -1
  132. package/src/tools/hub/jobs.ts +42 -1
  133. package/src/tools/hub/types.ts +2 -0
  134. package/src/tools/tool-timeouts.ts +1 -1
  135. package/src/tools/xdev.ts +11 -4
  136. package/src/tools/yield.ts +4 -1
  137. package/src/utils/git.ts +237 -0
  138. package/src/{modes/components/status-line → utils}/token-rate.ts +6 -0
  139. package/src/vibe/__tests__/token-rate.test.ts +96 -0
  140. package/src/vibe/runtime.ts +50 -0
  141. package/src/web/search/index.ts +9 -5
  142. package/src/web/search/providers/codex.ts +195 -99
  143. /package/dist/types/{modes/components/status-line → utils}/token-rate.d.ts +0 -0
@@ -15,6 +15,7 @@ import {
15
15
  formatModelSelectorValue,
16
16
  formatModelStringWithRouting,
17
17
  resolveAgentPrewalkPattern,
18
+ resolveConfiguredModelPatterns,
18
19
  resolveModelOverride,
19
20
  resolveModelOverrideWithAuthFallback,
20
21
  } from "../config/model-resolver";
@@ -161,22 +162,44 @@ function resolveSubagentRetryFallbackCandidates(
161
162
  return candidates;
162
163
  }
163
164
 
165
+ function resolveSubagentDefaultRetryFallbackChain(settings: Settings): string[] | undefined {
166
+ const fallbackChain = settings.get("retry.fallbackChains")?.default;
167
+ if (
168
+ !Array.isArray(fallbackChain) ||
169
+ fallbackChain.length === 0 ||
170
+ !fallbackChain.every(entry => typeof entry === "string")
171
+ ) {
172
+ return undefined;
173
+ }
174
+ return fallbackChain;
175
+ }
176
+
164
177
  function installSubagentRetryFallbackChain(args: {
165
178
  settings: Settings;
166
179
  id: string;
167
180
  candidates: SubagentRetryFallbackCandidate[];
181
+ defaultFallbackChain: string[] | undefined;
168
182
  model: Model<Api> | undefined;
169
183
  authFallbackUsed: boolean;
170
184
  }): string | undefined {
171
- const { settings, id, candidates, model, authFallbackUsed } = args;
172
- if (!model || authFallbackUsed || candidates.length <= 1) return undefined;
185
+ const { settings, id, candidates, defaultFallbackChain, model, authFallbackUsed } = args;
186
+ if (!model || authFallbackUsed || candidates.length === 0) return undefined;
173
187
 
174
188
  const selectedIndex = candidates.findIndex(
175
189
  candidate => candidate.model.provider === model.provider && candidate.model.id === model.id,
176
190
  );
177
191
  if (selectedIndex < 0) return undefined;
178
192
  const fallbackSelectors = candidates.slice(selectedIndex + 1).map(candidate => candidate.selector);
179
- if (fallbackSelectors.length === 0) return undefined;
193
+ const existingFallbackChains = settings.get("retry.fallbackChains");
194
+ // A single explicit model may reuse a configured default chain, but never an implicit parent fallback.
195
+ const fallbackChain = fallbackSelectors.length > 0 ? fallbackSelectors : defaultFallbackChain;
196
+ if (
197
+ !Array.isArray(fallbackChain) ||
198
+ fallbackChain.length === 0 ||
199
+ !fallbackChain.every(entry => typeof entry === "string")
200
+ ) {
201
+ return undefined;
202
+ }
180
203
 
181
204
  const role = `${SUBAGENT_RETRY_FALLBACK_ROLE_PREFIX}${id}`;
182
205
  const modelRoles: Record<string, string> = {};
@@ -189,10 +212,10 @@ function installSubagentRetryFallbackChain(args: {
189
212
  }
190
213
  modelRoles[role] = candidates[selectedIndex].selector;
191
214
  settings.override("modelRoles", modelRoles);
215
+ // Insert the task-specific role first so another role assigned to the same model cannot capture fallback routing.
192
216
  const fallbackChains: Record<string, string[]> = {
193
- [role]: fallbackSelectors,
217
+ [role]: fallbackChain,
194
218
  };
195
- const existingFallbackChains = settings.get("retry.fallbackChains");
196
219
  for (const existingRole in existingFallbackChains) {
197
220
  if (existingRole !== role) {
198
221
  fallbackChains[existingRole] = existingFallbackChains[existingRole];
@@ -805,6 +828,8 @@ export function createSubagentSettings(
805
828
 
806
829
  export type AbortReason = "signal" | "terminate" | "timeout" | "budget";
807
830
 
831
+ const MAX_YIELD_TOOL_ERRORS = 6;
832
+
808
833
  /** Inputs for the run monitor driving one subagent assignment. */
809
834
  interface RunMonitorArgs {
810
835
  index: number;
@@ -851,11 +876,13 @@ interface SubagentRunMonitor {
851
876
  waitForBudgetStop(): Promise<void>;
852
877
  /** The abort kind for this run, when an abort was requested. */
853
878
  abortKind(): AbortReason | undefined;
879
+ terminalError(): string | undefined;
854
880
  /** True when the abort carries a precise external reason (signal / wall-clock / budget). */
855
881
  hasExplicitAbortReason(): boolean;
856
882
  /** Whether the (attempted) abort counts as a cancelled run rather than an internal failure. */
857
883
  isAbortedRun(): boolean;
858
884
  requestAbort(reason: AbortReason): void;
885
+ failWithError(message: string): void;
859
886
  abortActiveSession(): Promise<void>;
860
887
  waitForActiveSessionAbort(): Promise<void>;
861
888
  resolveSignalAbortReason(): string;
@@ -914,7 +941,7 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
914
941
  const finalOutputChunks: string[] = [];
915
942
  const RECENT_OUTPUT_TAIL_BYTES = 8 * 1024;
916
943
  let recentOutputTail = "";
917
- let tailLastLineRepresentable = false;
944
+ let recentOutputDirty = false;
918
945
  let resolved = false;
919
946
  let abortSent = false;
920
947
  let abortReason: AbortReason | undefined;
@@ -942,6 +969,8 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
942
969
  let budgetLimitExceeded = false;
943
970
  let budgetStopRequested = false;
944
971
  let budgetStopAbortPromise: Promise<void> | undefined;
972
+ let terminalError: string | undefined;
973
+ let consecutiveYieldToolErrors = 0;
945
974
  let lastAssistantSalvageText: string | undefined;
946
975
  let activeSessionAbortPromise: Promise<void> | undefined;
947
976
 
@@ -998,6 +1027,11 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
998
1027
  : Promise.resolve();
999
1028
  };
1000
1029
 
1030
+ const failWithError = (message: string) => {
1031
+ terminalError ??= message;
1032
+ requestAbort("terminate");
1033
+ };
1034
+
1001
1035
  // Handle abort signal
1002
1036
  if (signal) {
1003
1037
  signal.addEventListener(
@@ -1054,7 +1088,22 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1054
1088
  let lastProgressEmitMs = 0;
1055
1089
  let progressTimeoutId: NodeJS.Timeout | null = null;
1056
1090
 
1091
+ // Recompute progress.recentOutput from the capped tail. Deferred: text_delta
1092
+ // appends only extend the tail and mark it dirty; the (up to 8KB) split/filter
1093
+ // runs synchronously here, immediately before the ONLY places the progress
1094
+ // object is snapshotted ({...progress} for onProgress and the eventBus
1095
+ // progress channel, both inside emitProgressNow — including the
1096
+ // scheduleProgress(flush) finalize/error/cancel paths). Observers therefore
1097
+ // always see exact state; no staleness beyond the existing 150ms coalescing.
1098
+ const refreshRecentOutput = () => {
1099
+ if (!recentOutputDirty) return;
1100
+ recentOutputDirty = false;
1101
+ const filtered = recentOutputTail.split("\n").filter(line => line.trim());
1102
+ progress.recentOutput = filtered.slice(-8).reverse();
1103
+ };
1104
+
1057
1105
  const emitProgressNow = () => {
1106
+ refreshRecentOutput();
1058
1107
  progress.durationMs = Date.now() - startTime;
1059
1108
  onProgress?.({ ...progress });
1060
1109
  const activityGist =
@@ -1137,36 +1186,16 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1137
1186
  return message.usage;
1138
1187
  };
1139
1188
 
1140
- const updateRecentOutputLines = () => {
1141
- const lines = recentOutputTail.split("\n");
1142
- const filtered = lines.filter(line => line.trim());
1143
- progress.recentOutput = filtered.slice(-8).reverse();
1144
- // The tail's last raw segment (after its final newline) is "represented"
1145
- // in recentOutput only when it trims non-empty — an empty/whitespace-only
1146
- // trailing segment is filtered out, so recentOutput[0] is then the line
1147
- // before it, not the tail's true last line.
1148
- tailLastLineRepresentable = lines[lines.length - 1].trim().length > 0;
1149
- };
1150
-
1151
1189
  const appendRecentOutputTail = (text: string) => {
1152
1190
  if (!text) return;
1153
1191
  recentOutputTail += text;
1154
- const truncated = recentOutputTail.length > RECENT_OUTPUT_TAIL_BYTES;
1155
- if (truncated) {
1192
+ if (recentOutputTail.length > RECENT_OUTPUT_TAIL_BYTES) {
1156
1193
  recentOutputTail = recentOutputTail.slice(-RECENT_OUTPUT_TAIL_BYTES);
1157
1194
  }
1158
- // Fast path: a token without a newline only extends the current last line.
1159
- // This runs on every text_delta token (hundreds/thousands per second while
1160
- // streaming), so skip re-splitting the whole (up to 8KB) tail unless the line
1161
- // structure actually changed. Requires no truncation AND the tail's last line
1162
- // already represented (trims non-empty) — otherwise boundaries shift and a
1163
- // full recompute is required. Appending to a non-empty line keeps it non-empty,
1164
- // so the flag stays valid across consecutive fast-path tokens.
1165
- if (truncated || text.includes("\n") || !tailLastLineRepresentable || progress.recentOutput.length === 0) {
1166
- updateRecentOutputLines();
1167
- } else {
1168
- progress.recentOutput = [progress.recentOutput[0] + text, ...progress.recentOutput.slice(1)];
1169
- }
1195
+ // O(chunk) hot path: this runs on every text_delta token (hundreds/
1196
+ // thousands per second while streaming). Line reconstruction is deferred
1197
+ // to refreshRecentOutput() at the emit boundary.
1198
+ recentOutputDirty = true;
1170
1199
  };
1171
1200
 
1172
1201
  const replaceRecentOutputFromContent = (content: unknown[]) => {
@@ -1181,12 +1210,12 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1181
1210
  recentOutputTail = recentOutputTail.slice(-RECENT_OUTPUT_TAIL_BYTES);
1182
1211
  }
1183
1212
  }
1184
- updateRecentOutputLines();
1213
+ recentOutputDirty = true;
1185
1214
  };
1186
1215
 
1187
1216
  const resetRecentOutput = () => {
1188
1217
  recentOutputTail = "";
1189
- tailLastLineRepresentable = false;
1218
+ recentOutputDirty = false;
1190
1219
  progress.recentOutput = [];
1191
1220
  };
1192
1221
 
@@ -1305,6 +1334,37 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1305
1334
  requestAbort("terminate");
1306
1335
  }
1307
1336
  }
1337
+ if (event.toolName === "yield") {
1338
+ if (event.isError && !abortSent) {
1339
+ consecutiveYieldToolErrors++;
1340
+ let yieldErrorText = "";
1341
+ const resultContent = event.result?.content;
1342
+ if (Array.isArray(resultContent)) {
1343
+ const textParts: string[] = [];
1344
+ for (const block of resultContent) {
1345
+ if (
1346
+ block &&
1347
+ typeof block === "object" &&
1348
+ "type" in block &&
1349
+ block.type === "text" &&
1350
+ "text" in block &&
1351
+ typeof block.text === "string"
1352
+ ) {
1353
+ textParts.push(block.text);
1354
+ }
1355
+ }
1356
+ yieldErrorText = textParts.join("\n").trim();
1357
+ }
1358
+ if (consecutiveYieldToolErrors >= MAX_YIELD_TOOL_ERRORS) {
1359
+ const suffix = yieldErrorText ? ` Last yield error: ${yieldErrorText}` : "";
1360
+ failWithError(
1361
+ `Subagent submitted invalid yield results ${consecutiveYieldToolErrors} times; stopping to avoid an infinite submit loop.${suffix}`,
1362
+ );
1363
+ }
1364
+ } else if (!event.isError) {
1365
+ consecutiveYieldToolErrors = 0;
1366
+ }
1367
+ }
1308
1368
  flushProgress = true;
1309
1369
  break;
1310
1370
  }
@@ -1540,6 +1600,7 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1540
1600
  hasUsage: () => hasUsage,
1541
1601
  yieldCalled: () => yieldCalled,
1542
1602
  runtimeLimitExceeded: () => runtimeLimitExceeded,
1603
+ terminalError: () => terminalError,
1543
1604
  hasExplicitAbortReason: () =>
1544
1605
  abortReason === "signal" || runtimeLimitExceeded || budgetLimitExceeded || budgetStopRequested,
1545
1606
  budgetStopRequested: () => budgetStopRequested,
@@ -1550,6 +1611,7 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1550
1611
  isAbortedRun: () =>
1551
1612
  abortReason === "signal" || runtimeLimitExceeded || budgetLimitExceeded || abortReason === undefined,
1552
1613
  requestAbort,
1614
+ failWithError,
1553
1615
  abortActiveSession,
1554
1616
  waitForActiveSessionAbort,
1555
1617
  resolveSignalAbortReason,
@@ -1745,6 +1807,7 @@ async function driveSessionToYield(
1745
1807
  }
1746
1808
  }
1747
1809
  } finally {
1810
+ error ??= monitor.terminalError();
1748
1811
  if (abortSignal.aborted && (!monitor.yieldCalled() || monitor.runtimeLimitExceeded())) {
1749
1812
  aborted = monitor.isAbortedRun();
1750
1813
  if (aborted) {
@@ -2319,6 +2382,11 @@ export async function runSubprocess(options: ExecutorOptions): Promise<SingleRes
2319
2382
  }
2320
2383
  checkAbort();
2321
2384
 
2385
+ const configuredModelPatterns = resolveConfiguredModelPatterns(modelPatterns, settings);
2386
+ const defaultRetryFallbackChain =
2387
+ configuredModelPatterns.length === 1
2388
+ ? resolveSubagentDefaultRetryFallbackChain(subagentSettings)
2389
+ : undefined;
2322
2390
  const {
2323
2391
  model,
2324
2392
  thinkingLevel: resolvedThinkingLevel,
@@ -2352,6 +2420,7 @@ export async function runSubprocess(options: ExecutorOptions): Promise<SingleRes
2352
2420
  settings: subagentSettings,
2353
2421
  id,
2354
2422
  candidates: resolveSubagentRetryFallbackCandidates(modelPatterns, modelRegistry, settings),
2423
+ defaultFallbackChain: defaultRetryFallbackChain,
2355
2424
  model,
2356
2425
  authFallbackUsed,
2357
2426
  });
@@ -2479,6 +2548,8 @@ export async function runSubprocess(options: ExecutorOptions): Promise<SingleRes
2479
2548
  model || modelOverride === undefined ? undefined : options.parentActiveModelPattern,
2480
2549
  modelPatternFallbackRole:
2481
2550
  model || modelOverride === undefined ? undefined : `${SUBAGENT_RETRY_FALLBACK_ROLE_PREFIX}${id}`,
2551
+ modelPatternDefaultFallbackChain:
2552
+ model || modelOverride === undefined ? undefined : defaultRetryFallbackChain,
2482
2553
  thinkingLevel: effectiveThinkingLevel,
2483
2554
  toolNames,
2484
2555
  outputSchema,
package/src/task/index.ts CHANGED
@@ -21,6 +21,7 @@ import type { ToolSession } from "..";
21
21
  import type { Theme } from "../modes/theme/theme";
22
22
  import subagentUserPromptTemplate from "../prompts/system/subagent-user-prompt.md" with { type: "text" };
23
23
  import taskDescriptionTemplate from "../prompts/tools/task.md" with { type: "text" };
24
+ import taskAsyncContractTemplate from "../prompts/tools/task-async-contract.md" with { type: "text" };
24
25
  import taskSummaryTemplate from "../prompts/tools/task-summary.md" with { type: "text" };
25
26
  import { truncateForPrompt } from "../tools/approval";
26
27
  import { isIrcEnabled } from "../tools/hub";
@@ -894,14 +895,16 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
894
895
  failedSchedules.length > 0
895
896
  ? ` Failed to schedule ${failedSchedules.length} spawn${failedSchedules.length === 1 ? "" : "s"}: ${failedSchedules.join("; ")}.`
896
897
  : "";
897
- const coordinationHint =
898
+ const coordinationHint = [
898
899
  started.length === 1
899
900
  ? ircEnabled
900
901
  ? `DM \`${started[0].agentId}\` via \`hub\` send to coordinate while it runs; use \`hub\` only to inspect (\`jobs\`), wait, or cancel a stuck task.`
901
902
  : `Use \`hub\` to inspect (\`jobs\`), wait, or cancel a stuck task.`
902
903
  : ircEnabled
903
904
  ? `DM these ids via \`hub\` send to coordinate while they run; use \`hub\` only to inspect (\`jobs\`), wait, or cancel a stuck task.`
904
- : `Use \`hub\` to inspect (\`jobs\`), wait, or cancel a stuck task by id.`;
905
+ : `Use \`hub\` to inspect (\`jobs\`), wait, or cancel a stuck task by id.`,
906
+ taskAsyncContractTemplate.trim(),
907
+ ].join("\n");
905
908
 
906
909
  if (syncSpawns.length === 0) {
907
910
  if (spawns.length === 1) {
@@ -915,7 +918,7 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
915
918
  content: [
916
919
  {
917
920
  type: "text",
918
- text: `Spawned agent \`${agentId}\` (job \`${jobId}\`). The result will be delivered when it yields. ${coordinationHint}`,
921
+ text: `Spawned agent \`${agentId}\` (job \`${jobId}\`). Its result auto-delivers on yield unless a settled \`hub jobs\`/\`wait\` snapshot consumes it first. ${coordinationHint}`,
919
922
  },
920
923
  ],
921
924
  details: buildAsyncDetails(),
@@ -932,7 +935,7 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
932
935
  content: [
933
936
  {
934
937
  type: "text",
935
- text: `Spawned ${started.length} background agents using ${agentLabel}.${scheduleFailureSummary} Each result will be delivered when that agent yields.\n${startedListing}\n${coordinationHint}`,
938
+ text: `Spawned ${started.length} background agents using ${agentLabel}.${scheduleFailureSummary} Each result auto-delivers on yield unless a settled \`hub jobs\`/\`wait\` snapshot consumes it first.\n${startedListing}\n${coordinationHint}`,
936
939
  },
937
940
  ],
938
941
  details: buildAsyncDetails(),
@@ -997,7 +1000,7 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
997
1000
 
998
1001
  const spawnedSummary =
999
1002
  started.length > 0
1000
- ? `Spawned ${started.length} background agent${started.length === 1 ? "" : "s"}.${scheduleFailureSummary} Each result will be delivered when that agent yields.\n${started.map(({ agentId, jobId }) => `- \`${agentId}\` (job \`${jobId}\`)`).join("\n")}\n${coordinationHint}`
1003
+ ? `Spawned ${started.length} background agent${started.length === 1 ? "" : "s"}.${scheduleFailureSummary} Each result auto-delivers on yield unless a settled \`hub jobs\`/\`wait\` snapshot consumes it first.\n${started.map(({ agentId, jobId }) => `- \`${agentId}\` (job \`${jobId}\`)`).join("\n")}\n${coordinationHint}`
1001
1004
  : scheduleFailureSummary.trim();
1002
1005
  const text = [merged.contentParts.join("\n\n"), spawnedSummary]
1003
1006
  .filter(section => section.trim().length > 0)
@@ -1078,12 +1081,41 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
1078
1081
  try {
1079
1082
  markRunning();
1080
1083
  progress.status = "running";
1081
- await reportProgress(`Running background task ${agentId}...`);
1084
+ await reportProgress(
1085
+ `Running background task ${agentId}...`,
1086
+ buildDetails() as unknown as Record<string, unknown>,
1087
+ );
1088
+ const forwardSyncProgress: AgentToolUpdateCallback<TaskToolDetails> = async update => {
1089
+ const nextProgress = update.details?.progress?.[0];
1090
+ if (nextProgress) {
1091
+ // The job body owns status and identity (id/index/agent);
1092
+ // copy only the live metrics the subagent streams so the
1093
+ // polling row reflects the resolved model, reasoning level,
1094
+ // and running counters without reverting the "running"
1095
+ // status back to the subagent's initial "pending" snapshot.
1096
+ progress.resolvedModel = nextProgress.resolvedModel;
1097
+ progress.tokens = nextProgress.tokens;
1098
+ progress.requests = nextProgress.requests;
1099
+ progress.contextTokens = nextProgress.contextTokens;
1100
+ progress.contextWindow = nextProgress.contextWindow;
1101
+ progress.cost = nextProgress.cost;
1102
+ progress.toolCount = nextProgress.toolCount;
1103
+ progress.currentTool = nextProgress.currentTool;
1104
+ progress.lastIntent = nextProgress.lastIntent;
1105
+ progress.recentTools = nextProgress.recentTools.slice();
1106
+ progress.recentOutput = nextProgress.recentOutput.slice();
1107
+ progress.retryState = nextProgress.retryState;
1108
+ progress.retryFailure = nextProgress.retryFailure;
1109
+ }
1110
+ const updateText =
1111
+ update.content.find(part => part.type === "text")?.text ?? `Running background task ${agentId}...`;
1112
+ await reportProgress(updateText, buildDetails() as unknown as Record<string, unknown>);
1113
+ };
1082
1114
  const result = await this.#executeSync(
1083
1115
  toolCallId,
1084
1116
  spawnParams,
1085
1117
  runSignal,
1086
- undefined,
1118
+ forwardSyncProgress,
1087
1119
  agentId,
1088
1120
  progress.index,
1089
1121
  true,
@@ -1104,11 +1136,16 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
1104
1136
  progress.extractedToolData = singleResult?.extractedToolData;
1105
1137
  progress.retryFailure = singleResult?.retryFailure;
1106
1138
  progress.retryState = undefined;
1139
+ if (singleResult?.resolvedModel) {
1140
+ progress.resolvedModel = singleResult.resolvedModel;
1141
+ } else {
1142
+ delete progress.resolvedModel;
1143
+ }
1107
1144
  onSettled?.(resultFailed);
1108
1145
  const statusText = resultFailed
1109
1146
  ? `Background task ${agentId} failed.`
1110
1147
  : `Background task ${agentId} complete.`;
1111
- await reportProgress(statusText);
1148
+ await reportProgress(statusText, buildDetails() as unknown as Record<string, unknown>);
1112
1149
  const deliveryText = `${finalText}${buildFollowUpHint(singleResult?.aborted === true)}`;
1113
1150
  if (resultFailed) {
1114
1151
  // Mark the job itself failed; the failed agent stays interrogable.
@@ -1123,7 +1160,7 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
1123
1160
  progress.durationMs = Math.max(0, Date.now() - startedAt);
1124
1161
  onSettled?.(true);
1125
1162
  const statusText = `Background task ${agentId} failed.`;
1126
- await reportProgress(statusText);
1163
+ await reportProgress(statusText, buildDetails() as unknown as Record<string, unknown>);
1127
1164
  const message = error instanceof Error ? error.message : String(error);
1128
1165
  const hint = AgentRegistry.global().get(agentId) ? buildFollowUpHint(false) : "";
1129
1166
  throw new TaskJobError(`${message}${hint}`);
@@ -414,6 +414,8 @@ export async function ensureIsolation(
414
414
  preferred?: IsoBackendKind,
415
415
  ): Promise<IsolationHandle> {
416
416
  const repoRoot = await getRepoRoot(baseCwd);
417
+ const repository = await git.repo.resolve(repoRoot);
418
+ const sourceCommonDir = repository?.commonDir ?? path.join(repoRoot, ".git");
417
419
  const baseDir = getWorktreeDir(getTaskIsolationSegment(repoRoot, id));
418
420
  const mergedDir = path.join(baseDir, TASK_ISOLATION_MOUNT_DIR);
419
421
  const resolution = natives.isoResolve(preferred ?? null);
@@ -424,6 +426,14 @@ export async function ensureIsolation(
424
426
  await fs.rm(baseDir, { recursive: true, force: true });
425
427
  try {
426
428
  await natives.isoStart(candidate, repoRoot, mergedDir);
429
+ // Sever the isolation's git metadata from the source checkout. Copy
430
+ // backends duplicate `repoRoot`'s `.git` verbatim — a linked-worktree
431
+ // pointer file (or the rcopy `git worktree add` registration) leaves
432
+ // the isolation sharing the source's HEAD/index/ref namespace, so a
433
+ // task's git operations would mutate the parent checkout and stack
434
+ // parallel task branches. Detaching gives each isolation a private,
435
+ // frozen repo that still borrows the source object DB via alternates.
436
+ await git.detachGitDir(mergedDir, sourceCommonDir);
427
437
  return {
428
438
  mergedDir,
429
439
  backend: candidate,
@@ -1,4 +1,5 @@
1
1
  import type { ElementHandle, JSHandle, Page } from "puppeteer-core";
2
+ import { ToolError } from "../../tool-errors";
2
3
  import ariaBundle from "./aria-snapshot.bundle.txt" with { type: "text" };
3
4
  // `aria-snapshot.bundle.txt` is a generated, committed artifact: Playwright's
4
5
  // injected ARIA-snapshot sources (pinned, Apache-2.0) bundled to a CJS module.
@@ -69,15 +70,41 @@ export async function resolveAriaRefHandle(page: Page, ref: string): Promise<Ele
69
70
  const ARIA_REF_PREFIXES = ["aria-ref=", "aria-ref/", "ariaref/"];
70
71
 
71
72
  /**
72
- * Recognize the explicit `[ref=eN]` selector forms and return the bare ref id,
73
- * else null. Accepts `aria-ref=e5` (Playwright-MCP style), `aria-ref/e5`, and
74
- * `ariaref/e5` — lets `tab.click("aria-ref=e5")` etc. act on snapshot refs. A
75
- * bare `e5` is intentionally NOT a ref selector: the cmux backend already uses
76
- * bare `eN`/`@eN` for its own observe ids, so requiring the prefix keeps action
77
- * selectors meaning the same thing on both backends. (`tab.ref("e5")` still
78
- * accepts a bare id directly.)
73
+ * Guard the selector funnels: `tab.click`/`type`/`fill`/`waitFor*`/`scrollIntoView`
74
+ * take string selectors only, but user `run` code routinely passes the ElementHandle
75
+ * from `tab.id(n)`/`tab.ref(...)` (or an un-awaited Promise of one) straight in.
76
+ * Without this the value reaches `.trim()`/`.startsWith()` and throws the opaque,
77
+ * minified `A.trim is not a function` instead of a recovery-naming ToolError.
78
+ */
79
+ export function assertSelectorString(selector: unknown): asserts selector is string {
80
+ if (typeof selector === "string") return;
81
+ let kind: string;
82
+ if (selector !== null && typeof selector === "object") {
83
+ kind =
84
+ "then" in selector && typeof selector.then === "function" ? "a Promise (missing await?)" : "an ElementHandle";
85
+ } else {
86
+ kind = `a ${typeof selector}`;
87
+ }
88
+ throw new ToolError(
89
+ `Browser selector must be a string; got ${kind}. ` +
90
+ "tab.click/type/fill/waitFor take string selectors only — " +
91
+ 'call the handle method directly (e.g. (await tab.id(n)).click()) or pass a string like "aria-ref=eN".',
92
+ );
93
+ }
94
+
95
+ /**
96
+ * Recognize a snapshot-ref selector and return the bare ref id, else null.
97
+ * Accepts `aria-ref=e5` (Playwright-MCP style), `aria-ref/e5`, `ariaref/e5`,
98
+ * and bare `e5`/`@e5`: agents copy ids straight out of the snapshot YAML
99
+ * (`[ref=e5]`), so `tab.click("e5")` must act on the ref instead of falling
100
+ * through to a CSS tag selector that can never match. Bare ids are safe to
101
+ * claim here — an eN tag name is not real HTML, and the tab-worker backend's
102
+ * observe ids are numeric (`tab.id(7)`), so refs are its only eN namespace.
103
+ * (The cmux backend parses selectors itself and routes bare `eN` to its own
104
+ * observe ids; either way `eN` means "the id from the last page dump".)
79
105
  */
80
106
  export function parseAriaRefSelector(selector: string): string | null {
107
+ assertSelectorString(selector);
81
108
  const trimmed = selector.trim();
82
109
  for (const prefix of ARIA_REF_PREFIXES) {
83
110
  if (trimmed.startsWith(prefix)) {
@@ -85,7 +112,8 @@ export function parseAriaRefSelector(selector: string): string | null {
85
112
  return /^e\d+$/.test(id) ? id : null;
86
113
  }
87
114
  }
88
- return null;
115
+ const bare = /^@?(e\d+)$/.exec(trimmed);
116
+ return bare ? bare[1]! : null;
89
117
  }
90
118
 
91
119
  /**
@@ -9,7 +9,7 @@ import type { ToolSession } from "../../index";
9
9
  import { resolveToCwd } from "../../path-utils";
10
10
  import { formatScreenshot } from "../../render-utils";
11
11
  import { ToolAbortError, ToolError, throwIfAborted } from "../../tool-errors";
12
- import { type AriaSnapshotOptions, buildAriaSnapshotScript } from "../aria/aria-snapshot";
12
+ import { type AriaSnapshotOptions, assertSelectorString, buildAriaSnapshotScript } from "../aria/aria-snapshot";
13
13
  import { DEFAULT_VIEWPORT } from "../launch";
14
14
  import { extractReadableFromHtml, type ReadableFormat } from "../readable";
15
15
  import {
@@ -1015,6 +1015,7 @@ export class CmuxTab {
1015
1015
  }
1016
1016
 
1017
1017
  #selectorSpec(selector: string): SelectorSpec {
1018
+ assertSelectorString(selector);
1018
1019
  const raw = selector;
1019
1020
  let normalized = selector;
1020
1021
  if (normalized.startsWith("p-text/")) normalized = `text/${normalized.slice("p-text/".length)}`;