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

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 (112) hide show
  1. package/CHANGELOG.md +86 -43
  2. package/dist/cli.js +3540 -3521
  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/extensibility/extensions/runner.d.ts +4 -2
  13. package/dist/types/extensibility/legacy-pi-coding-agent-shim.d.ts +16 -0
  14. package/dist/types/launch/spawn-options.d.ts +10 -0
  15. package/dist/types/launch/spawn-options.test.d.ts +1 -0
  16. package/dist/types/modes/components/status-line/component.d.ts +2 -3
  17. package/dist/types/modes/components/status-line/types.d.ts +3 -1
  18. package/dist/types/modes/components/tool-execution.d.ts +2 -0
  19. package/dist/types/modes/components/transcript-container.d.ts +4 -3
  20. package/dist/types/modes/components/tree-selector.d.ts +6 -2
  21. package/dist/types/modes/interactive-mode.d.ts +2 -0
  22. package/dist/types/modes/print-mode.d.ts +4 -0
  23. package/dist/types/modes/rpc/rpc-input.d.ts +5 -0
  24. package/dist/types/modes/rpc/rpc-mode.d.ts +1 -1
  25. package/dist/types/modes/types.d.ts +2 -0
  26. package/dist/types/sdk.d.ts +2 -0
  27. package/dist/types/session/agent-session.d.ts +19 -1
  28. package/dist/types/session/messages.d.ts +6 -0
  29. package/dist/types/tools/browser/aria/aria-snapshot.d.ts +17 -7
  30. package/dist/types/tools/browser/cmux/socket-client.d.ts +2 -0
  31. package/dist/types/tools/browser/tab-protocol.d.ts +2 -0
  32. package/dist/types/tools/browser/tab-worker.d.ts +2 -0
  33. package/dist/types/tools/gh.d.ts +5 -3
  34. package/dist/types/tools/hub/index.d.ts +1 -1
  35. package/dist/types/tools/hub/jobs.d.ts +1 -0
  36. package/dist/types/tools/hub/types.d.ts +2 -0
  37. package/dist/types/tools/tool-timeouts.d.ts +1 -1
  38. package/dist/types/utils/git.d.ts +33 -0
  39. package/dist/types/web/search/providers/codex.d.ts +1 -1
  40. package/package.json +12 -12
  41. package/src/advisor/__tests__/advisor.test.ts +150 -0
  42. package/src/advisor/advise-tool.ts +4 -0
  43. package/src/advisor/runtime.ts +38 -14
  44. package/src/async/job-manager.ts +3 -0
  45. package/src/cli/bench-cli.ts +8 -2
  46. package/src/cli/dry-balance-cli.ts +1 -0
  47. package/src/config/model-registry.ts +89 -8
  48. package/src/config/model-resolver.ts +78 -14
  49. package/src/config/models-config-schema.ts +1 -0
  50. package/src/config/settings.ts +3 -1
  51. package/src/dap/client.ts +168 -1
  52. package/src/dap/config.ts +51 -1
  53. package/src/dap/session.ts +575 -234
  54. package/src/dap/types.ts +6 -5
  55. package/src/discovery/agents.ts +2 -2
  56. package/src/extensibility/extensions/runner.ts +6 -4
  57. package/src/extensibility/legacy-pi-coding-agent-shim.ts +26 -0
  58. package/src/launch/broker.ts +34 -31
  59. package/src/launch/client.ts +7 -1
  60. package/src/launch/spawn-options.test.ts +31 -0
  61. package/src/launch/spawn-options.ts +17 -0
  62. package/src/lsp/types.ts +5 -1
  63. package/src/main.ts +17 -4
  64. package/src/mcp/transports/stdio.test.ts +9 -1
  65. package/src/modes/components/ask-dialog.ts +137 -73
  66. package/src/modes/components/status-line/component.ts +2 -2
  67. package/src/modes/components/status-line/segments.ts +20 -3
  68. package/src/modes/components/status-line/types.ts +3 -1
  69. package/src/modes/components/tool-execution.ts +5 -0
  70. package/src/modes/components/transcript-container.ts +23 -122
  71. package/src/modes/components/tree-selector.ts +10 -4
  72. package/src/modes/controllers/event-controller.ts +1 -2
  73. package/src/modes/controllers/input-controller.ts +1 -1
  74. package/src/modes/controllers/selector-controller.ts +29 -8
  75. package/src/modes/interactive-mode.ts +40 -8
  76. package/src/modes/noninteractive-dispose.test.ts +12 -1
  77. package/src/modes/print-mode.ts +21 -9
  78. package/src/modes/rpc/rpc-input.ts +38 -0
  79. package/src/modes/rpc/rpc-mode.ts +7 -2
  80. package/src/modes/setup-wizard/scenes/sign-in.ts +3 -1
  81. package/src/modes/types.ts +2 -0
  82. package/src/modes/utils/ui-helpers.ts +3 -2
  83. package/src/prompts/tools/browser.md +3 -2
  84. package/src/prompts/tools/debug.md +2 -7
  85. package/src/prompts/tools/github.md +6 -1
  86. package/src/prompts/tools/hub.md +4 -2
  87. package/src/prompts/tools/task-async-contract.md +1 -0
  88. package/src/prompts/tools/task.md +9 -2
  89. package/src/sdk.ts +38 -6
  90. package/src/session/agent-session.ts +395 -162
  91. package/src/session/messages.test.ts +91 -0
  92. package/src/session/messages.ts +248 -110
  93. package/src/slash-commands/builtin-registry.ts +1 -0
  94. package/src/task/executor.ts +59 -33
  95. package/src/task/index.ts +46 -9
  96. package/src/task/worktree.ts +10 -0
  97. package/src/tools/browser/aria/aria-snapshot.ts +36 -8
  98. package/src/tools/browser/cmux/cmux-tab.ts +2 -1
  99. package/src/tools/browser/cmux/socket-client.ts +139 -3
  100. package/src/tools/browser/run-cancellation.ts +4 -0
  101. package/src/tools/browser/tab-protocol.ts +2 -0
  102. package/src/tools/browser/tab-supervisor.ts +21 -11
  103. package/src/tools/browser/tab-worker.ts +199 -33
  104. package/src/tools/debug.ts +3 -0
  105. package/src/tools/gh.ts +40 -2
  106. package/src/tools/hub/index.ts +4 -1
  107. package/src/tools/hub/jobs.ts +42 -1
  108. package/src/tools/hub/types.ts +2 -0
  109. package/src/tools/tool-timeouts.ts +1 -1
  110. package/src/utils/git.ts +237 -0
  111. package/src/web/search/index.ts +9 -5
  112. package/src/web/search/providers/codex.ts +195 -99
