@zergai/ztc 0.26.2-dev.202611210149 → 0.26.4-dev.202611231953

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 (275) hide show
  1. package/README.md +590 -28
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/zmux-linux-x64 +0 -0
  4. package/bin/ztc-audio-darwin-arm64 +0 -0
  5. package/bin/ztc-capture-darwin-arm64 +0 -0
  6. package/bin/ztc-tui-darwin-arm64 +0 -0
  7. package/bin/ztc-tui-linux-x64 +0 -0
  8. package/bin/zterm-darwin-arm64 +2 -2
  9. package/dist/App.js +18 -1
  10. package/dist/agent/agent.d.ts +25 -1
  11. package/dist/agent/agent.js +26 -1
  12. package/dist/agent/attached_images.d.ts +58 -0
  13. package/dist/agent/attached_images.js +145 -0
  14. package/dist/agent/backends/anthropic.d.ts +14 -0
  15. package/dist/agent/backends/anthropic.js +49 -2
  16. package/dist/agent/backends/codex_app_server.d.ts +3 -1
  17. package/dist/agent/backends/codex_app_server.js +9 -6
  18. package/dist/agent/backends/codex_auth.js +3 -0
  19. package/dist/agent/backends/gemini.js +3 -0
  20. package/dist/agent/backends/host_effort_policy.js +14 -2
  21. package/dist/agent/backends/http_error.d.ts +17 -0
  22. package/dist/agent/backends/http_error.js +50 -1
  23. package/dist/agent/backends/index.js +2 -1
  24. package/dist/agent/backends/model_redirect.d.ts +47 -0
  25. package/dist/agent/backends/model_redirect.js +97 -0
  26. package/dist/agent/backends/openai_compatible.js +5 -0
  27. package/dist/agent/backends/openai_responses.d.ts +9 -1
  28. package/dist/agent/backends/openai_responses.js +21 -12
  29. package/dist/agent/backends/prompt_cache.d.ts +8 -0
  30. package/dist/agent/backends/prompt_cache.js +10 -0
  31. package/dist/agent/backends/provider_ids.d.ts +1 -1
  32. package/dist/agent/backends/provider_ids.js +1 -1
  33. package/dist/agent/backends/types.d.ts +8 -0
  34. package/dist/agent/backends/zerg-api.js +5 -1
  35. package/dist/agent/backends/zrouter_stream.d.ts +75 -9
  36. package/dist/agent/backends/zrouter_stream.js +250 -49
  37. package/dist/agent/commands/config.js +51 -4
  38. package/dist/agent/commands/connect.js +20 -0
  39. package/dist/agent/commands/credential_status.js +5 -3
  40. package/dist/agent/commands/debug.js +3 -0
  41. package/dist/agent/commands/diff.js +9 -5
  42. package/dist/agent/commands/emulation.js +7 -1
  43. package/dist/agent/commands/inbox.js +4 -3
  44. package/dist/agent/commands/mcp.js +3 -0
  45. package/dist/agent/commands/models.js +20 -3
  46. package/dist/agent/commands/permissions.js +16 -2
  47. package/dist/agent/commands/provider_selection.js +13 -6
  48. package/dist/agent/commands/settings.js +15 -4
  49. package/dist/agent/commands/status.js +23 -1
  50. package/dist/agent/commands/types.d.ts +34 -3
  51. package/dist/agent/commands/update.d.ts +2 -1
  52. package/dist/agent/commands/update.js +8 -3
  53. package/dist/agent/commands/zerg.d.ts +6 -0
  54. package/dist/agent/commands/zerg.js +152 -28
  55. package/dist/agent/commands/ztc_pane.js +8 -5
  56. package/dist/agent/factory.js +22 -4
  57. package/dist/agent/request_encoder.js +11 -2
  58. package/dist/agent/runtime/command_jobs.js +16 -1
  59. package/dist/agent/runtime/command_panes.js +4 -1
  60. package/dist/agent/runtime/execution_context.d.ts +8 -1
  61. package/dist/agent/runtime/execution_context.js +8 -2
  62. package/dist/agent/runtime/policy.d.ts +66 -5
  63. package/dist/agent/runtime/policy.js +161 -33
  64. package/dist/agent/runtime/remote_broker_transport.d.ts +7 -0
  65. package/dist/agent/runtime/remote_broker_transport.js +33 -3
  66. package/dist/agent/runtime/remote_resource_errors.d.ts +7 -0
  67. package/dist/agent/runtime/remote_resource_errors.js +10 -0
  68. package/dist/agent/runtime/remote_resources.d.ts +1 -1
  69. package/dist/agent/runtime/remote_resources.js +7 -3
  70. package/dist/agent/runtime/source_verification.js +15 -12
  71. package/dist/agent/runtime/tool_runtime.js +165 -58
  72. package/dist/agent/runtime/verifier_capture.d.ts +1 -1
  73. package/dist/agent/runtime/verifier_capture.js +6 -0
  74. package/dist/agent/runtime/work_base.js +46 -14
  75. package/dist/agent/tools/adaptation.js +29 -12
  76. package/dist/agent/tools/apply_patch.js +62 -5
  77. package/dist/agent/tools/background.js +2 -0
  78. package/dist/agent/tools/benchmark_cpu.js +2 -0
  79. package/dist/agent/tools/bus_message.d.ts +4 -2
  80. package/dist/agent/tools/bus_message.js +21 -3
  81. package/dist/agent/tools/delegate.js +2 -0
  82. package/dist/agent/tools/file.d.ts +12 -1
  83. package/dist/agent/tools/file.js +92 -11
  84. package/dist/agent/tools/lsp.d.ts +12 -0
  85. package/dist/agent/tools/lsp.js +61 -5
  86. package/dist/agent/tools/pane.js +20 -45
  87. package/dist/agent/tools/project_context.js +5 -2
  88. package/dist/agent/tools/routine.js +20 -4
  89. package/dist/agent/tools/screenshot.d.ts +8 -0
  90. package/dist/agent/tools/screenshot.js +39 -25
  91. package/dist/agent/tools/search.js +31 -3
  92. package/dist/agent/tools/shell.js +7 -1
  93. package/dist/agent/tools/supervision.js +6 -0
  94. package/dist/agent/tools/types.d.ts +18 -0
  95. package/dist/agent/tools/zerg.js +15 -19
  96. package/dist/agent/tools/ztc_command.d.ts +15 -4
  97. package/dist/agent/tools/ztc_command.js +48 -34
  98. package/dist/app/agent_runner.js +8 -6
  99. package/dist/app/conversation_compaction.d.ts +6 -3
  100. package/dist/app/conversation_compaction.js +6 -3
  101. package/dist/app/tool_callbacks.js +1 -0
  102. package/dist/audio/sfx.js +6 -0
  103. package/dist/batch/worktree.js +22 -10
  104. package/dist/board/client.js +2 -1
  105. package/dist/cli_main.d.ts +1 -0
  106. package/dist/cli_main.js +141 -45
  107. package/dist/cli_ratatui.d.ts +49 -4
  108. package/dist/cli_ratatui.js +355 -79
  109. package/dist/conductor_branch.js +4 -1
  110. package/dist/config/host_credentials.d.ts +157 -0
  111. package/dist/config/host_credentials.js +589 -0
  112. package/dist/config/model_pin.d.ts +111 -0
  113. package/dist/config/model_pin.js +182 -0
  114. package/dist/config/own_state_files.d.ts +35 -0
  115. package/dist/config/own_state_files.js +161 -0
  116. package/dist/config/permission_pin.d.ts +148 -0
  117. package/dist/config/permission_pin.js +203 -0
  118. package/dist/config/permissions.d.ts +9 -2
  119. package/dist/config/permissions.js +14 -3
  120. package/dist/config/platform_login.d.ts +72 -0
  121. package/dist/config/platform_login.js +111 -0
  122. package/dist/config/profile_limits.d.ts +34 -0
  123. package/dist/config/profile_limits.js +66 -0
  124. package/dist/config/provider_api_key_env.js +3 -2
  125. package/dist/config/provider_models.d.ts +6 -1
  126. package/dist/config/provider_models.js +38 -11
  127. package/dist/config/repo_config.d.ts +22 -0
  128. package/dist/config/repo_config.js +77 -3
  129. package/dist/config/router_runtime_grant.d.ts +53 -0
  130. package/dist/config/router_runtime_grant.js +131 -0
  131. package/dist/config/settings_merge.d.ts +22 -0
  132. package/dist/config/settings_merge.js +75 -0
  133. package/dist/config/types.d.ts +8 -0
  134. package/dist/config.d.ts +334 -4
  135. package/dist/config.js +1024 -41
  136. package/dist/context/project_intelligence.d.ts +11 -2
  137. package/dist/context/project_intelligence.js +38 -15
  138. package/dist/desktop/daily/desktop_wiring.js +8 -6
  139. package/dist/desktop/daily/native_pane_launcher.js +2 -1
  140. package/dist/desktop/daily/native_tool.d.ts +1 -1
  141. package/dist/desktop/daily/native_tool.js +4 -3
  142. package/dist/desktop/daily/process_identity.js +10 -2
  143. package/dist/desktop/daily/source_baseline.js +4 -3
  144. package/dist/diagnostics/native_terminal_benchmark.js +3 -2
  145. package/dist/diagnostics/session_export.js +27 -14
  146. package/dist/embedded/anempa_runtime.js +3 -3
  147. package/dist/embedded/gameboy_runtime.js +5 -4
  148. package/dist/embedded/zergpod_runtime.js +5 -4
  149. package/dist/emulation/catalog.js +6 -1
  150. package/dist/emulation/tool_adapters.js +13 -3
  151. package/dist/environment/store.js +5 -4
  152. package/dist/extension_discovery.d.ts +12 -2
  153. package/dist/extension_discovery.js +52 -7
  154. package/dist/headless.d.ts +8 -0
  155. package/dist/headless.js +52 -13
  156. package/dist/headless_cli.js +16 -1
  157. package/dist/headless_workflow_trigger.js +1 -1
  158. package/dist/hooks/dispatcher.d.ts +8 -0
  159. package/dist/hooks/dispatcher.js +22 -2
  160. package/dist/hooks/lifecycle.d.ts +6 -0
  161. package/dist/hooks/lifecycle.js +1 -0
  162. package/dist/hooks/program_files.d.ts +10 -0
  163. package/dist/hooks/program_files.js +175 -0
  164. package/dist/hooks/runner.d.ts +11 -1
  165. package/dist/hooks/runner.js +112 -11
  166. package/dist/hooks/types.d.ts +2 -0
  167. package/dist/host_credentials_startup.d.ts +6 -0
  168. package/dist/host_credentials_startup.js +17 -0
  169. package/dist/instance_registry.d.ts +6 -2
  170. package/dist/instance_registry.js +9 -15
  171. package/dist/intake/format.d.ts +6 -0
  172. package/dist/intake/format.js +9 -0
  173. package/dist/intake/notifications.js +2 -1
  174. package/dist/lsp/manager.d.ts +1 -1
  175. package/dist/lsp/manager.js +4 -5
  176. package/dist/mcp/client.d.ts +2 -0
  177. package/dist/mcp/client.js +116 -18
  178. package/dist/mcp/registry.d.ts +12 -0
  179. package/dist/mcp/registry.js +15 -1
  180. package/dist/modes/handlers.js +14 -5
  181. package/dist/panes/agent_cli.d.ts +23 -1
  182. package/dist/panes/agent_cli.js +96 -1
  183. package/dist/panes/agent_panes.d.ts +27 -4
  184. package/dist/panes/agent_panes.js +73 -11
  185. package/dist/panes/editor_program.d.ts +8 -0
  186. package/dist/panes/editor_program.js +25 -0
  187. package/dist/panes/motsi.d.ts +11 -1
  188. package/dist/panes/motsi.js +14 -1
  189. package/dist/panes/pane_registry.d.ts +28 -1
  190. package/dist/panes/pane_registry.js +25 -0
  191. package/dist/panes/worker_route.js +5 -3
  192. package/dist/panes/ztc_launch.d.ts +8 -0
  193. package/dist/panes/ztc_launch.js +26 -1
  194. package/dist/profile_baseline.js +2 -0
  195. package/dist/router_auth.d.ts +8 -3
  196. package/dist/router_auth.js +34 -2
  197. package/dist/runtime_info.js +56 -38
  198. package/dist/session.js +12 -2
  199. package/dist/shannon/runtime.js +13 -1
  200. package/dist/simulation/domains/loader.d.ts +2 -1
  201. package/dist/simulation/domains/loader.js +19 -2
  202. package/dist/simulation/living/context.d.ts +8 -8
  203. package/dist/simulation/living/types.d.ts +2 -2
  204. package/dist/simulation/memory/embedding.d.ts +2 -1
  205. package/dist/simulation/memory/embedding.js +25 -6
  206. package/dist/terminal_attach.js +2 -1
  207. package/dist/types.d.ts +21 -0
  208. package/dist/ui/ratatui/headless_pane_manager.d.ts +12 -6
  209. package/dist/ui/ratatui/headless_pane_manager.js +65 -21
  210. package/dist/ui/ratatui/ipc_path.d.ts +41 -2
  211. package/dist/ui/ratatui/ipc_path.js +164 -5
  212. package/dist/ui/ratatui/pane_credential_broker.d.ts +17 -4
  213. package/dist/ui/ratatui/pane_credential_broker.js +23 -5
  214. package/dist/ui/ratatui/pane_relay.d.ts +74 -0
  215. package/dist/ui/ratatui/pane_relay.js +188 -13
  216. package/dist/ui/ratatui/process.d.ts +15 -1
  217. package/dist/ui/ratatui/process.js +129 -163
  218. package/dist/ui/ratatui/protocol.d.ts +11 -1
  219. package/dist/ui/ratatui/protocol.js +6 -0
  220. package/dist/ui/ratatui/ztc_launch_trust.d.ts +87 -0
  221. package/dist/ui/ratatui/ztc_launch_trust.js +249 -0
  222. package/dist/utils/admitted_open.d.ts +40 -0
  223. package/dist/utils/admitted_open.js +111 -0
  224. package/dist/utils/clipboard.js +2 -1
  225. package/dist/utils/computer_native.js +12 -56
  226. package/dist/utils/dictation.js +15 -12
  227. package/dist/utils/dictation_native.js +17 -60
  228. package/dist/utils/git_probe_options.d.ts +28 -0
  229. package/dist/utils/git_probe_options.js +30 -0
  230. package/dist/utils/git_program_files.d.ts +145 -0
  231. package/dist/utils/git_program_files.js +1282 -0
  232. package/dist/utils/git_repository_programs.d.ts +13 -0
  233. package/dist/utils/git_repository_programs.js +38 -0
  234. package/dist/utils/host_shell.js +2 -1
  235. package/dist/utils/idle_compaction.js +8 -1
  236. package/dist/utils/image_fit.d.ts +4 -1
  237. package/dist/utils/image_fit.js +6 -2
  238. package/dist/utils/image_preview.js +3 -2
  239. package/dist/utils/mirror_media.d.ts +22 -4
  240. package/dist/utils/mirror_media.js +87 -86
  241. package/dist/utils/ml_native.js +11 -56
  242. package/dist/utils/native_install.d.ts +55 -0
  243. package/dist/utils/native_install.js +107 -0
  244. package/dist/utils/open_url.js +2 -0
  245. package/dist/utils/process_end.d.ts +16 -0
  246. package/dist/utils/process_end.js +73 -0
  247. package/dist/utils/router_catalog.js +9 -2
  248. package/dist/utils/sandbox.d.ts +64 -1
  249. package/dist/utils/sandbox.js +397 -89
  250. package/dist/utils/shell.js +31 -12
  251. package/dist/utils/subprocess_env.d.ts +218 -2
  252. package/dist/utils/subprocess_env.js +429 -11
  253. package/dist/utils/system_ps.d.ts +5 -0
  254. package/dist/utils/system_ps.js +30 -0
  255. package/dist/utils/tts.js +5 -0
  256. package/dist/utils/tts_native.js +13 -60
  257. package/dist/utils/zlicky_overlay.js +17 -50
  258. package/dist/utils/ztc_own_state.d.ts +58 -0
  259. package/dist/utils/ztc_own_state.js +236 -0
  260. package/dist/web/mirror_authenticator.d.ts +67 -6
  261. package/dist/web/mirror_authenticator.js +131 -22
  262. package/dist/web/mirror_stream.d.ts +54 -10
  263. package/dist/web/mirror_stream.js +379 -92
  264. package/dist/web/observer_query_redaction.js +53 -13
  265. package/dist/web/observer_secret_redaction.d.ts +59 -0
  266. package/dist/web/observer_secret_redaction.js +714 -0
  267. package/dist/web/pane_credentials.d.ts +20 -2
  268. package/dist/web/pane_credentials.js +58 -5
  269. package/dist/worker/executor.js +3 -1
  270. package/dist/workspace_collision.js +19 -15
  271. package/dist/zerg/local_zerg_launches.d.ts +27 -0
  272. package/dist/zerg/local_zerg_launches.js +198 -0
  273. package/dist/zlm-embed.mjs +6257 -2791
  274. package/npm-shrinkwrap.json +1 -1
  275. package/package.json +42 -15
