@zergai/ztc 0.21.0-beta.1 → 0.22.0-beta.1

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 (113) hide show
  1. package/README.md +144 -33
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/App.js +2 -2
  8. package/dist/agent/agent.d.ts +13 -3
  9. package/dist/agent/agent.js +179 -91
  10. package/dist/agent/backends/codex_app_server.d.ts +1 -0
  11. package/dist/agent/backends/codex_app_server.js +3 -1
  12. package/dist/agent/backends/host_effort_policy.d.ts +12 -0
  13. package/dist/agent/backends/host_effort_policy.js +132 -0
  14. package/dist/agent/backends/index.d.ts +3 -2
  15. package/dist/agent/backends/index.js +4 -0
  16. package/dist/agent/backends/router_gate.d.ts +11 -0
  17. package/dist/agent/backends/router_gate.js +27 -2
  18. package/dist/agent/backends/router_keys.d.ts +63 -0
  19. package/dist/agent/backends/router_keys.js +94 -0
  20. package/dist/agent/backends/router_refusal.d.ts +12 -15
  21. package/dist/agent/backends/router_refusal.js +29 -5
  22. package/dist/agent/backends/types.d.ts +10 -0
  23. package/dist/agent/backends/zrouter_stream.d.ts +48 -1
  24. package/dist/agent/backends/zrouter_stream.js +215 -24
  25. package/dist/agent/commands/agent_cli.js +11 -3
  26. package/dist/agent/commands/config.js +12 -0
  27. package/dist/agent/commands/index.js +2 -1
  28. package/dist/agent/commands/mirror.js +15 -5
  29. package/dist/agent/commands/provider.js +4 -2
  30. package/dist/agent/commands/provider_selection.js +16 -2
  31. package/dist/agent/commands/router_availability.d.ts +15 -0
  32. package/dist/agent/commands/router_availability.js +45 -0
  33. package/dist/agent/commands/settings.js +38 -5
  34. package/dist/agent/commands/subs.d.ts +4 -1
  35. package/dist/agent/commands/subs.js +15 -5
  36. package/dist/agent/commands/types.d.ts +10 -0
  37. package/dist/agent/commands/ztc_pane.d.ts +20 -0
  38. package/dist/agent/commands/ztc_pane.js +239 -0
  39. package/dist/agent/factory.js +10 -2
  40. package/dist/agent/host_model_context.d.ts +9 -0
  41. package/dist/agent/host_model_context.js +40 -0
  42. package/dist/agent/request_encoder.d.ts +3 -0
  43. package/dist/agent/request_encoder.js +11 -4
  44. package/dist/agent/runtime/tool_runtime.js +8 -2
  45. package/dist/agent/subagent.d.ts +9 -0
  46. package/dist/agent/subagent.js +65 -46
  47. package/dist/agent/tools/file.js +10 -6
  48. package/dist/agent/tools/pane.d.ts +7 -0
  49. package/dist/agent/tools/pane.js +31 -6
  50. package/dist/agent/tools/ztc_command.d.ts +12 -0
  51. package/dist/agent/tools/ztc_command.js +21 -6
  52. package/dist/app/agent_runner.js +5 -2
  53. package/dist/app/command_context.js +10 -4
  54. package/dist/app/mirror_startup.d.ts +16 -0
  55. package/dist/app/mirror_startup.js +10 -0
  56. package/dist/app/runtime_choices.d.ts +2 -0
  57. package/dist/app/runtime_choices.js +1 -1
  58. package/dist/app/runtime_choices_source.js +2 -1
  59. package/dist/app/tool_callbacks.js +1 -0
  60. package/dist/cli_args.d.ts +2 -0
  61. package/dist/cli_args.js +5 -0
  62. package/dist/cli_ratatui.d.ts +14 -0
  63. package/dist/cli_ratatui.js +113 -27
  64. package/dist/config/permissions.d.ts +13 -0
  65. package/dist/config/permissions.js +63 -1
  66. package/dist/config/retired_routes.d.ts +23 -3
  67. package/dist/config/retired_routes.js +62 -11
  68. package/dist/config/types.d.ts +18 -1
  69. package/dist/config.d.ts +42 -0
  70. package/dist/config.js +102 -3
  71. package/dist/desktop/daily/desktop_wiring.js +9 -0
  72. package/dist/desktop/daily/recipes.js +7 -1
  73. package/dist/headless.js +2 -2
  74. package/dist/library.js +2 -2
  75. package/dist/mcp/client.js +6 -3
  76. package/dist/mcp/workspace_server.d.ts +6 -1
  77. package/dist/mcp/workspace_server.js +58 -9
  78. package/dist/onboarding/first_run.d.ts +3 -1
  79. package/dist/onboarding/first_run.js +21 -6
  80. package/dist/onboarding/router_tips.js +10 -7
  81. package/dist/panes/agent_cli.d.ts +48 -0
  82. package/dist/panes/agent_cli.js +145 -0
  83. package/dist/panes/agent_panes.d.ts +11 -0
  84. package/dist/panes/agent_panes.js +25 -4
  85. package/dist/panes/initial_input.d.ts +6 -0
  86. package/dist/panes/initial_input.js +6 -0
  87. package/dist/panes/motsi.d.ts +22 -7
  88. package/dist/panes/motsi.js +36 -9
  89. package/dist/panes/worker_route.d.ts +123 -0
  90. package/dist/panes/worker_route.js +464 -0
  91. package/dist/panes/ztc_launch.d.ts +9 -0
  92. package/dist/panes/ztc_launch.js +58 -2
  93. package/dist/router_auth.d.ts +18 -0
  94. package/dist/router_auth.js +78 -2
  95. package/dist/types.d.ts +5 -0
  96. package/dist/ui/ratatui/headless_pane_manager.d.ts +2 -0
  97. package/dist/ui/ratatui/headless_pane_manager.js +6 -3
  98. package/dist/ui/ratatui/pane_relay.d.ts +11 -1
  99. package/dist/ui/ratatui/pane_relay.js +14 -2
  100. package/dist/ui/ratatui/protocol.d.ts +9 -1
  101. package/dist/utils/atomic_write.js +26 -1
  102. package/dist/utils/docker_target.js +4 -1
  103. package/dist/utils/subprocess_env.d.ts +18 -0
  104. package/dist/utils/subprocess_env.js +45 -0
  105. package/dist/web/mirror_authenticator.d.ts +6 -0
  106. package/dist/web/mirror_authenticator.js +15 -12
  107. package/dist/web/mirror_stream.d.ts +50 -0
  108. package/dist/web/mirror_stream.js +121 -30
  109. package/dist/worker/worker_models.d.ts +11 -0
  110. package/dist/worker/worker_models.js +19 -7
  111. package/dist/zlm-embed.mjs +1349 -429
  112. package/dist/zlm.js +1 -1
  113. package/package.json +32 -16
@@ -28,7 +28,8 @@ import { toolSearchTool } from './tools/tool_search.js';
28
28
  import { recallToolResponseTool } from './tools/recall_tool_response.js';