@@ -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];
@@ -914,7 +937,7 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
914
937
  const finalOutputChunks: string[] = [];
915
938
  const RECENT_OUTPUT_TAIL_BYTES = 8 * 1024;
916
939
  let recentOutputTail = "";
917
- let tailLastLineRepresentable = false;
940
+ let recentOutputDirty = false;
918
941
  let resolved = false;
919
942
  let abortSent = false;
920
943
  let abortReason: AbortReason | undefined;
@@ -1054,7 +1077,22 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1054
1077
  let lastProgressEmitMs = 0;
1055
1078
  let progressTimeoutId: NodeJS.Timeout | null = null;
1056
1079
 
1080
+ // Recompute progress.recentOutput from the capped tail. Deferred: text_delta
1081
+ // appends only extend the tail and mark it dirty; the (up to 8KB) split/filter
1082
+ // runs synchronously here, immediately before the ONLY places the progress
1083
+ // object is snapshotted ({...progress} for onProgress and the eventBus
1084
+ // progress channel, both inside emitProgressNow — including the
1085
+ // scheduleProgress(flush) finalize/error/cancel paths). Observers therefore
1086
+ // always see exact state; no staleness beyond the existing 150ms coalescing.
1087
+ const refreshRecentOutput = () => {
1088
+ if (!recentOutputDirty) return;
1089
+ recentOutputDirty = false;
1090
+ const filtered = recentOutputTail.split("\n").filter(line => line.trim());
1091
+ progress.recentOutput = filtered.slice(-8).reverse();
1092
+ };
1093
+
1057
1094
  const emitProgressNow = () => {
1095
+ refreshRecentOutput();
1058
1096
  progress.durationMs = Date.now() - startTime;
1059
1097
  onProgress?.({ ...progress });
1060
1098
  const activityGist =
@@ -1137,36 +1175,16 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1137
1175
  return message.usage;
1138
1176
  };
1139
1177
 
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
1178
  const appendRecentOutputTail = (text: string) => {
1152
1179
  if (!text) return;
1153
1180
  recentOutputTail += text;
1154
- const truncated = recentOutputTail.length > RECENT_OUTPUT_TAIL_BYTES;
1155
- if (truncated) {
1181
+ if (recentOutputTail.length > RECENT_OUTPUT_TAIL_BYTES) {
1156
1182
  recentOutputTail = recentOutputTail.slice(-RECENT_OUTPUT_TAIL_BYTES);
1157
1183
  }
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
- }
1184
+ // O(chunk) hot path: this runs on every text_delta token (hundreds/
1185
+ // thousands per second while streaming). Line reconstruction is deferred
1186
+ // to refreshRecentOutput() at the emit boundary.
1187
+ recentOutputDirty = true;
1170
1188
  };