@@ -4,7 +4,8 @@ import { openRouterRequestRouting } from '../../utils/openrouter_request.js';
4
4
  import { recordServed } from '../../utils/openrouter_served.js';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { measureResponse, measureStream } from './request_metrics.js';
7
- import { BackendHttpError, readHttpErrorBody, retryAfterDelayMs } from './http_error.js';
7
+ import { MODEL_REQUEST_REDIRECT, refuseModelRedirect, refuseRouterRedirect } from './model_redirect.js';
8
+ import { BackendHttpError, holdsCredential, readHttpErrorBody, retryAfterDelayMs } from './http_error.js';
8
9
  import { RequestRefusedError } from './types.js';
9
10
  import { parseSSEEvents } from './sse.js';
10
11
  import { buildOpenAIMessages, buildOpenAIToolDefs, refuseMediaForTextModel } from './openai_format.js';
@@ -20,11 +21,15 @@ import { OpenAIResponsesBackend } from './openai_responses.js';
20
21
  import { endingRouterRefusal, readRouterRefusal, RouterRefusalError } from './router_refusal.js';
21
22
  import { rejectedRouterKeyMessage, routerProviderLabel } from './router_keys.js';
22
23
  import { ROUTER_SIGN_IN_REJECTED } from '../../router_auth.js';