29
29
  import { adaptationRunTool } from './tools/adaptation.js';
30
30
  import { ToolGroupRuntime } from './tools/tool_groups.js';
31
- import { isCodexAppServerProvider } from './backends/provider_ids.js';
31
+ import { isCodexAppServerProvider, isLocalSubscriptionProvider, normalizeProviderId } from './backends/provider_ids.js';
32
+ import { PROVIDER_CHOICES } from './commands/provider_choices.js';
32
33
  import { getRequestToolDefinitions } from './tools/deferred.js';
33
34
  import { isToolResultMessage } from '../utils/tool_result_message.js';
34
35
  import { getLatestTodos } from './tools/todo.js';
@@ -49,6 +50,7 @@ import { createToolProgressAccumulator } from './runtime/tool_progress.js';
49
50
  import { ToolCapability } from './runtime/capabilities.js';
50
51
  import { buildUserSubprocessEnv } from '../utils/subprocess_env.js';
51
52
  import { projectHandoffHistory, resolvePromptPrefixId } from '../utils/compaction.js';
53
+ import { hostModelContextBudget, hostModelContextError } from './host_model_context.js';
52
54
  import { estimateConversationTokens, getContextWindowSize } from '../utils/context.js';
53
55
  import { shouldCompactMidTurn } from '../utils/mid_turn_compaction.js';
54
56
  import { clampCompletionTokens } from '../utils/deepseek.js';
