@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
@@ -6,7 +6,8 @@ import { KIMI_CODE_AUTH_SENTINEL } from './backends/kimi_code_auth.js';
6
6
  import { CODEX_APP_SERVER_SENTINEL, isCodexAppServerProvider, isCodexLegacyProvider, isLocalSubscriptionProvider, normalizeProviderId } from './backends/provider_ids.js';
7
7
  import { accountBackendOptions, resolveActiveAccount, isAccountProvider, canonicalAccountProvider, sourceDir } from './backends/account_pool.js';
8
8
  import { assertProviderNotRetired } from '../config/retired_routes.js';
9
- import { routerOnlyModelError } from './commands/provider_choices.js';
9
+ import { PROVIDER_CHOICES, routerOnlyModelError } from './commands/provider_choices.js';
10
+ import { routerCredentialsUrl } from './backends/router_keys.js';
10
11
  import { getEmulationProfile, buildRuntimeContext } from '../emulation/catalog.js';
11
12
  import { getEmulationMappingAddendum, emulationUsesPaneTools } from '../emulation/mappings.js';
12
13
  import { buildEmulationCompatibilityTools, getEmulationToolMapping } from '../emulation/tool_adapters.js';
@@ -268,10 +269,17 @@ export function resolveAgentBackendFromConfig(options) {
268
269
  apiKey = proxyToken;
269
270
  const connection = configStore.getRouterCatalogConnection(proxyUrl);
270
271
  const workspaceId = connection?.token === apiKey ? connection.workspaceId : undefined;
272
+ // On the person's own Router sign-in, a refusal for want of a provider key links that Router's Credentials page,
273
+ // and each request goes with the sign-in as the profile holds it then: another pane's login retires this key.
274
+ const personal = configStore.getPersonalRouterCredential();
275
+ const ownSignIn = personal && connection && connection.token === apiKey && connection.token === personal.token ? connection : undefined;
276
+ const providerLabel = PROVIDER_CHOICES.find(choice => choice.id === provider)?.label;
271
277
  runtimeDiag('info', `[ztc] routing LLM via ZergRouter proxy ${JSON.stringify({ proxy_url: proxyUrl, provider, has_token: Boolean(proxyToken) })}`);
272
278
  backend = new ZRouterStreamBackend({ apiKey, proxyUrl: proxyUrl, provider, model: llm.model, conversationId: options.sessionId,
273
279
  workspaceId, openRouterPreferences: () => configStore.get().openRouter,
274
- catalog: readRouterCatalog({ origin: proxyUrl, token: apiKey, workspaceId }) });
280
+ catalog: readRouterCatalog({ origin: proxyUrl, token: apiKey, workspaceId }),
281
+ ...(providerLabel ? { providerLabel } : {}),
282
+ ...(ownSignIn ? { credentialsUrl: routerCredentialsUrl(ownSignIn.origin), routerSignIn: () => configStore.getRouterSignIn(ownSignIn.origin) } : {}) });
275
283
  }