1171
1189
 
1172
1190
  const replaceRecentOutputFromContent = (content: unknown[]) => {
@@ -1181,12 +1199,12 @@ function createSubagentRunMonitor(args: RunMonitorArgs): SubagentRunMonitor {
1181
1199
  recentOutputTail = recentOutputTail.slice(-RECENT_OUTPUT_TAIL_BYTES);
1182
1200
  }
1183
1201
  }
1184
- updateRecentOutputLines();
1202
+ recentOutputDirty = true;
1185
1203
  };
1186
1204
 
1187
1205
  const resetRecentOutput = () => {
1188
1206
  recentOutputTail = "";
1189
- tailLastLineRepresentable = false;
1207
+ recentOutputDirty = false;
1190
1208
  progress.recentOutput = [];
1191
1209
  };
1192
1210
 
@@ -2319,6 +2337,11 @@ export async function runSubprocess(options: ExecutorOptions): Promise<SingleRes
2319
2337
  }
2320
2338
  checkAbort();
2321
2339
 
2340
+ const configuredModelPatterns = resolveConfiguredModelPatterns(modelPatterns, settings);
2341
+ const defaultRetryFallbackChain =
2342
+ configuredModelPatterns.length === 1
2343
+ ? resolveSubagentDefaultRetryFallbackChain(subagentSettings)
2344
+ : undefined;
2322
2345
  const {
2323
2346
  model,
2324
2347
  thinkingLevel: resolvedThinkingLevel,
@@ -2352,6 +2375,7 @@ export async function runSubprocess(options: ExecutorOptions): Promise<SingleRes
2352
2375
  settings: subagentSettings,
2353
2376
  id,
2354
2377
  candidates: resolveSubagentRetryFallbackCandidates(modelPatterns, modelRegistry, settings),
2378
+ defaultFallbackChain: defaultRetryFallbackChain,
2355
2379
  model,
2356
2380
  authFallbackUsed,
2357
2381
  });
@@ -2479,6 +2503,8 @@ export async function runSubprocess(options: ExecutorOptions): Promise<SingleRes
2479
2503
  model || modelOverride === undefined ? undefined : options.parentActiveModelPattern,
2480
2504
  modelPatternFallbackRole:
2481
2505
  model || modelOverride === undefined ? undefined : `${SUBAGENT_RETRY_FALLBACK_ROLE_PREFIX}${id}`,
2506
+ modelPatternDefaultFallbackChain:
2507
+ model || modelOverride === undefined ? undefined : defaultRetryFallbackChain,
2482
2508
  thinkingLevel: effectiveThinkingLevel,
2483
2509
  toolNames,