@@ -213,9 +215,6 @@ export class Agent {
213
215
  midTurnCompactTokenBudget;
214
216
  /** Codex/GPT reasoning effort override; undefined = provider default. */
215
217
  _codexEffort;
216
- /** One-shot: the next request carries the output-limit note at this effort. */
217
- /** The next request retries a discarded response: a note for the model, and lower effort when offered. */
218
- responseRetry = null;
219
218
  /** The person's attempt (admitPersonRequest), waiting for the run that takes it: the next to start, or the one whose
220
219
  * steering admitted it. */
221
220
  personRequestPending = false;
@@ -224,6 +223,15 @@ export class Agent {
224
223
  eventHandlers = new Set();
225
224
  toolEventSequence = 0;
226
225
  backend;
226
+ /** The run that started last and is still running: what the handoff summary, steering and the execution facts asked
227
+ * for outside a run's own loop go by. Its loop passes its own RunTurn everywhere. */
228
+ activeRun;
229
+ /** The backend, model and output limit RUN's request goes with: its host policy's snapshot, else the agent's own. */
230
+ turnBackend(run) { return run?.prepared?.backend ?? this.backend; }
231
+ turnModel(run) { return run?.prepared?.options.model ?? this.config.model; }
232
+ turnMaxTokens(run) {
233
+ return run?.prepared ? run.prepared.options.maxTokens : this.config.maxTokens;
234
+ }
227
235
  policy;
228
236
  tracer;
229
237
  diagnostics = createDiagnosticSnapshot();
@@ -238,6 +246,7 @@ export class Agent {
238
246
  _lastResponseStreamed = false;
239
247
  _cwd;
240
248
  _autoContinue;
249
+ modelSupportsTools;
241
250
  /** Auto-continues spent since the last tool run; reset per turn and per tool. */
242
251
  _consecutiveAutoContinues = 0;
243
252
  _turnAutoContinues = 0;
@@ -390,6 +399,8 @@ export class Agent {
390
399
  approvalContext;
391
400
  _hasCustomSystemPrompt;
392
401
  _authenticationManagedByBackend;
402
+ /** The provider the caller named, whose own key this Agent sends; none for a credential a host brokers. */
403
+ keyProvider;
393
404
  constructor(config = {}) {
394
405
  this.toolResponseStore = config.toolResponseStore ?? new ToolResponseStore();
395
406
  const ambientDiscovery = config.ambientDiscovery ?? true;
@@ -462,10 +473,7 @@ export class Agent {
462
473
  this.alwaysLoadedToolNames.add(name);
463
474
  }
464
475
  this.backend = this.config.backend;
465
- if (this.backend.getModelCapabilities?.(this.config.model)?.tools === false) {
466
- this.config.tools = [];
467
- this.config.autoContinue = false;
468
- }
476
+ this.modelSupportsTools = this.backend.getModelCapabilities?.(this.config.model)?.tools !== false;
469
477
  this.policy = this.config.policy;
470
478
  const suppliedTracer = this.config.tracer;
471
479
  this.tracer = { event: event => {
@@ -493,6 +501,7 @@ export class Agent {
493
501
  this.approvalContext = config.approvalContext;
494
502
  this._authenticationManagedByBackend =
495
503
  backend.isAuthenticationConfigured?.() === true;
504
+ this.keyProvider = config.disableApiKeyFallback ? undefined : config.provider;
496
505
  this._codexEffort = config.codexEffort;
497
506
  this._codexFastMode = config.codexFastMode ?? false;
498
507
  this._hasCustomSystemPrompt = typeof config.systemPrompt === 'string' && config.systemPrompt.trim().length > 0;
@@ -526,7 +535,7 @@ export class Agent {
526
535
  };
527
536
  }
528
537
  setAutoContinue(enabled) {
529
- this._autoContinue = enabled && this.backend.getModelCapabilities?.(this.config.model)?.tools !== false;
538
+ this._autoContinue = enabled;
530
539
  }
531
540
  /** Override the agent's system prompt (e.g., for simulation persona injection). */
532
541
  setSystemPrompt(prompt) {
@@ -545,7 +554,7 @@ export class Agent {
545
554
  this.config.systemPrompt = this.getDefaultSystemPrompt(this.config.tools);
546
555
  }
547
556
  getAutoContinue() {
548
- return this._autoContinue;
557
+ return this._autoContinue && this.modelSupportsTools;
549
558
  }
550
559
  /** Give each tool invocation its own copy so one tool cannot mutate the
551
560
  * hosted subprocess boundary for later calls in the same Agent. */
@@ -558,7 +567,7 @@ export class Agent {
558
567
  * Check if the response content indicates incomplete work that should trigger auto-continue
559
568
  */
560
569
  shouldContinue(content) {
561
- if (!this._autoContinue)
570
+ if (!this.getAutoContinue())
562
571
  return false;
563
572
  // Patterns that indicate the agent intends to continue but stopped
564
573
  const continuePatterns = [
@@ -580,7 +589,7 @@ export class Agent {
580
589
  * list of steps the model says it has not done yet.
581
590
  */
582
591
  needsAutonomousContinuation(content) {
583
- if (!this._autoContinue || !this.config.noHumanAvailable)
592
+ if (!this.getAutoContinue() || !this.config.noHumanAvailable)
584
593
  return false;
585
594
  const asksUser = [
586
595
  /\b(do|would) you (want|like|prefer)\b/i,
@@ -617,17 +626,21 @@ export class Agent {
617
626
  }
618
627
  /** Snapshot the effective tool surface after mode/provider filtering. */
619
628
  getConfiguredToolNames() {
629
+ if (!this.modelSupportsTools)
630
+ return [];
620
631
  return this.config.tools.map((tool) => tool.definition.name);
621
632
  }
622
633
  getHandoffContext(messages = []) {
623
- return { ...this.buildRequest([...messages]), backend: this.backend,
634
+ // A summary asked for mid-run (compaction) goes with that run's snapshot.
635
+ const run = this.activeRun;
636
+ return { ...this.buildRequest([...messages], this.config.tools, run), backend: this.turnBackend(run),
624
637
  onMetrics: metrics => {
625
638
  this.emit({ type: 'request_metrics', metrics });
626
639
  if (!metrics.usage)
627
640
  return;
628
641
  this.retainUsageReceipt({ id: `usage_${randomUUID()}`, sessionId: this.config.sessionId,
629
642
  projectHash: createHash('sha256').update(this._cwd).digest('hex').slice(0, 12),
630
- provider: this.config.runtimeFacts.provider ?? null, model: this.config.model, accountId: null,
643
+ provider: this.config.runtimeFacts.provider ?? null, model: this.turnModel(run), accountId: null,
631
644
  observedAt: new Date().toISOString(), source: metrics.usage.estimated ? 'estimated' : 'reported',
632
645
  usage: metrics.usage, costUsd: null });
633
646
  },
@@ -724,7 +737,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
724
737
  // tracks durable context and only moves backward on a real reset/compaction.
725
738
  _currentTransientOverageTokens = 0;
726
739
  _nativeContextId;
727
- formatMessages(messages) {
740
+ formatMessages(messages, run = this.activeRun) {
728
741
  // Pre-pass: collect every tool_use_id appearing in tool_result messages,
729
742
  // and retain every batch since the latest authored prompt. Running the
730
743
  // selector once for the whole request gives aggregate budget control;
@@ -757,8 +770,9 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
757
770
  }
758
771
  this._currentRequestToolIds = currentTurnToolIds;
759
772
  if (allToolIds.length > 0) {
760
- const activeModel = this.config.model || 'default';
761
- const budget = this.toolResponseStore.effectiveBudget(activeModel, this.backend.getModelCapabilities?.(activeModel) ? this.backend.getModelCapabilities(activeModel)?.context_window ?? null : undefined);
773
+ const activeModel = this.turnModel(run) || 'default';
774
+ const backend = this.turnBackend(run);
775
+ const budget = this.toolResponseStore.effectiveBudget(activeModel, backend.getModelCapabilities?.(activeModel) ? backend.getModelCapabilities(activeModel)?.context_window ?? null : undefined);
762
776
  this._selectorVerdict = this.toolResponseStore.selectInlineSet(allToolIds, currentTurnToolIds, budget);
763
777
  }
764
778
  else {
@@ -777,17 +791,19 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
777
791
  ? { ...message, metadata: { ...message.metadata, reasoningContent: providerReasoning } }
778
792
  : message;
779
793
  });
780
- const { messages: encoded, transientOverageTokens } = new RequestEncoder(this._encodeDeps()).encode(wireMessages);
794
+ const { messages: encoded, transientOverageTokens } = new RequestEncoder(this._encodeDeps(run)).encode(wireMessages);
781
795
  this._currentTransientOverageTokens = transientOverageTokens;
782
796
  return encoded;
783
797
  }
784
798
  // Assemble the encoder's dependencies from the agent's per-request selector
785
799
  // state and disk-backed media loaders. Used by formatMessages and the
786
800
  // buildContentBlocks pipeline entry point below.
787
- _encodeDeps() {
801
+ _encodeDeps(run = this.activeRun) {
788
802
  return {
789
- preserveNativeHistory: this.backend.preservesNativeHistory,
790
- model: this.config.model,
803
+ preserveNativeHistory: this.turnBackend(run).preservesNativeHistory,
804
+ model: this.turnModel(run),
805
+ legacyReasoningModel: run?.prepared ? this.config.model : undefined,
806
+ isModelCompatible: run?.prepared?.isModelCompatible,
791
807
  nativeContextId: this._nativeContextId,
792
808
  selectorVerdict: this._selectorVerdict,
793
809
  currentTurnToolIds: this._currentRequestToolIds,
@@ -1072,7 +1088,11 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1072
1088
  }
1073
1089
  return repaired;
1074
1090
  }
1075
- buildRequest(messages, availableTools = this.config.tools) {
1091
+ buildRequest(messages, availableTools = this.config.tools, run = this.activeRun) {
1092
+ // A host policy may replace the starting model. Keep configured tools and
1093
+ // caller intent intact; filter the effective surface for the selected turn.
1094
+ if (!this.modelSupportsTools)
1095
+ availableTools = [];
1076
1096
  messages = projectHandoffHistory(messages);
1077
1097
  this.captureUserInstructions(messages);
1078
1098
  // A call with a recorded outcome is sent with its result (inline or as a
@@ -1092,7 +1112,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1092
1112
  }
1093
1113
  // Repair any orphaned tool_use blocks before building request
1094
1114
  if (this.config.pinTaskHeader) {
1095
- const facts = describeExecutionContext({ ...this.getExecutionContext(), tools: availableTools.map(tool => tool.definition.name) });
1115
+ const facts = describeExecutionContext({ ...this.executionContext(run), tools: availableTools.map(tool => tool.definition.name) });
1096
1116
  const latestFacts = [...messages].reverse().find(message => typeof message.metadata?.executionContext === 'string')?.metadata?.executionContext;
1097
1117
  if (facts !== latestFacts) {
1098
1118
  const latestUser = [...messages].reverse().find(message => message.role === 'user');
@@ -1176,8 +1196,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1176
1196
  timestamp: new Date(this.runtimeEnvironmentTurn.capturedAt),
1177
1197
  metadata: { synthetic: true, hostContext: true, preserveUserBoundary: true } });
1178
1198
  }
1179
- const responseRetry = this.responseRetry;
1180
- this.responseRetry = null;
1199
+ const responseRetry = run?.retry ?? null;
1181
1200
  if (responseRetry) {
1182
1201
  contextMessages.push({ id: `retry_note_${randomUUID()}`, role: 'user', content: responseRetry.note,
1183
1202
  timestamp: new Date(), metadata: { synthetic: true, hostContext: true } });
@@ -1196,19 +1215,19 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1196
1215
  const system = this.systemWithTaskHeader(messages);
1197
1216
  const baseDefinitions = getRequestToolDefinitions(availableTools, this.discoveredTools, this.config.deferToolSchemas !== false, this.alwaysLoadedToolNames);
1198
1217
  const tools = this.toolGroups?.requestDefinitions(baseDefinitions, availableTools) ?? baseDefinitions;
1199
- this._nativeContextId = this.backend.preservesNativeHistory ? nativeHistoryContextId(system, tools) : undefined;
1218
+ this._nativeContextId = this.turnBackend(run).preservesNativeHistory ? nativeHistoryContextId(system, tools) : undefined;
1200
1219
  return {
1201
- model: this.config.model,
1202
- maxTokens: this.config.maxTokens,
1220
+ model: this.turnModel(run),
1221
+ maxTokens: this.turnMaxTokens(run),
1203
1222
  system,
1204
- messages: this.formatMessages(contextMessages),
1223
+ messages: this.formatMessages(contextMessages, run),
1205
1224
  tools,
1206
1225
  // A container pin identifies a cached prompt prefix, so the transport has to
1207
1226
  // know when this conversation is no longer sending the prefix its container
1208
1227
  // was warmed for. That is compaction, and only this layer can see it.
1209
1228
  promptPrefixId: resolvePromptPrefixId(repairedMessages),
1210
- routePlan: this.config.routePlan,
1211
- codexEffort: responseRetry?.effort ?? this._codexEffort,
1229
+ routePlan: run?.prepared ? run.prepared.options.routePlan : this.config.routePlan,
1230
+ codexEffort: run?.prepared ? run.prepared.options.codexEffort : responseRetry?.effort ?? this._codexEffort,
1212
1231
  codexFastMode: this._codexFastMode,
1213
1232
  };
1214
1233
  }
@@ -1261,7 +1280,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1261
1280
  * visible text, so an empty or whitespace-only response emits no stream
1262
1281
  * events (EPO-622), matching emitStreamText.
1263
1282
  */
1264
- async streamAndAssemble(request, signal, onAnswerOutput, onUsage) {
1283
+ async streamAndAssemble(backend, request, signal, onAnswerOutput, onUsage) {
1265
1284
  let text = '';
1266
1285
  let reasoning = '';
1267
1286
  const toolUses = [];
@@ -1283,7 +1302,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1283
1302
  let streamStarted = false;
1284
1303
  let sawCompletion = false;
1285
1304
  try {
1286
- for await (const ev of guardRunawayOutput(this.backend.generateStream(request))) {
1305
+ for await (const ev of guardRunawayOutput(backend.generateStream(request))) {
1287
1306
  streamStarted = true;
1288
1307
  if (signal?.aborted)
1289
1308
  throw new AgentError('Cancelled', 'CANCELLED');
@@ -1489,7 +1508,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1489
1508
  async steerUserMessage(message) {
1490
1509
  if (this.#conversationBinding)
1491
1510
  return false;
1492
- return this.backend.steerUserMessage?.(message) ?? false;
1511
+ return this.turnBackend(this.activeRun).steerUserMessage?.(message) ?? false;
1493
1512
  }
1494
1513
  /** Tools that end the agent turn when called (require user interaction before continuing). */
1495
1514
  static TURN_ENDING_TOOLS = new Set([
@@ -1581,6 +1600,11 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1581
1600
  }
1582
1601
  /** Append the pinned task header (R7) to the static system prompt. */
1583
1602
  getExecutionContext() {
1603
+ return this.executionContext(this.activeRun);
1604
+ }
1605
+ /** The execution facts RUN's requests go with: its host policy's output limit, when one chose the model. */
1606
+ executionContext(run) {
1607
+ const maxTokens = this.turnMaxTokens(run);
1584
1608
  return {
1585
1609
  permissions: this.config.runtimeFacts.permissions,
1586
1610
  ...(this.remoteResourceSession ? { remoteResourceGuard: {
@@ -1589,8 +1613,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1589
1613
  mode: this.config.runtimeFacts.mode ?? 'normal', cwd: this._cwd,
1590
1614
  tools: this.getConfiguredToolNames(), mux: this.config.runtimeFacts.mux ?? false,
1591
1615
  configScope: this.config.runtimeFacts.configScope ?? 'host configuration',
1592
- maxTokens: this.config.maxTokens,
1593
- outputLimitSource: this.config.runtimeFacts.outputLimitSource ?? (this.config.maxTokens === undefined ? 'provider default' : 'explicit configuration'),
1616
+ maxTokens,
1617
+ outputLimitSource: this.config.runtimeFacts.outputLimitSource ?? (maxTokens === undefined ? 'provider default' : 'explicit configuration'),
1594
1618
  settings: resolveExecutionSettings(this.config.execution), jobs: listCommandJobs(this.config.sessionId),
1595
1619
  };
1596
1620
  }
@@ -1682,6 +1706,9 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1682
1706
  // (a cancel lets the next turn begin at once) keeps its own.
1683
1707
  const attempt = { pending: this.personRequestPending };
1684
1708
  this.personRequestPending = false;
1709
+ // What this run prepares for its requests is its own too: a run unwinding after this one starts never clears it.
1710
+ const run = { retry: null };
1711
+ this.activeRun = run;
1685
1712
  // Only an admission the take itself makes (the person's steering it hands over) is this run's. One already
1686
1713
  // pending belongs to the person's next message: a cancelled run still takes steering as it unwinds.
1687
1714
  const take = takeSteering && (() => {
@@ -1702,7 +1729,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1702
1729
  await this.nativeEvidencePending;
1703
1730
  if (this.nativeEvidenceFailure)
1704
1731
  throw this.nativeEvidenceFailure;
1705
- result = await this.runBound(messages, signal, take, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt);
1732
+ result = await this.runBound(messages, signal, take, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt, run);
1706
1733
  return result;
1707
1734
  }
1708
1735
  catch (error) {
@@ -1710,6 +1737,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1710
1737
  throw error;
1711
1738
  }
1712
1739
  finally {
1740
+ if (this.activeRun === run)
1741
+ this.activeRun = undefined;
1713
1742
  signal?.removeEventListener('abort', onInterrupt);
1714
1743
  try {
1715
1744
  await this.nativeEvidencePending;
@@ -1734,10 +1763,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1734
1763
  }
1735
1764
  }
1736
1765
  }
1737
- async runBound(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }) {
1766
+ async runBound(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }, run = { retry: null }) {
1738
1767
  const binding = this.#conversationBinding;
1739
1768
  if (!binding)
1740
- return this.runCore(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt);
1769
+ return this.runCore(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt, run);
1741
1770
  const userMessage = [...messages].reverse().find((message) => message.role === 'user'
1742
1771
  && !message.metadata?.synthetic
1743
1772
  && !message.metadata?.toolResult);
@@ -1769,7 +1798,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1769
1798
  // The host driver publishes only the initial user and final assistant
1770
1799
  // for this turn. Leave busy input pending for a new hosted turn so the
1771
1800
  // authoritative conversation cannot silently omit it.
1772
- const result = await this.runCore(workingMessages, signal, undefined, toolCheckpoint, undefined, diagnosticTurn, onUsage, attempt);
1801
+ const result = await this.runCore(workingMessages, signal, undefined, toolCheckpoint, undefined, diagnosticTurn, onUsage, attempt, run);
1773
1802
  const assistantMessage = {
1774
1803
  id: `host_assistant_${randomUUID()}`,
1775
1804
  role: 'assistant',
@@ -1777,7 +1806,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1777
1806
  ...(result.nativeContent ? { nativeContent: result.nativeContent, nativeModel: result.nativeModel, nativeContextId: result.nativeContextId } : {}),
1778
1807
  timestamp: new Date(),
1779
1808
  ...(result.toolCalls.length > 0 ? { toolCalls: result.toolCalls } : {}),
1780
- metadata: { ...(result.responseItems ? { openaiResponseItems: result.responseItems, openaiResponseModel: this.config.model } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(result.reasoning ? { reasoningContent: result.reasoning } : {}) },
1809
+ metadata: { ...(result.responseItems ? { openaiResponseItems: result.responseItems, openaiResponseModel: this.turnModel(run) } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(result.reasoning ? { reasoningContent: result.reasoning, reasoningModel: result.reasoningModel } : {}) },
1781
1810
  };
1782
1811
  const receipt = await binding.driver.publish({
1783
1812
  turn,
@@ -1816,7 +1845,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1816
1845
  }
1817
1846
  }
1818
1847
  // Main execution loop shared by hosted and standalone turns.
1819
- async runCore(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }) {
1848
+ async runCore(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }, run = { retry: null }) {
1820
1849
  if (!this.hasApiKey()) {
1821
1850
  throw new AgentError('No API key configured. Use /config key <key> to set one.', 'NO_API_KEY');
1822
1851
  }
@@ -1847,8 +1876,11 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1847
1876
  // "as-is, including any reasoning_content"; without this the trace survives
1848
1877
  // only inside one run() and every later user turn sends a stripped history.
1849
1878
  let finalReasoning;
1879
+ let finalReasoningModel;
1850
1880
  let finalNativeContent;
1881
+ let finalNativeModel;
1851
1882
  let finalResponseItems;
1883
+ let finalResponseModel;
1852
1884
  let lastToolTurnText = '';
1853
1885
  let totalUsage = null;
1854
1886
  let runError = null;
@@ -1899,7 +1931,40 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1899
1931
  messages.push({ id: `lead_staffing_${randomUUID()}`, role: 'user', content: staffing.content, timestamp: new Date(),
1900
1932
  metadata: { synthetic: true, hostContext: true } });
1901
1933
  }
1902
- const request = this.buildRequest(messages, availableTools);
1934
+ run.prepared = undefined;
1935
+ run.prepared = await this.backend.prepareTurn?.({ model: this.config.model,
1936
+ maxTokens: this.config.maxTokens, routePlan: this.config.routePlan,
1937
+ codexEffort: run.retry?.effort ?? this._codexEffort, signal });
1938
+ if (run.prepared)
1939
+ this.modelSupportsTools = this.turnBackend(run).getModelCapabilities?.(this.turnModel(run))?.tools !== false;
1940
+ let request = this.buildRequest(messages, availableTools, run);
1941
+ let budget = run.prepared ? hostModelContextBudget(this.turnBackend(run), request) : undefined;
1942
+ if (budget?.exceeded && this.onMidTurnCompact) {
1943
+ try {
1944
+ const compacted = await this.onMidTurnCompact({ messages: [...messages], usedTokens: budget.usedTokens,
1945
+ windowTokens: budget.windowTokens, signal });
1946
+ if (signal?.aborted)
1947
+ throw new AgentError('Cancelled', 'CANCELLED');
1948
+ if (compacted?.length) {
1949
+ messages.splice(0, messages.length, ...compacted);
1950
+ turnMessages.splice(0, turnMessages.length, ...compacted);
1951
+ this.emit({ type: 'history_checkpoint', messages: [...turnMessages], replacesHistory: true });
1952
+ request = this.buildRequest(messages, availableTools, run);
1953
+ budget = hostModelContextBudget(this.turnBackend(run), request);
1954
+ }
1955
+ }
1956
+ catch (error) {
1957
+ if (signal?.aborted || error instanceof AgentError && error.code === 'CANCELLED')
1958
+ throw error;
1959
+ // The original request still overflows. Surface the same actionable
1960
+ // ContextOverflowError below, including when compaction is offline.
1961
+ }
1962
+ }
1963
+ if (budget?.exceeded) {
1964
+ const error = hostModelContextError(request, budget.windowTokens);
1965
+ throw new ContextOverflowError(error, request, error);
1966
+ }
1967
+ run.retry = null;
1903
1968
  request.signal = signal;
1904
1969
  if (attempt.pending) {
1905
1970
  attempt.pending = false;
@@ -1926,11 +1991,16 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1926
1991
  const identity = { id: `usage_${randomUUID()}`, sessionId: this.config.sessionId,
1927
1992
  projectHash: createHash('sha256').update(this._cwd).digest('hex').slice(0, 12),
1928
1993
  provider: this.config.runtimeFacts.provider ?? null, model: request.model, accountId: null };
1994
+ const selectedContextWindow = run.prepared
1995
+ ? this.turnBackend(run).getModelCapabilities?.(request.model)?.context_window : undefined;
1996
+ const hasPreparedTurn = run.prepared !== undefined;
1929
1997
  const retainReturnedAccounting = (response) => {
1930
1998
  const rawContent = response.content;
1931
1999
  const accountingResponse = { ...response, content: Array.isArray(rawContent) ? rawContent
1932
2000
  : typeof rawContent === 'string' && rawContent ? [{ type: 'text', text: rawContent }] : [] };
1933
- const usage = response.usage ?? this.estimateUsage(request, accountingResponse);
2001
+ const reported = response.usage ?? this.estimateUsage(request, accountingResponse);
2002
+ const usage = hasPreparedTurn && selectedContextWindow !== undefined
2003
+ ? { ...reported, contextWindow: selectedContextWindow } : reported;
1934
2004
  this.retainUsageReceipt({ ...identity, observedAt: new Date().toISOString(),
1935
2005
  source: usage.estimated === true ? 'estimated' : 'reported', usage,
1936
2006
  costUsd: typeof response.costUsd === 'number' && Number.isFinite(response.costUsd) && response.costUsd >= 0
@@ -1941,7 +2011,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1941
2011
  let response;
1942
2012
  let returnedResponse;
1943
2013
  try {
1944
- response = await this.callAPI(request, captureNativeObservation, signal, { messages, turnMessages, toolCalls: allToolCalls, handler: toolCheckpoint }, observed => { returnedResponse = observed; }, requestUsage);
2014
+ response = await this.callAPI(request, captureNativeObservation, signal, { messages, turnMessages, toolCalls: allToolCalls, handler: toolCheckpoint }, observed => { returnedResponse = observed; }, requestUsage, run);
1945
2015
  }
1946
2016
  catch (error) {
1947
2017
  // A success metrics observer may cancel synchronously just before the
@@ -1957,7 +2027,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1957
2027
  if (runawayRetried)
1958
2028
  throw new AgentError(repeatedRunawayMessage(error), RUNAWAY_OUTPUT_CODE);
1959
2029
  runawayRetried = true;
1960
- this.responseRetry = { note: RUNAWAY_OUTPUT_RETRY_NOTE, effort: outputLimitRetryEffort(this.backend.getModelCapabilities?.(request.model)?.reasoning?.choices, this._codexEffort) };
2030
+ run.retry = { note: RUNAWAY_OUTPUT_RETRY_NOTE, effort: outputLimitRetryEffort(this.turnBackend(run).getModelCapabilities?.(request.model)?.reasoning?.choices, this._codexEffort) };
1961
2031
  this.emit({ type: 'api_retry', attempt: 1, maxAttempts: 1, delay: 0, phase: 'retry', elapsedMs: 0,
1962
2032
  reason: 'The response kept repeating the same text and was stopped; retrying' });
1963
2033
  continue;
@@ -1981,7 +2051,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1981
2051
  ? [{ type: 'text', text: raw }]
1982
2052
  : [];
1983
2053
  }
1984
- if (!this.backend.preservesNativeHistory)
2054
+ if (!this.turnBackend(run).preservesNativeHistory)
1985
2055
  response.content = normalizeRepeatedResponseContent(response.content);
1986
2056
  this.tracer.event({ type: 'api_response', timestamp: new Date(), data: { turnId: diagnosticTurn?.id ?? null,
1987
2057
  model: request.model, stopReason: response.stopReason, stopReasonSource: 'backend_response', content: response.content, usage: response.usage } });
@@ -2017,7 +2087,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2017
2087
  if (!outputLimitRetried && isOutputLimitStop(response.stopReason, request.maxTokens, response.usage?.outputTokens)
2018
2088
  && !response.content.some(block => this.isTextBlock(block) && block.text.trim())) {
2019
2089
  outputLimitRetried = true;
2020
- this.responseRetry = { note: OUTPUT_LIMIT_RETRY_NOTE, effort: outputLimitRetryEffort(this.backend.getModelCapabilities?.(request.model)?.reasoning?.choices, this._codexEffort) };
2090
+ run.retry = { note: OUTPUT_LIMIT_RETRY_NOTE, effort: outputLimitRetryEffort(this.turnBackend(run).getModelCapabilities?.(request.model)?.reasoning?.choices, this._codexEffort) };
2021
2091
  this.emit({ type: 'api_retry', attempt: 1, maxAttempts: 1, delay: 0, phase: 'retry', elapsedMs: 0,
2022
2092
  reason: 'The response reached the output limit while reasoning; retrying in smaller steps' });
2023
2093
  continue;
@@ -2028,6 +2098,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2028
2098
  throw new AgentError('The model declined this request.', 'MODEL_REFUSAL');
2029
2099
  }
2030
2100
  finalResponseItems = response.responseItems;
2101
+ finalResponseModel = request.model;
2031
2102
  // Check for tool use
2032
2103
  const requestedToolBlocks = response.content.filter(this.isToolUseBlock);
2033
2104
  const requestedIds = new Set();
@@ -2062,7 +2133,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2062
2133
  occupiedIds.add(id);
2063
2134
  toolUseBlocks.push({ ...block, id });
2064
2135
  }
2065
- if (this.backend.preservesNativeHistory && toolUseBlocks.length > 0) {
2136
+ if (this.turnBackend(run).preservesNativeHistory && toolUseBlocks.length > 0) {
2066
2137
  // Native replay keeps opaque signed blocks unchanged. Its tool-use
2067
2138
  // IDs still need to pair with the canonical identities admitted above.
2068
2139
  const canonicalIds = new Map(requestedToolBlocks.map((block, index) => [block.id, toolUseBlocks[index].id]));
@@ -2070,8 +2141,14 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2070
2141
  ? { ...block, id: canonicalIds.get(block.id) } : block);
2071
2142
  }
2072
2143
  if (toolUseBlocks.length === 0) {
2073
- if (this.backend.preservesNativeHistory)
2144
+ if (this.turnBackend(run).preservesNativeHistory) {
2074
2145
  finalNativeContent = response.content;
2146
+ finalNativeModel = request.model;
2147
+ }
2148
+ else {
2149
+ finalNativeContent = undefined;
2150
+ finalNativeModel = undefined;
2151
+ }
2075
2152
  // No tools, extract text
2076
2153
  const textBlocks = response.content.filter(this.isTextBlock);
2077
2154
  const iterationText = this.remoteResourceSession
@@ -2087,11 +2164,13 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2087
2164
  if (iterationText.trim()) {
2088
2165
  finalContent = iterationText;
2089
2166
  finalReasoning = this.remoteResourceSession ? undefined : response.reasoning;
2167
+ finalReasoningModel = finalReasoning ? request.model : undefined;
2090
2168
  }
2091
2169
  else if (!this.remoteResourceSession && response.reasoning?.trim()) {
2092
2170
  // Reasoning-only output is observable activity too. Keep it without
2093
2171
  // inventing text or losing earlier text on an empty follow-up.
2094
2172
  finalReasoning = response.reasoning;
2173
+ finalReasoningModel = request.model;
2095
2174
  }
2096
2175
  // Skip the buffered pacing when the text was already streamed live.
2097
2176
  if (this.remoteResourceSession ? lastToolTurnText !== iterationText : !this._lastResponseStreamed)
@@ -2105,7 +2184,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2105
2184
  const answer = {
2106
2185
  id: `assistant_${Date.now()}_${iterations}`, role: 'assistant', content: iterationText, timestamp: new Date(),
2107
2186
  turn: requestUsage?.getTurn?.(),
2108
- metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.config.model } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning } : {}) },
2187
+ metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.turnModel(run) } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning, reasoningModel: this.turnModel(run) } : {}) },
2109
2188
  };
2110
2189
  messages.push(answer);
2111
2190
  turnMessages.push(answer);
@@ -2148,9 +2227,9 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2148
2227
  id: `assistant_${Date.now()}`,
2149
2228
  role: 'assistant',
2150
2229
  content: iterationText,
2151
- ...(this.backend.preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.config.model, nativeContextId: this._nativeContextId } : {}),
2230
+ ...(this.turnBackend(run).preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.turnModel(run), nativeContextId: this._nativeContextId } : {}),
2152
2231
  timestamp: new Date(),
2153
- metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.config.model } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning } : {}) },
2232
+ metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.turnModel(run) } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning, reasoningModel: this.turnModel(run) } : {}) },
2154
2233
  };
2155
2234
  messages.push(autoContinueAnswer);
2156
2235
  turnMessages.push(autoContinueAnswer);
@@ -2168,7 +2247,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2168
2247
  }
2169
2248
  if (!this.remoteResourceSession
2170
2249
  && needsCompletionCheck({ usedTools: this._turnToolBatches > 0, hasPendingToolCall: false })
2171
- && completionCheckDue({ autoContinue: this._autoContinue && this.config.completionCheck === true, toolBatches: this._turnToolBatches,
2250
+ && completionCheckDue({ autoContinue: this.getAutoContinue() && this.config.completionCheck === true, toolBatches: this._turnToolBatches,
2172
2251
  changedState: this._turnToolChangedState,
2173
2252
  askedSinceProgress: this._turnCheckAsked,
2174
2253
  turnChecks: this._turnAutoContinues, hardCap: this.config.maxConsecutiveAutoContinues,
@@ -2193,9 +2272,9 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2193
2272
  role: 'assistant',
2194
2273
  turn: requestUsage?.getTurn?.(),
2195
2274
  content: iterationText,
2196
- ...(this.backend.preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.config.model, nativeContextId: this._nativeContextId } : {}),
2275
+ ...(this.turnBackend(run).preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.turnModel(run), nativeContextId: this._nativeContextId } : {}),
2197
2276
  timestamp: new Date(),
2198
- metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.config.model } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning } : {}) },
2277
+ metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.turnModel(run) } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning, reasoningModel: this.turnModel(run) } : {}) },
2199
2278
  };
2200
2279
  messages.push(completionAnswer);
2201
2280
  turnMessages.push(completionAnswer);
@@ -2230,10 +2309,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2230
2309
  id: toolUseMessageId, role: 'assistant',
2231
2310
  content: this.remoteResourceSession ? '[Using tools...]'
2232
2311
  : response.content.filter(this.isTextBlock).map(block => block.text).join('\n') || '[Using tools...]',
2233
- ...(this.backend.preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.config.model, nativeContextId: this._nativeContextId } : {}),
2312
+ ...(this.turnBackend(run).preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.turnModel(run), nativeContextId: this._nativeContextId } : {}),
2234
2313
  timestamp: new Date(), toolCalls: batchCalls,
2235
- metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.config.model } : {}), toolCheckpoint: true, ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? this.remoteResourceSession
2236
- ? { providerReasoning: response.reasoning } : { reasoningContent: response.reasoning } : {}) },
2314
+ metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.turnModel(run) } : {}), toolCheckpoint: true, ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? this.remoteResourceSession
2315
+ ? { providerReasoning: response.reasoning, reasoningModel: this.turnModel(run) } : { reasoningContent: response.reasoning, reasoningModel: this.turnModel(run) } : {}) },
2237
2316
  };