276
284
  else if (provider === 'bedrock') {
277
285
  backend = createBackendForProvider(provider, { apiKey: '' });
@@ -0,0 +1,9 @@
1
+ import type { AgentBackend, BackendRequest } from './backends/types.js';
2
+ /** Use the selected model's catalog, including system/tools and output reserve. */
3
+ export declare function hostModelContextBudget(backend: AgentBackend, request: BackendRequest): {
4
+ windowTokens: number;
5
+ usedTokens: number;
6
+ reservedOutputTokens: number;
7
+ exceeded: boolean;
8
+ } | undefined;
9
+ export declare function hostModelContextError(request: BackendRequest, windowTokens: number): string;
@@ -0,0 +1,40 @@
1
+ import { clampCompletionTokens } from '../utils/deepseek.js';
2
+ /** Use the selected model's catalog, including system/tools and output reserve. */
3
+ export function hostModelContextBudget(backend, request) {
4
+ const capabilities = backend.getModelCapabilities?.(request.model);
5
+ const windowTokens = capabilities?.context_window;
6
+ if (!windowTokens || windowTokens <= 0)
7
+ return undefined;
8
+ // Text-only admission estimate. Encoded media and opaque signatures are
9
+ // transport bytes, not text tokens; their actual cost is provider-accounted.
10
+ // Still reject an oversized text portion even when media is attached.
11
+ const content = (block) => {
12
+ switch (block.type) {
13
+ case 'image':
14
+ case 'video': return { type: block.type };
15
+ case 'redacted_thinking': return { type: block.type };
16
+ case 'responses_reasoning': return { type: block.type, summary: block.item.summary };
17
+ case 'thinking': return { type: block.type, thinking: block.thinking };
18
+ case 'tool_use': return { type: block.type, id: block.id, name: block.name, input: block.input };
19
+ case 'tool_result': return { ...block, content: typeof block.content === 'string' ? block.content
20
+ : block.content.map(item => item.type === 'image' ? { type: item.type } : item) };
21
+ default: return block;
22
+ }
23
+ };
24
+ const messages = request.messages.map(message => ({ ...message,
25
+ responseItems: message.responseItems?.map(item => ({ ...item, encrypted_content: undefined })),
26
+ content: typeof message.content === 'string' ? message.content : message.content.map(content) }));
27
+ const usedTokens = Math.ceil((request.system.length + JSON.stringify(request.tools).length
28
+ + JSON.stringify(messages).length) / 4);
29
+ // An explicit output limit is reserved in full. Without one, the request carries the catalog maximum, which can
30
+ // equal the whole window; the provider then decides, as it does without a host policy. Reserving all of it here
31
+ // would refuse every turn before sending, so reserve at most a quarter of the window.
32
+ const reservedOutputTokens = clampCompletionTokens(request.model, request.maxTokens)
33
+ ?? Math.min(clampCompletionTokens(request.model, capabilities?.max_output_tokens) ?? 0, Math.floor(windowTokens * 0.25));
34
+ return { windowTokens, usedTokens, reservedOutputTokens,
35
+ exceeded: usedTokens + reservedOutputTokens > windowTokens };
36
+ }
37
+ export function hostModelContextError(request, windowTokens) {
38
+ return `Host-selected model ${request.model} has a ${windowTokens}-token context window. `
39
+ + 'This conversation does not fit with its output budget. Compact the conversation, start a new one, or select a larger model.';
40
+ }
@@ -20,6 +20,9 @@ import { LlmMessage, RequestContentBlock } from './backends/index.js';
20
20
  export interface EncodeDeps {
21
21
  preserveNativeHistory?: boolean;
22
22
  model?: string;
23
+ /** Model used by older, untagged reasoning before a host override. */
24
+ legacyReasoningModel?: string;
25
+ isModelCompatible?: (model: string) => boolean;
23
26
  nativeContextId?: string;
24
27
  /**
25
28
  * Per-request tool-result selector verdict (tool_use_id -> rendered content),
@@ -62,15 +62,20 @@ export class RequestEncoder {
62
62
  metadata: { synthetic: true, hostContext: true, preserveUserBoundary: true },
63
63
  }, message];
64
64
  });
65
+ const managed = this.deps.legacyReasoningModel !== undefined;
66
+ const sameModel = (model) => typeof model === 'string'
67
+ && (this.deps.isModelCompatible?.(model) ?? model === this.deps.model);
65
68
  const formatted = eligibleMessages
66
69
  .map(m => {
67
70
  const responseItems = Array.isArray(m.metadata?.openaiResponseItems)
68
- && (m.metadata?.openaiResponseModel === undefined || m.metadata?.openaiResponseModel === this.deps.model)
69
- && (!this.deps.preserveNativeHistory || m.nativeContextId === undefined || m.nativeContextId === this.deps.nativeContextId)
71
+ && (managed ? sameModel(m.metadata?.openaiResponseModel)
72
+ && m.nativeContextId !== undefined && m.nativeContextId === this.deps.nativeContextId
73
+ : (m.metadata?.openaiResponseModel === undefined || sameModel(m.metadata?.openaiResponseModel))
74
+ && (!this.deps.preserveNativeHistory || m.nativeContextId === undefined || m.nativeContextId === this.deps.nativeContextId))
70
75
  ? m.metadata?.openaiResponseItems : undefined;
71
76
  const assistantContent = m.role === 'assistant' ? assistantClaimReplayContent(m) : m.content;
72
- if (this.deps.preserveNativeHistory && m.nativeContent !== undefined && m.nativeModel === this.deps.model
73
- && m.nativeContextId === this.deps.nativeContextId) {
77
+ if (this.deps.preserveNativeHistory && m.nativeContent !== undefined && sameModel(m.nativeModel)
78
+ && (!managed || m.nativeContextId !== undefined) && m.nativeContextId === this.deps.nativeContextId) {
74
79
  if (typeof m.nativeContent === 'string' && assistantContent !== m.content) {
75
80
  // The host may have observed this claim after its plain native text
76
81
  // was frozen. Retain the admitted qualification on every replay.
@@ -93,7 +98,9 @@ export class RequestEncoder {
93
98
  content
94
99
  };
95
100
  }
101
+ const reasoningModel = m.metadata?.reasoningModel ?? this.deps.legacyReasoningModel;
96
102
  const reasoning = typeof m.metadata?.reasoningContent === 'string'
103
+ && (!managed || sameModel(reasoningModel))
97
104
  ? m.metadata.reasoningContent
98
105
  : undefined;
99
106
  // A model switch starts a fresh reasoning context. Preserve factual
@@ -12,6 +12,7 @@ import { recallToolResponseTool } from '../tools/recall_tool_response.js';
12
12
  import { sessionEvidenceTool } from '../tools/session_evidence.js';
13
13
  import { parseVerificationRequest } from './source_verification_contract.js';
14
14
  import { readCommandTool, runCommandTool, stopCommandTool } from '../tools/shell.js';
15
+ import { ztcCommandCapabilities, ztcCommandTool } from '../tools/ztc_command.js';
15
16
  import { verifyArtifactTool } from '../tools/verify_artifact.js';
16
17
  import { benchmarkCPUTool } from '../tools/benchmark_cpu.js';
17
18
  import { compareBenchmarksTool } from '../tools/compare_benchmarks.js';
@@ -164,9 +165,14 @@ export async function executeToolWithRuntime(name, args, options) {
164
165
  const sourceTool = tool?.outputSource ?? tool;
165
166
  const traceStartedAt = Date.now();
166
167
  const ordinaryCapabilities = getRuntimeCapabilities(tool);
168
+ // A ztc_command call also needs what its command does (ztcCommandCapabilities): /claude and /codex start a program
169
+ // that runs commands, so the profile refuses them, or asks first, as it does a shell.
170
+ const callCapabilities = (input) => (sourceTool === ztcCommandTool
171
+ ? [...new Set([...ordinaryCapabilities, ...ztcCommandCapabilities(input)])]
172
+ : ordinaryCapabilities);
167
173
  const requiredCapabilities = (input) => (sourceTool === runCommandTool && Object.hasOwn(input, 'verification')
168
174
  ? [...new Set([...ordinaryCapabilities, ToolCapability.FILE_READ])]
169
- : ordinaryCapabilities);
175
+ : callCapabilities(input));
170
176
  let capabilities = requiredCapabilities(args);
171
177
  let effectiveArgs = args;
172
178
  let approvalGranted = false;
@@ -325,7 +331,7 @@ export async function executeToolWithRuntime(name, args, options) {
325
331
  const decision = options.policy.evaluateTool({
326
332
  name,
327
333
  args: effectiveArgs,
328
- capabilities: ordinaryCapabilities,
334
+ capabilities: callCapabilities(effectiveArgs),
329
335
  ...(policyExecutionCwd === undefined ? {} : { executionCwd: policyExecutionCwd }),
330
336
  });
331
337
  profileApprovalRequired = decision.approvalRequired === true;
@@ -44,6 +44,10 @@ export interface SubAgentResult {
44
44
  export declare class SubAgent {
45
45
  private config;
46
46
  private backend;
47
+ /** The backend and model a run's request goes with: the host policy's snapshot that run prepared (prepareTurn),
48
+ * else the worker's own. Each run keeps its own, so a second run, refused or finished, never changes the first's. */
49
+ private turnBackend;
50
+ private turnModel;
47
51
  private model;
48
52
  /**
49
53
  * This run's identity for container affinity.
@@ -101,6 +105,11 @@ export declare class SubAgent {
101
105
  * Track what the sub-agent accessed
102
106
  */
103
107
  private trackToolUsage;
108
+ /**
109
+ * The host policy's snapshot for the request a run builds next (undefined without a policy), for that run to keep.
110
+ */
111
+ private prepareTurn;
112
+ private prepareRequest;
104
113
  /**
105
114
  * Format messages for the API
106
115
  */
@@ -24,6 +24,7 @@ import { listCommandJobs, shutdownCommandJobs } from './runtime/command_jobs.js'
24
24
  import { awaitManagedCommandProgress, formatManagedCommandObservations } from './runtime/command_wait.js';
25
25
  import { scheduleToolBatch, commandStillRunning } from './runtime/tool_scheduler.js';
26
26
  import { configStore } from '../config.js';
27
+ import { hostModelContextBudget, hostModelContextError } from './host_model_context.js';
27
28
  import { RequestEncoder, nativeHistoryContextId } from './request_encoder.js';
28
29
  import { presentToolResult, toolCallNames } from './tool_result_presentation.js';
29
30
  import { ToolResponseIntegrityError, ToolResponseStore } from './tool_response_store.js';
@@ -171,6 +172,10 @@ function createBackend(provider, apiKey) {
171
172
  export class SubAgent {
172
173
  config;
173
174
  backend;
175
+ /** The backend and model a run's request goes with: the host policy's snapshot that run prepared (prepareTurn),
176
+ * else the worker's own. Each run keeps its own, so a second run, refused or finished, never changes the first's. */
177
+ turnBackend(turn) { return turn?.backend ?? this.backend; }
178
+ turnModel(turn) { return turn?.options.model ?? this.model; }
174
179
  model;
175
180
  /**
176
181
  * This run's identity for container affinity.
@@ -218,8 +223,6 @@ export class SubAgent {
218
223
  * @param opts Optional overrides (abort signal, custom system prompt, tools)
219
224
  */
220
225
  async run(task, opts) {
221
- if (this.backend.getModelCapabilities?.(this.model)?.tools === false)
222
- throw new Error('Chat-only models cannot run tool-dependent subagents.');
223
226
  const signal = opts?.signal;
224
227
  const startTime = Date.now();
225
228
  const timeoutMs = this.config.timeoutMs || 120000; // 2 minute default
@@ -244,15 +247,7 @@ export class SubAgent {
244
247
  });
245
248
  // This summary-producing worker does not own the parent checklist or
246
249
  // terminal answer lifecycle.
247
- const tools = (opts?.tools ?? RESEARCH_TOOLS).filter(tool => !tool.finalResponse);
248
- // A native host supplies a closed, bounded vocabulary. Adding ambient
249
- // helper schemas can reject that otherwise valid request before dispatch.
250
- if (!this.backend.preservesNativeHistory || opts?.tools === undefined) {
251
- for (const tool of [recallToolResponseTool, sessionEvidenceTool]) {
252
- if (!tools.some(existing => existing.definition.name === tool.definition.name))
253
- tools.push(tool);
254
- }
255
- }
250
+ const suppliedTools = (opts?.tools ?? RESEARCH_TOOLS).filter(tool => !tool.finalResponse);
256
251
  const messages = [
257
252
  ...structuredClone(opts?.messages ?? []),
258
253
  {
@@ -279,6 +274,8 @@ export class SubAgent {
279
274
  let responseRetry = null;
280
275
  let outputLimitRetried = false;
281
276
  let runawayRetried = false;
277
+ // This run's host policy snapshot for the request it is building: its own, never another run's.
278
+ let prepared;
282
279
  const publishEvidence = () => {
283
280
  opts?.onEvent?.({ type: 'evidence', sessionId: this.sessionId, snapshot: this.getEvidenceSnapshot() });
284
281
  };
@@ -287,7 +284,7 @@ export class SubAgent {
287
284
  parentSessionId: this.config.parentSessionId, cwd: this.cwd });
288
285
  await bindDelegatedEvidence(this.toolResponseStore, this.discoveredTools, { sessionId: this.sessionId, parentSessionId: this.config.parentSessionId, cwd: this.cwd }, this.config.resumeSessionId !== undefined);
289
286
  evidenceBound = true;
290
- await this.persistEvidenceCheckpoint();
287
+ await this.persistEvidenceCheckpoint(this.model);
291
288
  publishEvidence();
292
289
  while (iterations < maxIterations) {
293
290
  checkTimeout();
@@ -297,6 +294,16 @@ export class SubAgent {
297
294
  messages.push({ id: `lead_message_${randomUUID()}`, role: 'user', content: `[Message from your lead]\n${message}`,
298
295
  timestamp: new Date(), metadata: { synthetic: true, hostContext: true } });
299
296
  }
297
+ prepared = await this.prepareTurn(runSignal, responseRetry?.effort);
298
+ const tools = [...suppliedTools];
299
+ // Explicit native vocabularies stay closed; portable turns need recall
300
+ // helpers. Reevaluate after each policy refresh, in both directions.
301
+ if (!this.turnBackend(prepared).preservesNativeHistory || opts?.tools === undefined) {
302
+ for (const tool of [recallToolResponseTool, sessionEvidenceTool]) {
303
+ if (!tools.some(existing => existing.definition.name === tool.definition.name))
304
+ tools.push(tool);
305
+ }
306
+ }
300
307
  // Stamp new host observations and changed run state into a new user
301
308
  // row. Earlier rows and the system prompt keep their original bytes,
302
309
  // so each request extends the last one and its prefix stays cached.
@@ -321,28 +328,16 @@ export class SubAgent {
321
328
  // The retry note goes only to the retried request.
322
329
  const requestMessages = responseRetry ? [...messages, { id: `retry_note_${randomUUID()}`, role: 'user',
323
330
  content: responseRetry.note, timestamp: new Date(), metadata: { synthetic: true, hostContext: true } }] : messages;
324
- const request = {
325
- model: this.model,
326
- // No fixed output cap: a reasoning model spends much of it before acting.
327
- ...(responseRetry?.effort ? { codexEffort: responseRetry.effort } : {}),
328
- // R7 parity: pin the task in request.system so a long subagent run
329
- // can't lose the task framing the same way the main loop could (F9).
330
- system,
331
- messages: this.formatMessages(requestMessages, contextId),
332
- tools: definitions,
333
- // The inherited backend is pinned to the parent conversation; this is
334
- // what tells it the prefix being sent is this run's instead.
335
- agentRunId: this.agentRunId,
336
- signal: runSignal,
337
- };
331
+ const request = this.prepareRequest(prepared, requestMessages, system, definitions, runSignal, responseRetry?.effort);
332
+ const backend = this.turnBackend(prepared);
338
333
  // Name the Router turn here, so an abandoned response can be cancelled by it.
339
- if (this.backend.handlesTransportRetries?.(request))
334
+ if (backend.handlesTransportRetries?.(request))
340
335
  request.transportTurnId = randomUUID();
341
336
  const retriedRequest = responseRetry !== null;
342
337
  responseRetry = null;
343
338
  let response;
344
339
  try {
345
- response = await generateWorkerResponse(this.backend, request);
340
+ response = await generateWorkerResponse(backend, request);
346
341
  }
347
342
  catch (error) {
348
343
  opts?.onUsage?.({ inputTokens: 0, outputTokens: 0, totalTokens: 0, estimated: true, unreported: true });
@@ -351,14 +346,14 @@ export class SubAgent {
351
346
  // a turn after the client leaves, so cancel it.
352
347
  const runaway = error instanceof RunawayOutputError;
353
348
  if (runaway || runSignal.aborted)
354
- void this.backend.cancelTurn?.(request).catch(() => undefined);
349
+ void backend.cancelTurn?.(request).catch(() => undefined);
355
350
  if (!runaway)
356
351
  throw error;
357
352
  if (runawayRetried)
358
353
  throw new Error(repeatedRunawayMessage(error));
359
354
  runawayRetried = true;
360
355
  responseRetry = { note: RUNAWAY_OUTPUT_RETRY_NOTE,
361
- effort: outputLimitRetryEffort(this.backend.getModelCapabilities?.(this.model)?.reasoning?.choices, undefined) };
356
+ effort: outputLimitRetryEffort(backend.getModelCapabilities?.(this.turnModel(prepared))?.reasoning?.choices, undefined) };
362
357
  continue;
363
358
  }
364
359
  if (response.usage)
@@ -389,7 +384,7 @@ export class SubAgent {
389
384
  && !response.content.some(block => block.type === 'text' && block.text.trim())) {
390
385
  outputLimitRetried = true;
391
386
  responseRetry = { note: OUTPUT_LIMIT_RETRY_NOTE,
392
- effort: outputLimitRetryEffort(this.backend.getModelCapabilities?.(this.model)?.reasoning?.choices, undefined) };
387
+ effort: outputLimitRetryEffort(backend.getModelCapabilities?.(this.turnModel(prepared))?.reasoning?.choices, undefined) };
393
388
  continue;
394
389
  }
395
390
  throw new Error(incompleteModelResponseMessage(response.stopReason, request.maxTokens, response.usage?.outputTokens));
@@ -428,7 +423,7 @@ export class SubAgent {
428
423
  occupiedIds.add(id);
429
424
  toolUseBlocks.push({ ...block, id });
430
425
  }
431
- if (this.backend.preservesNativeHistory && toolUseBlocks.length > 0) {
426
+ if (backend.preservesNativeHistory && toolUseBlocks.length > 0) {
432
427
  // Keep signed/opaque native blocks intact while pairing tool-use IDs
433
428
  // with the canonical result identities admitted above.
434
429
  const canonicalIds = new Map(requestedToolBlocks.map((block, index) => [block.id, toolUseBlocks[index].id]));
@@ -532,7 +527,7 @@ export class SubAgent {
532
527
  id: toolUseMessageId,
533
528
  role: 'assistant',
534
529
  content: textContent || '[Using tools...]',
535
- ...(this.backend.preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.model, nativeContextId: contextId } : {}),
530
+ ...(backend.preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.turnModel(prepared), nativeContextId: contextId } : {}),
536
531
  timestamp: new Date(),
537
532
  toolCalls: toolUseBlocks.map(tb => ({
538
533
  id: tb.id,
@@ -543,8 +538,8 @@ export class SubAgent {
543
538
  // Reasoning models expect each historical assistant tool-call turn
544
539
  // replayed with its reasoning_content; without this a multi-iteration
545
540
  // subagent sends a stripped history on every pass (mirrors the main loop).
546
- metadata: { ...(response.reasoning ? { reasoningContent: response.reasoning } : {}),
547
- ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.model } : {}) },
541
+ metadata: { ...(response.reasoning ? { reasoningContent: response.reasoning, reasoningModel: this.turnModel(prepared) } : {}),
542
+ ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.turnModel(prepared) } : {}) },
548
543
  });
549
544
  // Add tool results
550
545
  messages.push({
@@ -591,9 +586,9 @@ export class SubAgent {
591
586
  content: `You have used all ${maxIterations} steps. Do not call tools. Report now what you found, with file paths and `
592
587
  + 'line numbers, and what you did not get to.',
593
588
  metadata: { synthetic: true, hostContext: true } }];
594
- const response = await generateWorkerResponse(this.backend, { model: this.model, system,
595
- messages: this.formatMessages(wrapUp, nativeHistoryContextId(system, [])), tools: [], agentRunId: this.agentRunId,
596
- signal: runSignal });
589
+ prepared = await this.prepareTurn(runSignal);
590
+ const request = this.prepareRequest(prepared, wrapUp, system, [], runSignal);
591
+ const response = await generateWorkerResponse(this.turnBackend(prepared), request);
597
592
  opts?.onUsage?.(response.usage ?? { inputTokens: 0, outputTokens: 0, totalTokens: 0, estimated: true, unreported: true });
598
593
  this.inputTokens += response.usage?.inputTokens || 0;
599
594
  this.outputTokens += response.usage?.outputTokens || 0;
@@ -606,7 +601,7 @@ export class SubAgent {
606
601
  }
607
602
  }
608
603
  const durationMs = Date.now() - startTime;
609
- await this.persistEvidenceCheckpoint();
604
+ await this.persistEvidenceCheckpoint(this.turnModel(prepared));
610
605
  // Exhausted maxIterations while still requesting tools = did NOT finish.
611
606
  const exhausted = !completedCleanly;
612
607
  const success = !exhausted;
@@ -714,12 +709,12 @@ export class SubAgent {
714
709
  throw error;
715
710
  }
716
711
  }
717
- async persistEvidenceCheckpoint() {
712
+ async persistEvidenceCheckpoint(model) {
718
713
  await this.toolResponseStore.flush();
719
714
  // Delegated instructions originate with the parent model, not the user.
720
715
  // Save a canonical evidence checkpoint without synthesizing user directives
721
716
  // or transferring a child conversation's permissions through task handoff.
722
- await saveSessionToFile(getSessionPathForCwd(this.cwd, this.sessionId), this.sessionId, this.cwd, [], this.model, this.config.provider, undefined, undefined, { evidence: this.getEvidenceSnapshot(), mode: 'delegated' });
717
+ await saveSessionToFile(getSessionPathForCwd(this.cwd, this.sessionId), this.sessionId, this.cwd, [], model, this.config.provider, undefined, undefined, { evidence: this.getEvidenceSnapshot(), mode: 'delegated' });
723
718
  }
724
719
  evidenceSource(toolCallId, toolName, args, managed) {
725
720
  const source = { origin: managed ? 'host_receipt' : 'host_tool', toolCallId, toolName, cwd: this.cwd,
@@ -754,13 +749,34 @@ export class SubAgent {
754
749
  // search and list_directory don't need tracking
755
750
  }
756
751
  }
752
+ /**
753
+ * The host policy's snapshot for the request a run builds next (undefined without a policy), for that run to keep.
754
+ */
755
+ async prepareTurn(signal, codexEffort) {
756
+ const turn = await this.backend.prepareTurn?.({ model: this.model, signal, codexEffort });
757
+ if (this.turnBackend(turn).getModelCapabilities?.(this.turnModel(turn))?.tools === false) {
758
+ throw new Error('Chat-only models cannot run tool-dependent subagents.');
759
+ }
760
+ return turn;
761
+ }
762
+ prepareRequest(turn, messages, system, tools, signal, codexEffort) {
763
+ const request = {
764
+ ...(turn?.options ?? { model: this.model, signal, codexEffort }), system, tools,
765
+ messages: this.formatMessages(turn, messages, nativeHistoryContextId(system, tools)), agentRunId: this.agentRunId,
766
+ };
767
+ const budget = turn ? hostModelContextBudget(this.turnBackend(turn), request) : undefined;
768
+ if (budget?.exceeded)
769
+ throw new Error(hostModelContextError(request, budget.windowTokens));
770
+ return request;
771
+ }
757
772
  /**
758
773
  * Format messages for the API
759
774
  */
760
- formatMessages(messages, contextId) {
761
- if (this.backend.preservesNativeHistory) {
762
- return new RequestEncoder({ preserveNativeHistory: true, model: this.model,
763
- nativeContextId: contextId,
775
+ formatMessages(turn, messages, contextId) {
776
+ if (this.turnBackend(turn).preservesNativeHistory) {
777
+ return new RequestEncoder({ preserveNativeHistory: true, model: this.turnModel(turn),
778
+ nativeContextId: contextId, legacyReasoningModel: turn ? this.model : undefined,
779
+ isModelCompatible: turn?.isModelCompatible,
764
780
  selectorVerdict: null,
765
781
  currentTurnToolIds: new Set(messages.flatMap(message => message.toolCalls?.map(call => call.id) ?? [])),
766
782
  renderForContext: () => null, loadImageBlock: () => null, loadVideoBlock: () => null,
@@ -795,9 +811,12 @@ export class SubAgent {
795
811
  // main-loop encoder does (request_encoder.ts) — Kimi expects it back.
796
812
  // No metadata.reasoning display-message filter here: the subagent loop
797
813
  // builds its own history and never creates UI-only reasoning bubbles.
798
- const responseItems = Array.isArray(m.metadata?.openaiResponseItems) && m.metadata?.openaiResponseModel === this.model
814
+ const responseItems = Array.isArray(m.metadata?.openaiResponseItems) && m.metadata?.openaiResponseModel === this.turnModel(turn)
799
815
  ? m.metadata?.openaiResponseItems : undefined;
816
+ const reasoningModel = m.metadata?.reasoningModel ?? this.model;
800
817
  const reasoning = typeof m.metadata?.reasoningContent === 'string'
818
+ && (!turn || (typeof reasoningModel === 'string'
819
+ && (turn.isModelCompatible?.(reasoningModel) ?? reasoningModel === this.turnModel(turn))))
801
820
  ? m.metadata.reasoningContent
802
821
  : undefined;
803
822
  // Assistant message with tool calls
@@ -28,6 +28,14 @@ async function dockerExec(command) {
28
28
  const fullCmd = `docker exec ${DOCKER_CONTAINER} bash -c ${shellEscape(command)}`;
29
29
  return execAsync(fullCmd, { maxBuffer: 10 * 1024 * 1024 });
30
30
  }
31
+ async function dockerWriteAtomic(path, content) {
32
+ const b64Content = Buffer.from(content).toString('base64');
33
+ const tmpPath = `${path}.ztc-tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
34
+ await dockerExec(`echo ${shellEscape(b64Content)} | base64 -d > ${shellEscape(tmpPath)}`
35
+ // -L reads the mode of the file a symlink points to; the link's own mode reads as 777 on Linux.
36
+ + ` && { m=$(stat -L -c %a ${shellEscape(path)} 2>/dev/null || stat -L -f %Lp ${shellEscape(path)} 2>/dev/null); if [ -n "$m" ]; then chmod "$(printf "%o" $((0$m & 0777)))" ${shellEscape(tmpPath)}; fi; }`
37
+ + ` && mv -f ${shellEscape(tmpPath)} ${shellEscape(path)}`);
38
+ }
31
39
  const READ_FILE_MAX_BYTES = 10 * 1024 * 1024; // 10 MB hard cap (OOM guard)
32
40
  const READ_FILE_TRUNCATE_BYTES = 80_000; // Truncate output above this (~20K tokens)
33
41
  // The encoded result's ceiling, under the tool runtime's 80,000-character cap with room for the read intent note.
@@ -337,9 +345,7 @@ export const writeFileTool = {
337
345
  // Base64 keeps special chars intact; a random temp path + rename
338
346
  // keeps readers from seeing a partial file.
339
347
  const intended = append ? before + content : content;
340
- const b64Content = Buffer.from(intended).toString('base64');
341
- const tmpPath = `${path}.ztc-tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
342
- await dockerExec(`echo ${shellEscape(b64Content)} | base64 -d > ${shellEscape(tmpPath)} && mv -f ${shellEscape(tmpPath)} ${shellEscape(path)}`);
348
+ await dockerWriteAtomic(path, intended);
343
349
  const { stdout: afterOut } = await dockerExec(`cat ${shellEscape(path)}`);
344
350
  if (afterOut !== intended) {
345
351
  throw new Error(`write_file: verification failed for ${path}: content on disk does not match the intended result`);
@@ -436,9 +442,7 @@ export async function readRawFile(path) {
436
442
  async function writeRawFile(path, content) {
437
443
  if (DOCKER_CONTAINER) {
438
444
  // Temp path + rename so a reader never observes a partially-written file.
439
- const b64Content = Buffer.from(content).toString('base64');
440
- const tmpPath = `${path}.ztc-tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
441
- await dockerExec(`echo ${shellEscape(b64Content)} | base64 -d > ${shellEscape(tmpPath)} && mv -f ${shellEscape(tmpPath)} ${shellEscape(path)}`);
445
+ await dockerWriteAtomic(path, content);
442
446
  return;
443
447
  }
444
448
  await writeFileAtomic(path, content);
@@ -6,6 +6,11 @@ import type { PaneLaunchSpec } from '../../panes/types.js';
6
6
  export { resolveModelAndProvider };
7
7
  export declare function setPaneToolsPendingLaunchCallback(cb: (requestId: string, launchSpec: PaneLaunchSpec) => void): void;
8
8
  export declare function clearPaneToolsPendingLaunchCallback(): void;
9
+ /**
10
+ * Tell the app layer that the create_pane sent as REQUEST_ID opens a pane on LAUNCH_SPEC, as create_ztc_pane does, so
11
+ * the main ZTC records the pane's route for a split, a restore and the mirror's badge. Nothing in a child pane.
12
+ */
13
+ export declare function notePendingPaneLaunch(requestId: string, launchSpec: PaneLaunchSpec): void;
9
14
  export declare function setPaneToolsTuiProcess(tui: PaneCommandTransport): void;
10
15
  export declare function setPaneToolsOwnId(id: number): void;
11
16
  export declare function setPaneToolsExitCallback(cb: () => Promise<void>): void;
@@ -70,6 +75,8 @@ export declare const createTerminalPaneTool: Tool;
70
75
  export declare const createZtcPaneTool: Tool;
71
76
  export declare const readTerminalPaneTool: Tool;
72
77
  export declare const writeTerminalPaneTool: Tool;
78
+ /** What close_terminal_pane answers for pane 0. */
79
+ export declare const MAIN_PANE_STAYS_OPEN: string;
73
80
  export declare const closeTerminalPaneTool: Tool;
74
81
  export declare const listTerminalPanesTool: Tool;
75
82
  export declare const createFeedPaneTool: Tool;
@@ -16,6 +16,8 @@ import { CAPABILITY_PANE_DELIVERY_ACK } from '../../ui/ratatui/protocol.js';
16
16
  import { generateSessionId } from '../../session.js';
17
17
  import { isPaneProvider, resolveModelAndProvider } from '../../panes/model_catalog.js';
18
18
  import { buildZtcPaneLaunchCommand, createZtcLaunchSpec } from '../../panes/ztc_launch.js';
19
+ import { keylessZtcPaneRoute } from '../../panes/worker_route.js';
20
+ import { newPaneRoute } from '../commands/runtime_model.js';
19
21
  import { buildUserSubprocessEnvOverrides } from '../../utils/subprocess_env.js';
20
22
  export { resolveModelAndProvider };
21
23
  // --- Callback-based TUI process access ---
@@ -43,6 +45,13 @@ export function setPaneToolsPendingLaunchCallback(cb) {
43
45
  export function clearPaneToolsPendingLaunchCallback() {
44
46
  pendingPaneLaunchCallback = null;
45
47
  }
48
+ /**
49
+ * Tell the app layer that the create_pane sent as REQUEST_ID opens a pane on LAUNCH_SPEC, as create_ztc_pane does, so
50
+ * the main ZTC records the pane's route for a split, a restore and the mirror's badge. Nothing in a child pane.
51
+ */
52
+ export function notePendingPaneLaunch(requestId, launchSpec) {
53
+ pendingPaneLaunchCallback?.(requestId, launchSpec);
54
+ }
46
55
  function isShellLikeCommand(command) {
47
56
  const normalized = command.split(/[\/]/).pop()?.toLowerCase() || command.toLowerCase();
48
57
  return normalized === 'bash'
@@ -756,17 +765,22 @@ export const createZtcPaneTool = {
756
765
  model = resolved.model;
757
766
  provider = resolved.provider;
758
767
  }
759
- // Validate API key exists for requested provider
768
+ // A provider the pane reaches on a key here needs that key; one it reaches through Zerg Router needs Router's.
760
769
  if (provider) {
761
- const { configStore } = await import('../../config.js');
762
770
  // A child on a provider this run's own --provider didn't choose would choose it for a waiting profile.
763
771
  if (configStore.routeAwaitingChoice(provider) !== undefined)
764
772
  return `Error: ${ROUTE_AWAITS_A_CHOICE}`;
765
- const key = configStore.getApiKey(provider);
766
- if (!key) {
773
+ const started = configStore.getNewPaneRoute();
774
+ const routed = newPaneRoute(configStore, { ...started, provider, model: model ?? started.model }).routed;
775
+ if (!routed && !configStore.getApiKey(provider)) {
767
776
  return `Error: No API key configured for provider "${provider}". Set it with /config key ${provider} <key> or the appropriate environment variable.`;
768
777
  }
769
778
  }
779
+ // A route Zerg Router has no key for fails on its first message, the route new panes start on included: it is
780
+ // refused before anything opens, with where the key goes (Router asked once more first).
781
+ const keyless = await keylessZtcPaneRoute(provider, model);
782
+ if (keyless)
783
+ return `Error: No ZTC pane was opened: ${provider || model ? '' : 'new ZTC panes start on Zerg Router. '}${keyless}`;
770
784
  // Inject --provider/--model into child args
771
785
  const modelArgs = [];
772
786
  if (provider)
@@ -1048,10 +1062,13 @@ For raw keystrokes set submit=false; input bytes are preserved and Enter is \\r
1048
1062
  return `Input delivered to pane ${paneId}${shouldSubmit ? ' (submitted)' : ' (raw)'}. Delivery is not command completion; read the pane to inspect output.`;
1049
1063
  },
1050
1064
  };
1065
+ /** What close_terminal_pane answers for pane 0. */
1066
+ export const MAIN_PANE_STAYS_OPEN = 'Error: Pane 0 is ZTC\'s Main, which stays open while ZTC runs, so close_terminal_pane '
1067
+ + 'can\'t close it. The person quits ZTC to close it.';
1051
1068
  export const closeTerminalPaneTool = {
1052
1069
  definition: {
1053
1070
  name: 'close_terminal_pane',
1054
- description: `Close a terminal pane and kill its process. The pane will be removed from the zmux layout. You can close your own pane (self-close) — zmux will clean it up.`,
1071
+ description: `Close a terminal pane and kill its process. The pane will be removed from the zmux layout. You can close your own pane (self-close) — zmux will clean it up. Pane 0, ZTC's Main, stays open.`,
1055
1072
  parameters: {
1056
1073
  type: 'object',
1057
1074
  properties: {
@@ -1071,15 +1088,23 @@ export const closeTerminalPaneTool = {
1071
1088
  if (isNaN(paneId)) {
1072
1089
  return 'Error: pane_id must be a number.';
1073
1090
  }
1091
+ // Pane 0 is ZTC's Main (the desktop app's owner surface, zmux's ZTC pane), which stays open while ZTC runs, as zmux
1092
+ // and the browser mirror keep it: not closed, and not quit from by its own agent either.
1093
+ if (paneId === 0)
1094
+ return MAIN_PANE_STAYS_OPEN;
1074
1095
  // Self-close: exit this ZTC process; zmux will detect exit and remove the pane
1075
1096
  if (ownPaneId !== null && paneId === ownPaneId && exitCallback) {
1076
1097
  void exitCallback();
1077
1098
  return `Closing own pane ${paneId}...`;
1078
1099
  }
1079
- const eventPromise = waitForEvent(tuiProcessRef, (e) => (e.type === 'pane_closed' && e.pane_id === paneId) || e.type === 'error', 10000);
1100
+ // Its own pane's close, or a refusal tied to this request (isPaneRefusalFor): never another request's refusal, which
1101
+ // other pane work in flight (an agent opening panes, a child's request through the relay) can bring first.
1102
+ const requestId = `close-pane-${randomUUID()}`;
1103
+ const eventPromise = waitForEvent(tuiProcessRef, (e) => (e.type === 'pane_closed' && e.pane_id === paneId) || isPaneRefusalFor(e, requestId), 10000);
1080
1104
  const sent = tuiProcessRef.send({
1081
1105
  type: 'close_pane',
1082
1106
  pane_id: paneId,
1107
+ request_id: requestId,
1083
1108
  });
1084
1109
  if (!sent) {
1085
1110
  eventPromise.catch(() => { }); // prevent unhandled rejection from dangling timeout
@@ -1,5 +1,6 @@
1
1
  import { Tool } from './types.js';
2
2
  import { type SlashUsage } from '../commands/usage_spec.js';
3
+ import type { ToolCapability } from '../runtime/capabilities.js';
3
4
  /**
4
5
  * ZTC Command Tool — drives slash commands the same way the user types them.
5
6
  *
@@ -22,6 +23,11 @@ export interface CommandCatalogEntry {
22
23
  /** "global" or a mode name. */
23
24
  scope: 'global' | string;
24
25
  agentRunnable: boolean;
26
+ /**
27
+ * What running the command does that the agent's permission profile governs (Command.agentCapabilities): the tool
28
+ * runtime checks them as the ztc_command call's own (ztcCommandCapabilities).
29
+ */
30
+ capabilities?: readonly ToolCapability[];
25
31
  }
26
32
  export interface CommandCatalogProvider {
27
33
  getEntries: () => CommandCatalogEntry[];
@@ -36,6 +42,12 @@ export declare function clearZtcCommandExecutor(): void;
36
42
  */
37
43
  export declare function setZtcCommandCatalog(provider: CommandCatalogProvider): void;
38
44
  export declare function clearZtcCommandCatalog(): void;
45
+ /**
46
+ * What a ztc_command call's command does that the agent's permission profile governs, which the tool runtime checks as
47
+ * the call's own capabilities: /claude and /codex start a program that runs commands (shell_exec), so a profile refuses
48
+ * them, or asks before them, as it does a shell. None for a command the agent can't run, which execute refuses.
49
+ */
50
+ export declare function ztcCommandCapabilities(args: Record<string, unknown>): ToolCapability[];
39
51
  /** Group entries by scope (global first, modes alphabetical) then by category. */
40
52
  export declare function buildZtcCommandDescription(provider: CommandCatalogProvider): string;
41
53
  export declare const ztcCommandTool: Tool;