2484
2510
  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)}`;
@@ -1,9 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import * as net from "node:net";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
3
5
  import { ToolError } from "../../tool-errors";
4
6
 
5
7
  const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;
6
8
  const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
9
+ const UTF8 = new TextEncoder();
7
10
 
8
11
  type RequestJob = {
9
12
  method: string;
@@ -25,6 +28,37 @@ type CmuxErrorPayload = {
25
28
  details?: unknown;
26
29
  };
27
30
 
31
+ type RelayEndpoint = {
32
+ host: string;
33
+ port: number;
34
+ };
35
+
36
+ type RelayCredentials = {
37
+ relayId: string;
38
+ relayToken: Uint8Array<ArrayBuffer>;
39
+ };
40
+
41
+ function parseRelayCredentials(relayIdValue: unknown, relayTokenValue: unknown): RelayCredentials | null {
42
+ if (typeof relayIdValue !== "string" || typeof relayTokenValue !== "string") {
43
+ return null;
44
+ }
45
+ const relayId = relayIdValue.trim();
46
+ const relayTokenHex = relayTokenValue.trim();
47
+ if (
48
+ relayId.length === 0 ||
49
+ relayTokenHex.length === 0 ||
50
+ relayTokenHex.length % 2 !== 0 ||
51
+ !/^[0-9a-f]+$/i.test(relayTokenHex)
52
+ ) {
53
+ return null;
54
+ }
55
+ const relayToken = new Uint8Array(new ArrayBuffer(relayTokenHex.length / 2));
56
+ for (let index = 0; index < relayToken.length; index++) {
57
+ relayToken[index] = Number.parseInt(relayTokenHex.slice(index * 2, index * 2 + 2), 16);
58
+ }
59
+ return { relayId, relayToken };
60
+ }
61
+
28
62
  export function formatCmuxError(error: CmuxErrorPayload | undefined): string {
29
63
  const code = typeof error?.code === "string" && error.code.length > 0 ? error.code : "error";
30
64
  const message = typeof error?.message === "string" && error.message.length > 0 ? error.message : "cmux error";
@@ -35,6 +69,8 @@ export function formatCmuxError(error: CmuxErrorPayload | undefined): string {
35
69
  export class CmuxSocketClient {
36
70
  readonly #socketPath: string;
37
71
  readonly #password: string | undefined;
72
+ readonly #relayId: string | undefined;
73
+ readonly #relayToken: string | undefined;
38
74
  #socket: net.Socket | null = null;
39
75
  #connectPromise: Promise<void> | null = null;
40
76
  #connected = false;
@@ -45,9 +81,11 @@ export class CmuxSocketClient {
45
81
  #activeJob: RequestJob | null = null;
46
82
  #pumping = false;
47
83
 
48
- constructor(opts: { socketPath: string; password?: string }) {
84
+ constructor(opts: { socketPath: string; password?: string; relayId?: string; relayToken?: string }) {
49
85
  this.#socketPath = opts.socketPath;
50
86
  this.#password = opts.password;
87
+ this.#relayId = opts.relayId ?? process.env.CMUX_RELAY_ID;
88
+ this.#relayToken = opts.relayToken ?? process.env.CMUX_RELAY_TOKEN;
51
89
  }
52
90
 
53
91
  async connect(): Promise<void> {
@@ -101,7 +139,11 @@ export class CmuxSocketClient {
101
139
  }
102
140
 
103
141
  async #openSocket(): Promise<void> {
104
- const socket = net.createConnection({ path: this.#socketPath });
142
+ const relayEndpoint = this.#parseRelayEndpoint();
143
+ const relayCredentials = relayEndpoint ? await this.#loadRelayCredentials(relayEndpoint) : null;
144
+ const socket = relayEndpoint
145
+ ? net.createConnection({ host: relayEndpoint.host, port: relayEndpoint.port })
146
+ : net.createConnection({ path: this.#socketPath });
105
147
  this.#socket = socket;
106
148
  this.#buffer = "";
107
149
  socket.setEncoding("utf8");
@@ -111,13 +153,16 @@ export class CmuxSocketClient {
111
153
 
112
154
  try {
113
155
  await this.#waitForConnect(socket);
114
- this.#connected = true;
156
+ if (relayEndpoint && relayCredentials) {
157
+ await this.#authenticateRelay(relayEndpoint, relayCredentials);
158
+ }
115
159
  if (this.#password) {
116
160
  const line = await this.#sendLine(`auth ${this.#password}`, DEFAULT_CONNECT_TIMEOUT_MS);
117
161
  if (line.startsWith("ERROR:") && !line.includes("Unknown command 'auth'")) {
118
162
  throw new ToolError(line);
119
163
  }
120
164
  }
165
+ this.#connected = true;
121
166
  } catch (err) {
122
167
  this.#connected = false;
123
168
  socket.destroy();
@@ -128,6 +173,97 @@ export class CmuxSocketClient {
128
173
  }
129
174
  }
130
175
 