24
+ import { isHostRouterGrant, ROUTER_RUNTIME_GRANT_REFUSED } from '../../config/router_runtime_grant.js';
25
+ import { hostCredential, hostEnvironmentValue } from '../../config/host_credentials.js';
23
26
  import { ROUTER_REFUSAL_RETRY_MS, routerAccount, routerRefusalGate } from './router_gate.js';
24
27
  import { countRouterRequests } from './router_requests.js';
25
28
  import { conversationPin } from './conversation_pin.js';
26
29
  import { requiredRouterModel } from '../../config/router_required.js';
27
30
  import { applyHostEffortPolicy } from './host_effort_policy.js';
31
+ import { attachedImageTypesOutside, carriesAttachedImages, routeName, routerPricedImageTypes, withheldImageNote, withheldImagesNotice, withoutAttachedImages } from '../attached_images.js';
32
+ import { promptCacheTtl } from './prompt_cache.js';
28
33
  const ZROUTER_HEADERS_TIMEOUT_MS = 90_000;
29
34
  // A process session is descriptive telemetry, never a registered machine identity.
30
35
  const routerClientSession = randomUUID();
@@ -54,6 +59,14 @@ function toolImageRefusal(error) {
54
59
  // again.
55
60
  return failure?.status === 400 && refusesImages(failure.body) ? 'HTTP 400' : undefined;
56
61
  }
62
+ /**
63
+ * Whether ERROR is Router refusing a request as one it can't price under a spending limit: what an image the person
64
+ * attached causes for any model Router can't bound an image's cost for (agent/attached_images.ts). Any other refusal,
65
+ * and any other failure, is never put down to their images.
66
+ */
67
+ function unpricedRefusal(error) {
68
+ return error instanceof RouterRefusalError && error.refusal.code === 'router_usage_unpriced';
69
+ }
57
70
  /** What Router says when a request's images are what a model or its Atlas service takes none of, or no more of. */