2238
2317
  messages.push(toolUseMessage);
2239
2318
  turnMessages.push(toolUseMessage);
@@ -2536,6 +2615,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2536
2615
  if (answer?.trim()) {
2537
2616
  finalContent = answer;
2538
2617
  finalReasoning = response.reasoning;
2618
+ finalReasoningModel = request.model;
2539
2619
  await this.emitStreamText(answer, signal);
2540
2620
  if (signal?.aborted)
2541
2621
  throw new AgentError('Cancelled', 'CANCELLED');
@@ -2616,11 +2696,12 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2616
2696
  }
2617
2697
  if (this.onMidTurnCompact && shouldCompactMidTurn({
2618
2698
  usedTokens: contextTokens > 0 ? contextTokens : estimateConversationTokens(messages),
2619
- windowTokens: getContextWindowSize(this.config.model, this.midTurnCompactWindow !== undefined ? this.midTurnCompactWindow : usage.contextWindow),
2699
+ windowTokens: getContextWindowSize(this.turnModel(run), run.prepared ? this.turnBackend(run).getModelCapabilities?.(this.turnModel(run))?.context_window ?? null
2700
+ : this.midTurnCompactWindow !== undefined ? this.midTurnCompactWindow : usage.contextWindow),
2620
2701
  thresholdPercent: this.midTurnCompactThresholdPercent ?? 90,
2621
2702
  tokenBudget: this.midTurnCompactTokenBudget,
2622
- reservedOutputTokens: clampCompletionTokens(this.config.model, this.config.maxTokens
2623
- ?? this.backend.getModelCapabilities?.(this.config.model)?.max_output_tokens),
2703
+ reservedOutputTokens: clampCompletionTokens(this.turnModel(run), this.turnMaxTokens(run)
2704
+ ?? this.turnBackend(run).getModelCapabilities?.(this.turnModel(run))?.max_output_tokens),
2624
2705
  messagesSinceLastCompaction: midTurnMessagesSinceCompaction,
2625
2706
  lastFreedTokens: midTurnLastFreedTokens,
2626
2707
  enabled: true,
@@ -2645,6 +2726,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2645
2726
  }
2646
2727
  }
2647
2728
  catch (err) {
2729
+ if (signal?.aborted)
2730
+ err = new AgentError('Cancelled', 'CANCELLED');
2648
2731
  const error = err.message;
2649
2732
  this.emit({ type: 'error', error });
2650
2733
  throw err;
@@ -2697,10 +2780,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2697
2780
  toolCalls: allToolCalls,
2698
2781
  usage: totalUsage || undefined,
2699
2782
  stopReason,
2700
- ...(finalReasoning ? { reasoning: finalReasoning } : {}),
2783
+ ...(finalReasoning ? { reasoning: finalReasoning, reasoningModel: finalReasoningModel } : {}),
2701
2784
  responseItems: finalResponseItems,
2702
- ...(finalResponseItems ? { nativeModel: this.config.model } : {}),
2703
- ...(finalNativeContent ? { nativeContent: finalNativeContent, nativeModel: this.config.model, nativeContextId: this._nativeContextId } : {}),
2785
+ ...(finalResponseItems ? { nativeModel: finalResponseModel } : {}),
2786
+ ...(finalNativeContent ? { nativeContent: finalNativeContent, nativeModel: finalNativeModel, nativeContextId: this._nativeContextId } : {}),
2704
2787
  turnMessages,
2705
2788
  };
2706
2789
  }