176
+ #parseRelayEndpoint(): RelayEndpoint | null {
177
+ const value = this.#socketPath.trim();
178
+ if (value.length === 0 || value.startsWith("/")) {
179
+ return null;
180
+ }
181
+ const match = /^(127\.0\.0\.1|localhost):([0-9]+)$/.exec(value);
182
+ if (!match) {
183
+ return null;
184
+ }
185
+ const port = Number.parseInt(match[2] ?? "", 10);
186
+ if (!Number.isInteger(port) || port < 1 || port > 65_535) {
187
+ return null;
188
+ }
189
+ return { host: "127.0.0.1", port };
190
+ }
191
+
192
+ async #loadRelayCredentials(endpoint: RelayEndpoint): Promise<RelayCredentials> {
193
+ const environmentCredentials = parseRelayCredentials(this.#relayId, this.#relayToken);
194
+ if (environmentCredentials) {
195
+ return environmentCredentials;
196
+ }
197
+
198
+ const authPath = path.join(os.homedir(), ".cmux", "relay", `${endpoint.port}.auth`);
199
+ let payload: unknown;
200
+ try {
201
+ payload = await Bun.file(authPath).json();
202
+ } catch {
203
+ throw new ToolError(
204
+ `Missing cmux relay auth metadata for ${endpoint.host}:${endpoint.port}; set CMUX_RELAY_ID/CMUX_RELAY_TOKEN or restore ~/.cmux/relay/${endpoint.port}.auth`,
205
+ );
206
+ }
207
+ const relayId = payload && typeof payload === "object" && "relay_id" in payload ? payload.relay_id : undefined;
208
+ const relayToken =
209
+ payload && typeof payload === "object" && "relay_token" in payload ? payload.relay_token : undefined;
210
+ const fileCredentials = parseRelayCredentials(relayId, relayToken);
211
+ if (!fileCredentials) {
212
+ throw new ToolError(`Invalid cmux relay auth metadata in ~/.cmux/relay/${endpoint.port}.auth`);
213
+ }
214
+ return fileCredentials;
215
+ }
216
+
217
+ async #authenticateRelay(endpoint: RelayEndpoint, credentials: RelayCredentials): Promise<void> {
218
+ const challengeLine = await this.#nextLine(DEFAULT_CONNECT_TIMEOUT_MS);
219
+ let challenge: unknown;
220
+ try {
221
+ challenge = JSON.parse(challengeLine);
222
+ } catch {
223
+ throw new ToolError(`Invalid cmux relay authentication challenge from ${endpoint.host}:${endpoint.port}`);
224
+ }
225
+ if (
226
+ !challenge ||
227
+ typeof challenge !== "object" ||
228
+ !("protocol" in challenge) ||
229
+ challenge.protocol !== "cmux-relay-auth" ||
230
+ !("version" in challenge) ||
231
+ typeof challenge.version !== "number" ||
232
+ !Number.isInteger(challenge.version) ||
233
+ !("relay_id" in challenge) ||
234
+ challenge.relay_id !== credentials.relayId ||
235
+ !("nonce" in challenge) ||
236
+ typeof challenge.nonce !== "string" ||
237
+ challenge.nonce.length === 0
238
+ ) {
239
+ throw new ToolError(`Invalid cmux relay authentication challenge from ${endpoint.host}:${endpoint.port}`);
240
+ }
241
+
242
+ const message = `relay_id=${challenge.relay_id}\nnonce=${challenge.nonce}\nversion=${challenge.version}`;
243
+ const key = await globalThis.crypto.subtle.importKey(
244
+ "raw",
245
+ credentials.relayToken,
246
+ { name: "HMAC", hash: "SHA-256" },
247
+ false,
248
+ ["sign"],
249
+ );
250
+ const mac = await globalThis.crypto.subtle.sign("HMAC", key, UTF8.encode(message));
251
+ const authLine = JSON.stringify({
252
+ relay_id: credentials.relayId,
253
+ mac: Buffer.from(mac).toString("hex"),
254
+ });
255
+ const responseLine = await this.#sendLine(authLine, DEFAULT_CONNECT_TIMEOUT_MS);
256
+ let response: unknown;
257
+ try {
258
+ response = JSON.parse(responseLine);
259
+ } catch {
260
+ throw new ToolError(`Cmux relay authentication failed for ${endpoint.host}:${endpoint.port}`);
261
+ }
262
+ if (!response || typeof response !== "object" || !("ok" in response) || response.ok !== true) {
263
+ throw new ToolError(`Cmux relay authentication failed for ${endpoint.host}:${endpoint.port}`);
264
+ }
265
+ }
266
+
131
267
  #waitForConnect(socket: net.Socket): Promise<void> {
132
268
  const { promise, resolve, reject } = Promise.withResolvers<void>();
133
269
  const timer = setTimeout(() => {
@@ -117,6 +117,10 @@ export function bindBrowserRunFacade<T extends object>(target: T, signal: AbortS
117
117
  return wrapped;
118
118
  }
119
119
  if (value && typeof value === "object") {
120
+ // Never proxy AbortSignals: native combinators (AbortSignal.any, fetch)
121
+ // brand-check internal slots that a Proxy cannot forward, and reading a
122
+ // signal needs no abort gating anyway.
123
+ if (value instanceof AbortSignal) return value;
120
124
  const wrapped = bindBrowserRunFacade(value, signal);
121
125
  cache.set(prop, wrapped);
122
126
  return wrapped;
@@ -95,6 +95,8 @@ export interface RunErrorPayload {
95
95
  stack?: string;
96
96
  isToolError: boolean;
97
97
  isAbort: boolean;
98
+ /** The worker could not restore tab-scoped browser state and must be recycled. */
99
+ recoverTab?: boolean;
98
100
  }
99
101
 
100
102
  export type WorkerOutbound =