58
71
  const IMAGE_REFUSAL_MESSAGES = new Set(['Model does not support images', 'Atlas images must be bounded inline image data']);
59
72
  /** Whether BODY is Router refusing a request's images, in its H3 envelope or the Responses route's. */
@@ -85,6 +98,30 @@ function toolImagesRefusal(key) {
85
98
  const refused = toolImagesRefused.get(key);
86
99
  return refused !== undefined && Date.now() - refused.at < ROUTER_REFUSAL_RETRY_MS ? refused.reason : undefined;
87
100
  }
101
+ /**
102
+ * What Router answers a service-account key's request carrying a field the account's allowlist doesn't name
103
+ * (zapps/zergrouter/server/lib/service-accounts.ts, serviceRequestQuote): neither `prompt_cache` nor the `route` that
104
+ * goes with it on a request with no plan of its own is one it names.
105
+ */
106
+ const UNSUPPORTED_SERVICE_OPTION = 'Unsupported service inference option';
107
+ /** Whether ERROR is Router's 400 for a field of the request a service-account key doesn't take, in any of its envelopes. */
108
+ function unsupportedServiceOption(error) {
109
+ if (!(error instanceof BackendHttpError) || error.status !== 400)
110
+ return false;
111
+ try {
112
+ const parsed = JSON.parse(error.body);
113
+ return [parsed?.statusMessage, parsed?.message, parsed?.error?.message].includes(UNSUPPORTED_SERVICE_OPTION);
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ /**
120
+ * The Routers and accounts that refused `prompt_cache` (a service-account key's allowlist doesn't take it): no request to
121
+ * them carries it again in this process, from any backend. Kept beside the backends, since a host effort policy builds
122
+ * one per turn.
123
+ */
124
+ const promptCacheRefused = new Set();
88
125
  /**
89
126
  * Whether a Router chat model takes images: its measured or documented contract, which outranks a catalog that read
90
127
  * provider metadata and fills its gaps (Router left every Claude and Gemini model unmarked and marked Morph's DeepSeek
@@ -253,6 +290,10 @@ export class ZRouterStreamBackend {
253
290
  const { provider, providerLabel, credentialsUrl } = this.refusalRequest();
254
291
  return { provider, label: providerLabel, credentialsUrl };
255
292
  }
293
+ /** Whether this backend's requests go with the host's Router runtime grant, whose refusal is worded as the grant's. */
294
+ onHostGrant() {
295
+ return !this.authTokenProvider && !this.routerSignIn && isHostRouterGrant(this.apiKey);
296
+ }
256
297
  /** What a refusal is worded with: this backend's provider, by the name Router's catalog gives it, and its link. */
257
298
  refusalRequest() {
258
299
  const providerLabel = routerProviderLabel(this.catalog, this.provider) ?? this.providerLabel;
@@ -273,7 +314,7 @@ export class ZRouterStreamBackend {
273
314
  allowsRequestRetryAfterFailure(request) {
274
315
  // A prepared turn holds its policy snapshot, so a retry resends the same route. Only an unprepared backend
275
316
  // would read the policy again mid-request.
276
- if (process.env.ZTC_EFFORT_POLICY_URL && !this.hostPolicyPrepared)
317
+ if (hostEnvironmentValue('ZTC_EFFORT_POLICY_URL') && !this.hostPolicyPrepared)
277
318
  return false;
278
319
  return !this.usesNativeResponses(request);
279
320
  }
@@ -343,11 +384,13 @@ export class ZRouterStreamBackend {
343
384
  return;
344
385
  const headers = await this.buildHeaders(request);
345
386
  // The id Router runs the turn under: a turn sent again without its tool images or its order's fields went under a
346
- // new one (renewTurn).
347
- const response = await fetch(`${this.proxyUrl}/v1/chat/turns/cancel`, {
387
+ // new one (renewTurn). The cancel goes to this Router alone: a redirect is not followed.
388
+ const url = `${this.proxyUrl}/v1/chat/turns/cancel`;
389
+ const response = await fetch(url, {
348
390
  method: 'POST', headers: { ...headers, 'X-Zerg-Turn-ID': renewedTurns.get(request.transportTurnId) ?? request.transportTurnId },
349
- signal: AbortSignal.timeout(10_000),
391
+ signal: AbortSignal.timeout(10_000), redirect: MODEL_REQUEST_REDIRECT,
350
392
  });
393
+ await refuseRouterRedirect(response, url, 'this turn\'s cancel', headers);
351
394
  await response.body?.cancel();
352
395
  }
353
396
  /** Logs who served a request for the model, and keeps its endpoint as the conversation's sticky provider. */
@@ -404,6 +447,51 @@ export class ZRouterStreamBackend {
404
447
  const plan = request.routePlan;
405
448
  return plan && plan.allow_fallbacks !== false ? plan.fallbacks.filter(Boolean) : [];
406
449
  }
450
+ /**
451
+ * The providers REQUEST's route may reach, by name: this backend's, then each of its plan's fallbacks' (`provider/model`,
452
+ * or a model of this backend's provider), since Router sends each of them the same body.
453
+ */
454
+ routeProviders(request) {
455
+ return [this.provider, ...this.planFallbacks(request).map(fallback => fallback.includes('/') ? fallback.split('/')[0] : this.provider)];
456
+ }
457
+ /** What promptCacheRefused knows REQUEST's Router and account by. */
458
+ promptCacheKey(request) {
459
+ const { route, account } = this.gateTarget(request);
460
+ return JSON.stringify([route, account]);
461
+ }
462
+ /**
463
+ * Whether REQUEST's chat body asks Router for no prompt cache (`prompt_cache: false`): when ZTC_PROMPT_CACHE_TTL is off
464
+ * (promptCacheTtl, as AnthropicBackend reads it, whose requests then carry no cache_control), for a route whose every
465
+ * provider is Anthropic. Router's translation to Anthropic's Messages API caches a system prompt of 1024 characters or
466
+ * more unless the body says so, and records a request carrying cache_control without a price, which a dollar limit
467
+ * counts at its whole hold. Router hands the body to every other provider's API as it came, a field that API doesn't
468
+ * know included, so a body that asks with no route plan of its own also says it has no fallbacks (buildOpenAIBody):
469
+ * Router would take the deck's or the workspace's stored plan, which ZTC can't see. Never on a Router and account
470
+ * that refused the field (refusedPromptCache).
471
+ */
472
+ asksNoPromptCache(request) {
473
+ return promptCacheTtl() === 'off' && this.routeProviders(request).every(provider => provider === 'anthropic')
474
+ && !promptCacheRefused.has(this.promptCacheKey(request));
475
+ }
476
+ /**
477
+ * Whether Router refused REQUEST, whose body asked for no prompt cache, for a field its account doesn't take, as a
478
+ * service-account key's allowlist refuses prompt_cache and the route that goes with it: then that Router and account
479
+ * get the field no more (promptCacheRefused), which the runtime diagnostics say once, and the caller sends the request
480
+ * once more without it, and so without that route (buildOpenAIBody).
481
+ */
482
+ refusedPromptCache(request, error) {
483
+ if (!unsupportedServiceOption(error))
484
+ return false;
485
+ const key = this.promptCacheKey(request);
486
+ if (!promptCacheRefused.has(key)) {
487
+ promptCacheRefused.add(key);
488
+ runtimeDiag('warn', `[ztc] Zerg Router at ${this.proxyUrl} refused a request asking it for no prompt cache (prompt_cache: false, `
489
+ + `sent under ZTC_PROMPT_CACHE_TTL=off) with 400 "${UNSUPPORTED_SERVICE_OPTION}", as a service-account key's allowlist does, `
490
+ + 'so ZTC sent it again without the field and sends that Router none on this key for the rest of the run. Router then caches '
491
+ + 'a Claude model\'s long system prompt, as it does by default.');
492
+ }
493
+ return true;
494
+ }
407
495
  /**
408
496
  * What toolImagesRefused knows this request's route, account, provider and model by, and its plan's fallbacks: Router
409
497
  * doesn't say which model of a plan refused, so a refusal on a plan is that plan's, not its model's alone.
@@ -453,11 +541,73 @@ export class ZRouterStreamBackend {
453
541
  this.tellToolImagesRefused(request, key);
454
542
  return true;
455
543
  }
544
+ /**
545
+ * The media types of an image Router may price on REQUEST's route under a spending limit: what it prices for this
546
+ * route's provider and for each provider its plan falls back to, since Router sends each the same body.
547
+ */
548
+ pricedImageTypes(request) {
549
+ const providers = this.routeProviders(request);
550
+ return routerPricedImageTypes(this.provider).filter(type => providers.every(provider => routerPricedImageTypes(provider).includes(type)));
551
+ }
552
+ /**
553
+ * REQUEST to send again when Router refused it as one it can't price under a spending limit while it carried images
554
+ * the person attached: the same request with a note in place of each of theirs of a format Router never prices on the
555
+ * route (pricedImageTypes: all but a PNG, JPEG or WebP for OpenAI's models, every image for another provider's), or of
556
+ * every one of theirs when ALL, as a turn of its own (Router keeps a turn's body under its id), and what it withheld.
557
+ * Every Zerg Router route does this: a host's (its Router runtime grant, as ZergCloud's resident runs, or a host's own
558
+ * credential provider) and the person's own key or sign-in, as desktop and npm owners run ZTC. Undefined for any
559
+ * other failure, or a request without such images.
560
+ */
561
+ withoutRefusedAttachedImages(request, error, all = false) {
562
+ if (!unpricedRefusal(error) || !carriesAttachedImages(request.messages))
563
+ return undefined;
564
+ const keep = all ? [] : this.pricedImageTypes(request);
565
+ const outside = attachedImageTypesOutside(request.messages, keep);
566
+ if (outside.length === 0)
567
+ return undefined;
568
+ // The formats are named when Router may still price the person's other images on this route.
569
+ const formats = keep.length > 0 ? outside : undefined;
570
+ const note = withheldImageNote(this.provider, request.model, formats);
571
+ runtimeDiag('warn', `[ztc] Zerg Router refused a request to ${routeName(this.provider, request.model)} that carried `
572
+ + `${formats ? `${outside.join(', ')} images` : 'images'} the person attached (router_usage_unpriced), so ZTC sent it again without them.`);
573
+ return { request: renewTurn({ ...request, messages: withoutAttachedImages(request.messages, note, keep) }),
574
+ withheld: { note, keep, ...(formats ? { formats } : {}) } };
575
+ }
576
+ /**
577
+ * Router took REQUEST, sent again without the images the person attached that WITHHELD names: the transcript says
578
+ * why, and the caller puts its note in their place in its conversation, so no later request carries them again.
579
+ */
580
+ tellAttachedImagesWithheld(request, withheld) {
581
+ request.onNotice?.(withheldImagesNotice(this.provider, request.model, withheld.formats));
582
+ request.onAttachedImagesWithheld?.(withheld.note, withheld.keep);
583
+ }
584
+ /**
585
+ * What to send once more after Router refused REQUEST with ERROR, before any output, when it carried tool images if
586
+ * CARRIES_TOOL_IMAGES (and went WITHOUT_TOOL_IMAGES, WITHHELD the person's images already), and asked for no prompt
587
+ * cache if ASKS_NO_PROMPT_CACHE: without that field when Router refused it (refusedPromptCache), as a turn of its own,
588
+ * whose body is built again; else first without the person's images in a format Router never prices on the route,
589
+ * which Router can't price whatever else goes, so a tool's images that it does price aren't held off the route for
590
+ * them; then without the tool images, for what they can cause (refusedForToolImages, which holds them off the route);
591
+ * then without every image the person attached. Undefined when none applies, and the refusal stands.
592
+ */
593
+ afterRefusal(request, error, carriesToolImages, withoutToolImages, withheld, asksNoPromptCache = false) {
594
+ if (asksNoPromptCache && this.refusedPromptCache(request, error))
595
+ return { request: renewTurn(request), withoutToolImages, withheld };
596
+ const formats = this.withoutRefusedAttachedImages(request, error);
597
+ if (formats)
598
+ return { request: formats.request, withoutToolImages, withheld: formats.withheld };
599
+ if (carriesToolImages && this.refusedForToolImages(request, error))
600
+ return { request: renewTurn(request), withoutToolImages: true, withheld };
601
+ const all = this.withoutRefusedAttachedImages(request, error, true);
602
+ return all ? { request: all.request, withoutToolImages, withheld: all.withheld } : undefined;
603
+ }
456
604
  /**
457
605
  * The chat completions body for REQUEST, with at most SENT of the latest tool images, whether it carries one, and
458
606
  * what the route takes as one. WITHOUT_TOOL_IMAGES sends none, as a request Router refused for them goes again.
459
607
  */
460
608
  buildOpenAIBody(request, withoutToolImages, sent = TOOL_IMAGE_BUDGET) {
609
+ const noPromptCache = this.asksNoPromptCache(request);
610
+ const promptCache = noPromptCache ? { prompt_cache: false } : {};
461
611
  if (this.catalog?.version === 1) {
462
612
  const descriptor = resolveRouterModel(this.catalog, this.provider, request.model);
463
613
  if (!descriptor?.capabilities?.chat)
@@ -490,11 +640,13 @@ export class ZRouterStreamBackend {
490
640
  return { carriesToolImages, toolImages, body: {
491
641
  provider: descriptor.owned_by, model: `${descriptor.id}${variant}`,
492
642
  ...(routing ? { openrouter: routing } : {}),
493
- // With no plan Router takes the deck's or the workspace's stored default plan, whose fallbacks ZTC can't see:
494
- // a request carrying tool images says it has none, so they reach its model alone.
495
- ...(request.routePlan ? { route: request.routePlan } : carriesToolImages ? { route: { allow_fallbacks: false } } : {}),
643
+ // With no plan Router takes the deck's or the workspace's stored default plan, whose fallbacks ZTC can't see and
644
+ // which gets each the same body: a request carrying tool images, or asking for no prompt cache, says it has none,
645
+ // so what it carries reaches its model alone.
646
+ ...(request.routePlan ? { route: request.routePlan } : carriesToolImages || noPromptCache ? { route: { allow_fallbacks: false } } : {}),
496
647
  ...(outputLimit === undefined ? {} : { max_output_tokens: outputLimit }),
497
648
  ...(caps.reasoning && request.codexEffort ? { reasoning_effort: request.codexEffort } : {}),
649
+ ...promptCache,
498
650
  messages: buildOpenAIMessages(prepared, { flattenToolHistory: chatOnly, toolImages, sent }),
499
651
  ...(prepared.tools.length ? { tools: buildOpenAIToolDefs(prepared.tools) } : {}),
500
652
  } };
@@ -529,20 +681,22 @@ export class ZRouterStreamBackend {
529
681
  return { carriesToolImages: false, body: {
530
682
  provider: this.provider,
531
683
  model: request.model,
532
- ...(request.routePlan ? { route: request.routePlan } : {}),
684
+ // A request asking for no prompt cache with no plan of its own says it has no fallbacks, as above.
685
+ ...(request.routePlan ? { route: request.routePlan } : noPromptCache ? { route: { allow_fallbacks: false } } : {}),
533
686
  ...tokenParam,
534
687
  ...(request.codexEffort && modelContract(this.provider, request.model, 'chat_tools')?.reasoningEfforts.includes(request.codexEffort)
535
688
  ? { reasoning_effort: request.codexEffort } : {}),
689
+ ...promptCache,
536
690
  messages: buildOpenAIMessages(request),
537
691
  ...(request.tools.length > 0 ? { tools: buildOpenAIToolDefs(request.tools) } : {})
538
692
  } };
539
693
  }
540
694
  /**
541
- * The body first sent under each recent turn id, and whether it carries a tool image. Router binds a turn id to one
542
- * body and refuses a retry whose body differs ("Turn id was reused with a different request body", forge3d hub
543
- * 2026-11-06); the body reads settings, such as the model catalog that loads at startup, that can change between two
544
- * tries of a turn. A turn sent again with another body (without its tool images or its order's fields) goes under a
545
- * new id (renewTurn), so it never meets a body cached here for the id before.
695
+ * The body first sent under each recent turn id, and whether it carries a tool image or asks for no prompt cache. Router
696
+ * binds a turn id to one body and refuses a retry whose body differs ("Turn id was reused with a different request
697
+ * body", forge3d hub 2026-11-06); the body reads settings, such as the model catalog that loads at startup, that can
698
+ * change between two tries of a turn. A turn sent again with another body (without its tool images, its order's fields
699
+ * or prompt_cache) goes under a new id (renewTurn), so it never meets a body cached here for the id before.
546
700
  */
547
701
  turnBodies = new Map();
548
702
  /** The body REQUEST's turn sends: the one its first try sent (turnBodies), else bodyFor's. */
@@ -562,8 +716,9 @@ export class ZRouterStreamBackend {
562
716
  return built;
563
717
  }
564
718
  /**
565
- * The body as sent, and whether it carries a tool image; WITHOUT_TOOL_IMAGES as buildOpenAIBody takes it. A route
566
- * whose models limit the whole request (Gemini) gets only as many of the latest tool images as fit (fittedBody).
719
+ * The body as sent, and whether it carries a tool image or asks for no prompt cache; WITHOUT_TOOL_IMAGES as
720
+ * buildOpenAIBody takes it. A route whose models limit the whole request (Gemini) gets only as many of the latest tool
721
+ * images as fit (fittedBody).
567
722
  */
568
723
  bodyFor(request, stream, withoutToolImages) {
569
724
  let built = this.buildOpenAIBody(request, withoutToolImages);
@@ -595,7 +750,7 @@ export class ZRouterStreamBackend {
595
750
  }
596
751
  }
597
752
  }
598
- return { body: serialized, carriesToolImages: built.carriesToolImages };
753
+ return { body: serialized, carriesToolImages: built.carriesToolImages, asksNoPromptCache: built.body.prompt_cache === false };
599
754
  }
600
755
  async buildHeaders(request) {
601
756
  const { token, workspaceId } = this.authTokenProvider
@@ -693,7 +848,7 @@ export class ZRouterStreamBackend {
693
848
  return { backend, request: effective };
694
849
  }
695
850
  async prepareTurn(options) {
696
- if (!process.env.ZTC_EFFORT_POLICY_URL && !process.env.ZTC_EFFORT_POLICY_TOKEN)
851
+ if (!hostEnvironmentValue('ZTC_EFFORT_POLICY_URL') && !hostCredential('ZTC_EFFORT_POLICY_TOKEN'))
697
852
  return undefined;
698
853
  const turn = await this.hostPolicyTurn({ ...options, system: '', messages: [], tools: [] });
699
854
  // Even effort-only/inherit policies get an isolated snapshot. Dispatch must
@@ -734,25 +889,35 @@ export class ZRouterStreamBackend {
734
889
  }
735
890
  });
736
891
  }
737
- /** REQUEST's answer; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
738
- async generateResponse(request, fetcher, withoutToolImages = false) {
892
+ /**
893
+ * REQUEST's answer; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. WITHHELD is the
894
+ * note that stands in for the person's images in a request sent again without them, which the caller is told of once
895
+ * Router answers it (tellAttachedImagesWithheld).
896
+ */
897
+ async generateResponse(request, fetcher, withoutToolImages = false, withheld) {
739
898
  if (this.usesNativeResponses(request)) {
740
899
  const native = await this.nativeResponses(request, fetcher, withoutToolImages);
900
+ let again;
741
901
  try {
742
- return await native.backend.generate(native.request);
902
+ const response = await native.backend.generate(native.request);
903
+ if (withheld !== undefined)
904
+ this.tellAttachedImagesWithheld(request, withheld);
905
+ return response;
743
906
  }
744
907
  catch (error) {
745
- const failure = nativeRouterFailure(error, this.refusalRequest(), this.signInTarget());
746
- // Refused for what its tool images can cause: once more without them.
747
- if (!native.carriesToolImages || !this.refusedForToolImages(request, failure))
908
+ const failure = nativeRouterFailure(error, this.refusalRequest(), this.signInTarget(), this.onHostGrant());
909
+ // Refused for the person's images or a tool's: once more without what Router can't take (afterRefusal).
910
+ const next = this.afterRefusal(request, failure, native.carriesToolImages, withoutToolImages, withheld);
911
+ if (!next)
748
912
  throw failure;
913
+ again = next;
749
914
  }
750
915
  finally {
751
916
  native.dispose();
752
917
  }
753
- return this.generateResponse(renewTurn(request), fetcher, true);
918
+ return this.generateResponse(again.request, fetcher, again.withoutToolImages, again.withheld);
754
919
  }
755
- const { body, carriesToolImages } = this.serializeBody(request, false, withoutToolImages);
920
+ const { body, carriesToolImages, asksNoPromptCache } = this.serializeBody(request, false, withoutToolImages);
756
921
  const headers = await this.buildHeaders(request);
757
922
  // Proof-chain log: the exact router endpoint + model this turn dispatches to.
758
923
  runtimeDiag('info', `[ztc] zrouter dispatch ${JSON.stringify({
@@ -766,14 +931,17 @@ export class ZRouterStreamBackend {
766
931
  headers,
767
932
  body,
768
933
  signal: request.signal,
934
+ redirect: MODEL_REQUEST_REDIRECT,
769
935
  });
936
+ await refuseModelRedirect(response, this.endpointFor(), headers);
770
937
  if (!response.ok) {
771
938
  const failure = await readHttpErrorBody(response, request.signal);
772
939
  const error = routerFailure(response.status, failure.body, { headers, response, bodyReadState: failure.bodyReadState, request: this.refusalRequest(),
773
- ownSignIn: this.signInTarget(), provider: this.provider });
774
- // Refused for what its tool images can cause: once more without them.
775
- if (carriesToolImages && this.refusedForToolImages(request, error))
776
- return this.generateResponse(renewTurn(request), fetcher, true);
940
+ ownSignIn: this.signInTarget(), hostGrant: this.onHostGrant(), provider: this.provider });
941
+ // Refused for prompt_cache, the person's images or a tool's: once more without what Router can't take (afterRefusal).
942
+ const next = this.afterRefusal(request, error, carriesToolImages, withoutToolImages, withheld, asksNoPromptCache);
943
+ if (next)
944
+ return this.generateResponse(next.request, fetcher, next.withoutToolImages, next.withheld);
777
945
  throw error;
778
946
  }
779
947
  const data = await response.json();
@@ -781,6 +949,8 @@ export class ZRouterStreamBackend {
781
949
  if (this.getModelCapabilities(request.model)?.tools === false && parsed.content.some(block => block.type === 'tool_use')) {
782
950
  throw new Error('Chat-only model returned tools; execution is disabled.');
783
951
  }
952
+ if (withheld !== undefined)
953
+ this.tellAttachedImagesWithheld(request, withheld);
784
954
  return parsed;
785
955
  }
786
956
  parseOpenAIResponse(data) {
@@ -866,31 +1036,42 @@ export class ZRouterStreamBackend {
866
1036
  throw error;
867
1037
  }
868
1038
  }
869
- /** REQUEST's stream; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
870
- async *streamResponse(request, fetcher, withoutToolImages = false) {
1039
+ /**
1040
+ * REQUEST's stream; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. WITHHELD is the
1041
+ * note that stands in for the person's images in a request sent again without them, which the caller is told of once
1042
+ * Router streams its answer (tellAttachedImagesWithheld).
1043
+ */
1044
+ async *streamResponse(request, fetcher, withoutToolImages = false, withheld) {
871
1045
  if (this.usesNativeResponses(request)) {
872
1046
  const native = await this.nativeResponses(request, fetcher, withoutToolImages);
873
1047
  let answered = false;
1048
+ let again;
874
1049
  try {
875
1050
  for await (const event of native.backend.generateStream(native.request)) {
1051
+ if (!answered && event.type !== 'heartbeat' && withheld !== undefined)
1052
+ this.tellAttachedImagesWithheld(request, withheld);
876
1053
  answered ||= event.type !== 'heartbeat';
877
1054
  yield event;
878
1055
  }
879
1056
  return;
880
1057
  }
881
1058
  catch (error) {
882
- const failure = nativeRouterFailure(error, this.refusalRequest(), this.signInTarget());
883
- // Refused, before any output, for what its tool images can cause: once more without them.
884
- if (answered || !native.carriesToolImages || !this.refusedForToolImages(request, failure))
1059
+ const failure = nativeRouterFailure(error, this.refusalRequest(), this.signInTarget(), this.onHostGrant());
1060
+ if (answered)
885
1061
  throw failure;
1062
+ // Refused, before any output, for the person's images or a tool's: once more without what Router can't take.
1063
+ const next = this.afterRefusal(request, failure, native.carriesToolImages, withoutToolImages, withheld);
1064
+ if (!next)
1065
+ throw failure;
1066
+ again = next;
886
1067
  }
887
1068
  finally {
888
1069
  native.dispose();
889
1070
  }
890
- yield* this.streamResponse(renewTurn(request), fetcher, true);
1071
+ yield* this.streamResponse(again.request, fetcher, again.withoutToolImages, again.withheld);
891
1072
  return;
892
1073
  }
893
- const { body, carriesToolImages } = this.serializeBody(request, true, withoutToolImages);
1074
+ const { body, carriesToolImages, asksNoPromptCache } = this.serializeBody(request, true, withoutToolImages);
894
1075
  const mapEvent = createZrouterEventMapper();
895
1076
  // Events that mapped to nothing, by type, so a stream that never completes can say what it carried instead.
896
1077
  const unread = new Map();
@@ -901,6 +1082,8 @@ export class ZRouterStreamBackend {
901
1082
  // Router appends a router_error as the turn's last event and ends the turn,
902
1083
  // so a resume past it replays nothing: report the error instead.
903
1084
  let routerTurnEnded = false;
1085
+ // Whether the caller has heard that the person's images were withheld (WITHHELD): once Router streams its answer.
1086
+ let withheldTold = withheld === undefined;
904
1087
  const policy = resolveReconnectPolicy();
905
1088
  let reconnectStarted;
906
1089
  const budget = () => resumeAfter ? 300_000 : 30_000;
@@ -921,11 +1104,14 @@ export class ZRouterStreamBackend {
921
1104
  headers,
922
1105
  body,
923
1106
  signal: request.signal,
1107
+ redirect: MODEL_REQUEST_REDIRECT,
924
1108
  }, request.transportTurnId ? Math.min(ZROUTER_HEADERS_TIMEOUT_MS, Math.max(1, remaining())) : ZROUTER_HEADERS_TIMEOUT_MS);
1109
+ // Never resumed: Router would only redirect it again.
1110
+ await refuseModelRedirect(response, this.endpointFor(), headers);
925
1111
  if (!response.ok) {
926
1112
  const failure = await readHttpErrorBody(response, request.signal);
927
1113
  throw routerFailure(response.status, routerErrorFrameBody(failure.body), { headers, response, bodyReadState: failure.bodyReadState,
928
- request: this.refusalRequest(), ownSignIn: this.signInTarget(), provider: this.provider });
1114
+ request: this.refusalRequest(), ownSignIn: this.signInTarget(), hostGrant: this.onHostGrant(), provider: this.provider });
929
1115
  }
930
1116
  if (!response.body) {
931
1117
  throw new Error('ZRouter API error: no response body for streaming request');
@@ -955,7 +1141,7 @@ export class ZRouterStreamBackend {
955
1141
  : 502;
956
1142
  routerTurnEnded = true;
957
1143
  throw routerFailure(status, JSON.stringify(ev.body ?? {}), { headers, turnEnded: true, request: this.refusalRequest(),
958
- ownSignIn: this.signInTarget(), provider: this.provider });
1144
+ ownSignIn: this.signInTarget(), hostGrant: this.onHostGrant(), provider: this.provider });
959
1145
  }
960
1146
  const mapped = mapEvent(ev);
961
1147
  if (mapped.length === 0) {
@@ -968,6 +1154,10 @@ export class ZRouterStreamBackend {
968
1154
  if (this.getModelCapabilities(request.model)?.tools === false && mapped.some(event => event.type.startsWith('tool_use'))) {
969
1155
  throw new Error('Chat-only model returned tools; execution is disabled.');
970
1156
  }
1157
+ if (!withheldTold && mapped.some(event => event.type !== 'heartbeat')) {
1158
+ withheldTold = true;
1159
+ this.tellAttachedImagesWithheld(request, withheld);
1160
+ }
971
1161
  if (mapped.length > 0) {
972
1162
  // Heartbeats are liveness, not model output. A drop while only
973
1163
  // heartbeats have arrived cannot duplicate visible text, so it
@@ -988,10 +1178,12 @@ export class ZRouterStreamBackend {
988
1178
  return;
989
1179
  }
990
1180
  catch (error) {
991
- // Refused, before any output, for what its tool images can cause: once more without them, as a turn of its
992
- // own, since Router keeps a streamed turn's body under its id.
993
- if (carriesToolImages && !emittedMappedEvent && this.refusedForToolImages(request, error)) {
994
- yield* this.streamResponse(renewTurn(request), fetcher, true);
1181
+ // Refused, before any output, for prompt_cache, the person's images or a tool's: once more without what Router
1182
+ // can't take (afterRefusal), as a turn of its own, since Router keeps a streamed turn's body under its id.
1183
+ const next = emittedMappedEvent ? undefined
1184
+ : this.afterRefusal(request, error, carriesToolImages, withoutToolImages, withheld, asksNoPromptCache);
1185
+ if (next) {
1186
+ yield* this.streamResponse(next.request, fetcher, next.withoutToolImages, next.withheld);
995
1187
  return;
996
1188
  }
997
1189
  // Once the Router is replaying a turn we already started, the backend
@@ -1091,13 +1283,16 @@ async function waitForReconnect(delayMs, signal) {
1091
1283
  * server-side exception, since the body has nothing to correlate on.
1092
1284
  *
1093
1285
  * Bounded and header-only: never reads the body (already consumed), and caps
1094
- * each value so a hostile/proxied header cannot bloat an error message.
1286
+ * each value so a hostile/proxied header cannot bloat an error message. A value
1287
+ * that holds a credential (the bearer the request went with, SENT, or one of
1288
+ * ZTC's own) correlates nothing and is left out: the agent shows the request id,
1289
+ * and the session keeps what it shows.
1095
1290
  */
1096
- function failureHeaderSuffix(response) {
1291
+ function failureHeaderSuffix(response, sent) {
1097
1292
  const parts = [];
1098
1293
  for (const name of ['fly-request-id', 'x-request-id', 'cf-ray', 'x-zerg-error-code']) {
1099
1294
  const value = response.headers.get(name)?.trim();
1100
- if (value && value.length <= 128 && !/[\r\n\0]/.test(value))
1295
+ if (value && value.length <= 128 && !/[\r\n\0]/.test(value) && !holdsCredential(value, sent))
1101
1296
  parts.push(`${name}=${value}`);
1102
1297
  }
1103
1298
  return parts.length > 0 ? ` [${parts.join(' ')}]` : '';
@@ -1155,6 +1350,12 @@ function routersOwnAuthenticationFailure(body, native) {
1155
1350
  * has none.
1156
1351
  */
1157
1352
  function routerFailure(status, body, options) {
1353
+ // Router's own refusal of the host's grant, a 401 or 403 before anything reached a provider that is none of its usage
1354
+ // refusals: the grant expired or was revoked. Nothing else is tried.
1355
+ if (options.hostGrant && (status === 401 || status === 403 || authenticationErrorBody(body)) && !options.turnEnded
1356
+ && routersOwnAuthenticationFailure(body, options.native === true) && !readRouterRefusal(status, body, options.request)) {
1357
+ return new RouterAuthenticationError(ROUTER_RUNTIME_GRANT_REFUSED);
1358
+ }
1158
1359
  if (options.ownSignIn && (status === 401 || authenticationErrorBody(body))) {
1159
1360
  // Router's own refusal of this ZTC's sign-in, before anything reached a provider; else the provider's, inside a turn
1160
1361
  // Router started or passed on as it came.
@@ -1166,7 +1367,7 @@ function routerFailure(status, body, options) {
1166
1367
  const error = new BackendHttpError(status, body, { prefix: 'ZRouter API', headers: options.headers, bodyReadState: options.bodyReadState,
1167
1368
  retryAfter, rateLimitReset: options.response?.headers.get('x-ratelimit-reset'), turnEnded: options.turnEnded, provider: options.provider });
1168
1369
  if (options.response)
1169
- error.message += failureHeaderSuffix(options.response);
1370
+ error.message += failureHeaderSuffix(options.response, options.headers);
1170
1371
  return error;
1171
1372
  };
1172
1373
  const error = httpError(header);
@@ -1185,12 +1386,12 @@ function routerFailure(status, body, options) {
1185
1386
  * an authentication failure are said as Router's, whoever's credential the request went with: never as the provider's
1186
1387
  * own key, which ZTC didn't send. Any other failure keeps the native transport's own words.
1187
1388
  */
1188
- function nativeRouterFailure(error, request, ownSignIn) {
1389
+ function nativeRouterFailure(error, request, ownSignIn, hostGrant = false) {
1189
1390
  const failure = error instanceof Error ? /^API error \((\d{3})\): ([\s\S]*)$/.exec(error.message) : null;
1190
1391
  if (!failure)
1191
1392
  return error;
1192
1393
  const status = Number(failure[1]);
1193
- const converted = routerFailure(status, failure[2], { headers: {}, request, ownSignIn, native: true });
1394
+ const converted = routerFailure(status, failure[2], { headers: {}, request, ownSignIn, hostGrant, native: true });
1194
1395
  const unauthenticated = status === 401 || authenticationErrorBody(failure[2]);
1195
1396
  return converted instanceof RouterRefusalError || converted instanceof RouterAuthenticationError || unauthenticated ? converted : error;
1196
1397
  }