@@ -2924,11 +3007,12 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2924
3007
  }
2925
3008
  return source;
2926
3009
  }
2927
- // API call with retry logic for transient errors
2928
- async callAPI(request, onProviderObservation, signal, checkpointContext, onReturnedResponse, onUsage) {
3010
+ // API call with retry logic for transient errors. RUN's request goes through its own host policy's snapshot.
3011
+ async callAPI(request, onProviderObservation, signal, checkpointContext, onReturnedResponse, onUsage, run = this.activeRun) {
2929
3012
  const { maxAttempts, recoveryWindowMs } = this.config.apiRetry;
2930
3013
  const timeoutMs = this.config.llmRequestTimeoutMs;
2931
- if (this.backend.handlesTransportRetries?.(request) === true) {
3014
+ const backend = this.turnBackend(run);
3015
+ if (backend.handlesTransportRetries?.(request) === true) {
2932
3016
  request = { ...request, transportTurnId: request.transportTurnId ?? randomUUID() };
2933
3017
  }
2934
3018
  // Real token streaming when the backend streams natively (ZTC_NO_STREAM=1
@@ -2942,14 +3026,14 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2942
3026
  // non-authoritative (never replayed to the provider, rendered as its own
2943
3027
  // labelled block), so a transport drop during a long thinking phase on a
2944
3028
  // model like deepseek can regenerate the turn instead of killing the run.
2945
- const useStream = process.env.ZTC_NO_STREAM !== '1' && !this.backend.streamsSyntheticallyFor?.(request);
3029
+ const useStream = process.env.ZTC_NO_STREAM !== '1' && !backend.streamsSyntheticallyFor?.(request);
2946
3030
  let answerOutputEmitted = false;
2947
3031
  let effectObserved = false;
2948
3032
  let freshTurnRetried = false;
2949
3033
  let recoveryStartedAt;
2950
3034
  let rateLimitedAttempts = 0;
2951
3035
  let lastReason = 'Server temporarily unavailable';
2952
- const canRegenerate = () => this.backend.allowsRequestRetryAfterFailure?.(request) !== false;
3036
+ const canRegenerate = () => backend.allowsRequestRetryAfterFailure?.(request) !== false;
2953
3037
  const returned = (response) => { onReturnedResponse?.(response); return response; };
2954
3038
  for (let attempt = 1;; attempt++) {
2955
3039
  if (signal?.aborted) {
@@ -3051,7 +3135,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3051
3135
  this._lastResponseStreamed = true;
3052
3136
  try {
3053
3137
  return await Promise.race([
3054
- this.streamAndAssemble(guardedRequest, signal, () => { answerOutputEmitted = true; }, onUsage).then(returned),
3138
+ this.streamAndAssemble(backend, guardedRequest, signal, () => { answerOutputEmitted = true; }, onUsage).then(returned),
3055
3139
  guardPromise,
3056
3140
  ]);
3057
3141
  }
@@ -3062,7 +3146,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3062
3146
  // cancel/timeout), fall back to the buffered generate() for this
3063
3147
  // attempt — never regress a turn just because generateStream can't
3064
3148
  // serve this request.
3065
- if (this.backend.allowsBufferedFallbackAfterStreamFailure?.(guardedRequest) === false
3149
+ if (backend.allowsBufferedFallbackAfterStreamFailure?.(guardedRequest) === false
3066
3150
  || isIncompleteStreamError(streamErr)
3067
3151
  || !canRegenerate() || effectObserved || answerOutputEmitted || timedOut || signal?.aborted
3068
3152
  || streamErr instanceof RunawayOutputError
@@ -3072,7 +3156,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3072
3156
  this._lastResponseStreamed = false;
3073
3157
  streamingAttempt = false;
3074
3158
  return await Promise.race([
3075
- this.backend.generate(guardedRequest).then(response => {
3159
+ backend.generate(guardedRequest).then(response => {
3076
3160
  if (response.usage)
3077
3161
  onUsage?.(response.usage);
3078
3162
  return returned(response);
@@ -3083,7 +3167,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3083
3167
  }
3084
3168
  this._lastResponseStreamed = false;
3085
3169
  return await Promise.race([
3086
- this.backend.generate(guardedRequest).then(response => {
3170
+ backend.generate(guardedRequest).then(response => {
3087
3171
  if (response.usage)
3088
3172
  onUsage?.(response.usage);
3089
3173
  return returned(response);
@@ -3105,7 +3189,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3105
3189
  if (err instanceof RunawayOutputError || timedOut || signal?.aborted
3106
3190
  || (err instanceof AgentError && err.code === 'CANCELLED')) {
3107
3191
  attemptController.abort();
3108
- void this.backend.cancelTurn?.(guardedRequest).catch(() => undefined);
3192
+ void backend.cancelTurn?.(guardedRequest).catch(() => undefined);
3109
3193
  }
3110
3194
  if (err instanceof AgentError && err.code === 'CANCELLED') {
3111
3195
  throw err;
@@ -3362,10 +3446,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3362
3446
  }
3363
3447
  // Non-retryable errors with clean messages
3364
3448
  if (statusCode === 401 || errorType === 'authentication_error' || errorType === 'UNAUTHENTICATED') {
3365
- return {
3366
- retryable: false,
3367
- reason: 'Authentication failed. Check your API key or auth configuration.',
3368
- };
3449
+ return { retryable: false, reason: authenticationFailure(this.keyProvider, message) };
3369
3450
  }
3370
3451
  if (statusCode === 403 || errorType === 'PERMISSION_DENIED') {
3371
3452
  return { retryable: false, reason: admissionMessage || 'Permission denied' };
@@ -3383,18 +3464,6 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3383
3464
  : `This model needs an active Zerg Router subscription. ${guidance}`,
3384
3465
  };
3385
3466
  }
3386
- // Keep the Router's setup failure actionable without echoing arbitrary
3387
- // remote bodies. Only these known provider names can enter the message.
3388
- const missingRouterKey = typeof errorMessage === 'string'
3389
- ? errorMessage.match(/^No API key available for provider: (anthropic|openai|gemini|deepseek|kimi|modal|inception|clarifai|openrouter|fireworks)$/)
3390
- : null;
3391
- if (statusCode === 400 && message.startsWith('ZRouter API error (') && missingRouterKey) {
3392
- const provider = missingRouterKey[1];
3393
- // Modal runs only on Zerg's own key, so another model is the only way on.
3394
- return { retryable: false, reason: provider === 'modal'
3395
- ? 'Zerg Router has no key for modal, so it cannot run this model. Choose another model with /model.'
3396
- : `Zerg Router has no key for ${provider}. Add one in Zerg Router, or choose another model with /model.` };
3397
- }
3398
3467
  // OpenRouter choices that leave no provider: Router names the cause, and it stays until changed.
3399
3468
  const openRouterNext = admissionCode === 'openrouter_limits_unmet'
3400
3469
  ? 'Loosen them on the reasoning page (/effort) or with /config openrouter limit.'
@@ -3425,6 +3494,25 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3425
3494
  }
3426
3495
  /** The longest provider message an error shows, on one line. */
3427
3496
  const PROVIDER_DETAIL_CHARS = 300;
3497
+ /**
3498
+ * What a 401 says. The provider's own API turning away what ZTC sent (a direct route's `API error (401)`) names the
3499
+ * provider and where its key, or this computer's sign-in to it, is fixed. Any other route keeps the general words:
3500
+ * Zerg Router's 401 on the person's own sign-in is worded by its backend (RouterAuthenticationError), and a
3501
+ * credential a host or the ZergAI platform gives this ZTC is theirs to fix.
3502
+ */
3503
+ function authenticationFailure(provider, message) {
3504
+ const named = provider ? normalizeProviderId(provider) : undefined;
3505
+ if (!named || !/^(?:Codex )?API error \(/.test(message))
3506
+ return 'Authentication failed. Check your API key or auth configuration.';
3507
+ // A provider named by another of its names (moonshot) is the one /config key knows (kimi).
3508
+ const choice = PROVIDER_CHOICES.find(entry => entry.id === named || entry.aliases?.includes(named));
3509
+ const id = choice?.id ?? named;
3510
+ const label = choice?.label ?? named;
3511
+ if (isLocalSubscriptionProvider(id))
3512
+ return `Authentication failed: ${label} didn't accept this computer's sign-in. Sign in again through /accounts.`;
3513
+ return `Authentication failed: ${id === 'openai_compatible' ? `the ${label} endpoint` : label} didn't accept the API key ZTC sent. `
3514
+ + `Check it with /config key ${id}.`;
3515
+ }
3428
3516
  /** The message inside a provider's raw error body: Anthropic's error.message, a bare message, or the text itself. */
3429
3517
  function nestedProviderMessage(raw) {
3430
3518
  try {