@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
@@ -31,6 +31,23 @@ export declare function readHttpErrorBody(response: Response, signal?: AbortSign
31
31
  body: string;
32
32
  bodyReadState: BodyReadState;
33
33
  }>;
34
+ /**
35
+ * Whether TEXT, something a server answered that ZTC would show or keep as it came (a response header's value), holds a
36
+ * credential the request went with (HEADERS) or one of ZTC's own (answeredCredentialForms), in any letter case.
37
+ */
38
+ export declare function holdsCredential(text: string, headers?: RequestInit['headers']): boolean;
39
+ /**
40
+ * TEXT, something a server answered that ZTC shows (where a redirect points), with each credential holdsCredential looks
41
+ * for withheld, in any letter case: the URL parser hands a host and a scheme back in lower case.
42
+ */
43
+ export declare function withholdCredentials(text: string, headers?: RequestInit['headers']): string;
44
+ /**
45
+ * TEXT, the words a server answered a request with (an error body, the message of a response that failed in band),
46
+ * without the credentials the request went with (HEADERS) or any labelled one, as BackendHttpError gives its body: for a
47
+ * transport that words its own error from what the server said, such as the Responses API's `API error (NNN): body`.
48
+ * TEXT must be whole: a body cut short is BackendHttpError's to redact.
49
+ */
50
+ export declare function redactSentCredentials(text: string, headers: RequestInit['headers']): string;
34
51
  /** Credentials in error text a person will read: bearer tokens, `key: value` credential pairs and sk- keys. */
35
52
  export declare function redactErrorText(text: string): string;
36
53
  export {};
@@ -1,4 +1,5 @@
1
1
  import { MAX_TIMER_DELAY_MS } from '../../config/api_retry.js';
2
+ import { CREDENTIAL_COPY_MIN_LENGTH, liveCredentialValues } from '../../config/host_credentials.js';
2
3
  const BODY_BYTES = 16 * 1024;
3
4
  const DIAGNOSTIC_BYTES = 4 * 1024;
4
5
  const BODY_TIMEOUT_MS = 1000;
@@ -170,7 +171,8 @@ function boundedCanonicalBody(text) {
170
171
  return bounded;
171
172
  }
172
173
  }
173
- function redact(text, headers, incomplete) {
174
+ /** The credentials HEADERS carry: each credential header's value, the token after an Authorization's scheme, each cookie's value. */
175
+ function sentSecrets(headers) {
174
176
  const secrets = new Set();
175
177
  for (const [name, value] of new Headers(headers)) {
176
178
  if (!/authorization|api[-_]?key|token|secret|credential|cookie/i.test(name) || !value)
@@ -186,6 +188,44 @@ function redact(text, headers, incomplete) {
186
188
  }
187
189
  }
188
190
  }
191
+ return secrets;
192
+ }
193
+ /**
194
+ * The credentials looked for in what a server answered that ZTC would show or keep as it came: those the request went
195
+ * with (HEADERS) and ZTC's own live in this process (config/host_credentials.ts liveCredentialValues), each of
196
+ * CREDENTIAL_COPY_MIN_LENGTH characters or more, as it is, JSON-escaped and URL-encoded; longest first.
197
+ */
198
+ function answeredCredentialForms(headers) {
199
+ const forms = new Set();
200
+ for (const secret of [...sentSecrets(headers), ...liveCredentialValues()]) {
201
+ if (secret.length < CREDENTIAL_COPY_MIN_LENGTH)
202
+ continue;
203
+ for (const form of [secret, JSON.stringify(secret).slice(1, -1), encodeURIComponent(secret)])
204
+ forms.add(form);
205
+ }
206
+ return [...forms].sort((a, b) => b.length - a.length);
207
+ }
208
+ /**
209
+ * Whether TEXT, something a server answered that ZTC would show or keep as it came (a response header's value), holds a
210
+ * credential the request went with (HEADERS) or one of ZTC's own (answeredCredentialForms), in any letter case.
211
+ */
212
+ export function holdsCredential(text, headers) {
213
+ const lower = text.toLowerCase();
214
+ return answeredCredentialForms(headers).some(form => lower.includes(form.toLowerCase()));
215
+ }
216
+ /**
217
+ * TEXT, something a server answered that ZTC shows (where a redirect points), with each credential holdsCredential looks
218
+ * for withheld, in any letter case: the URL parser hands a host and a scheme back in lower case.
219
+ */
220
+ export function withholdCredentials(text, headers) {
221
+ let withheld = text;
222
+ for (const form of answeredCredentialForms(headers)) {
223
+ withheld = withheld.replace(new RegExp(form.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), REDACTED);
224
+ }
225
+ return withheld;
226
+ }
227
+ function redact(text, headers, incomplete) {
228
+ const secrets = sentSecrets(headers);
189
229
  try {
190
230
  // Decode strings first: credential labels embedded in JSON messages may be
191
231
  // escaped on the wire. Sanitizing raw JSON could leave part of that value.
@@ -204,6 +244,15 @@ function redact(text, headers, incomplete) {
204
244
  return redactText(text.replace(/\\+(["'])/g, '$1'), secrets, incomplete);
205
245
  }
206
246
  }
247
+ /**
248
+ * TEXT, the words a server answered a request with (an error body, the message of a response that failed in band),
249
+ * without the credentials the request went with (HEADERS) or any labelled one, as BackendHttpError gives its body: for a
250
+ * transport that words its own error from what the server said, such as the Responses API's `API error (NNN): body`.
251
+ * TEXT must be whole: a body cut short is BackendHttpError's to redact.
252
+ */
253
+ export function redactSentCredentials(text, headers) {
254
+ return redact(text, headers, false);
255
+ }
207
256
  /** Credentials in error text a person will read: bearer tokens, `key: value` credential pairs and sk- keys. */
208
257
  export function redactErrorText(text) {
209
258
  return redactText(text, new Set(), false);
@@ -28,6 +28,7 @@ import { ClarifaiBackend } from './clarifai.js';
28
28
  import { KimiCodeAuthBackend, KimiCodeAuthManager } from './kimi_code_auth.js';
29
29
  import { ZRouterStreamBackend } from './zrouter_stream.js';
30
30
  import { requiredRouterModel } from '../../config/router_required.js';
31
+ import { hostEnvironmentValue } from '../../config/host_credentials.js';
31
32
  import { CODEX_APP_SERVER_PROVIDER, CODEX_LEGACY_PROVIDER, isDirectBackendProvider, normalizeProviderId } from './provider_ids.js';
32
33
  import { writeBackendTrace } from './trace.js';
33
34
  import { assertProviderNotRetired } from '../../config/retired_routes.js';
@@ -133,7 +134,7 @@ export function createBackendForProvider(provider, opts) {
133
134
  if (provider !== required.provider)
134
135
  throw new Error(`Required Router profile permits only ${required.provider}/${required.model}`);
135
136
  const proxyUrl = process.env.ZERG_PROXY_URL;
136
- const apiKey = process.env.ZERG_AUTH_TOKEN?.trim();
137
+ const apiKey = hostEnvironmentValue('ZERG_AUTH_TOKEN')?.trim();
137
138
  if (!proxyUrl || !apiKey)
138
139
  throw new Error('Required Router origin and service credential are unavailable');
139
140
  const origin = new URL(proxyUrl);
@@ -0,0 +1,47 @@
1
+ import { RequestRefusedError } from './types.js';
2
+ /**
3
+ * A model request goes only to the address it was made for. fetch follows a 307 or 308 by sending the same POST, with
4
+ * its body (the conversation), on to wherever the Location points, and undici drops only Authorization when that leaves
5
+ * the origin: a key in x-api-key, a ChatGPT-Account-Id and the X-Zerg headers go along, and the answer from there was
6
+ * read as the model's, tool calls included. So every fetch that sends a model request passes
7
+ * `redirect: MODEL_REQUEST_REDIRECT`, which hands back the redirect itself unfollowed, and gives the answer to
8
+ * refuseModelRedirect before reading it. No model endpoint ZTC talks to redirects a request on purpose (Zerg Router's
9
+ * canonical-origin redirect is for a browser's page loads only), so a redirect to the same origin is refused too.
10
+ */
11
+ export declare const MODEL_REQUEST_REDIRECT = "manual";
12
+ /**
13
+ * A model request whose endpoint answered with a redirect, which ZTC did not follow: the request went to the endpoint it
14
+ * was made for and nowhere else. Its message is shown as written, and it is never retried: the endpoint would only
15
+ * redirect it again.
16
+ */
17
+ export declare class ModelRequestRedirectError extends RequestRefusedError {
18
+ /** The redirect's HTTP status. */ readonly redirectStatus: number;
19
+ /** Where the redirect pointed: its origin, or what it was when it named no web origin; a credential in it withheld. */ readonly target: string;
20
+ constructor(
21
+ /** The redirect's HTTP status. */ redirectStatus: number,
22
+ /** Where the redirect pointed: its origin, or what it was when it named no web origin; a credential in it withheld. */ target: string, from: string);
23
+ }
24
+ /**
25
+ * A request to Zerg Router that sends no model request (its catalog read, a turn's cancel), answered with a redirect
26
+ * ZTC did not follow. It carries the Router's bearer and ZTC's workspace and turn headers, which go to the Router they
27
+ * are for and nowhere else, so it went there alone, and nothing another address says is read as the Router's.
28
+ */
29
+ export declare class RouterRequestRedirectError extends Error {
30
+ /** The redirect's HTTP status. */ readonly redirectStatus: number;
31
+ /** Where the redirect pointed: its origin, or what it was when it named no web origin; a credential in it withheld. */ readonly target: string;
32
+ readonly name = "RouterRequestRedirectError";
33
+ constructor(
34
+ /** The redirect's HTTP status. */ redirectStatus: number,
35
+ /** Where the redirect pointed: its origin, or what it was when it named no web origin; a credential in it withheld. */ target: string, from: string,
36
+ /** The request, as a sentence names it: "the model catalog read". */ request: string);
37
+ }
38
+ /**
39
+ * Throws ModelRequestRedirectError when RESPONSE, the answer to a model request sent to URL with
40
+ * MODEL_REQUEST_REDIRECT and SENT, its headers, is a redirect; its body is let go unread. Any other answer passes.
41
+ */
42
+ export declare function refuseModelRedirect(response: Response, url: string | URL, sent?: RequestInit['headers']): Promise<void>;
43
+ /**
44
+ * Throws RouterRequestRedirectError when RESPONSE, the answer to REQUEST ("the model catalog read") sent to URL with
45
+ * MODEL_REQUEST_REDIRECT and SENT, its headers, is a redirect; its body is let go unread. Any other answer passes.
46
+ */
47
+ export declare function refuseRouterRedirect(response: Response, url: string | URL, request: string, sent?: RequestInit['headers']): Promise<void>;
@@ -0,0 +1,97 @@
1
+ import { withholdCredentials } from './http_error.js';
2
+ import { RequestRefusedError } from './types.js';
3
+ /**
4
+ * A model request goes only to the address it was made for. fetch follows a 307 or 308 by sending the same POST, with
5
+ * its body (the conversation), on to wherever the Location points, and undici drops only Authorization when that leaves
6
+ * the origin: a key in x-api-key, a ChatGPT-Account-Id and the X-Zerg headers go along, and the answer from there was
7
+ * read as the model's, tool calls included. So every fetch that sends a model request passes
8
+ * `redirect: MODEL_REQUEST_REDIRECT`, which hands back the redirect itself unfollowed, and gives the answer to
9
+ * refuseModelRedirect before reading it. No model endpoint ZTC talks to redirects a request on purpose (Zerg Router's
10
+ * canonical-origin redirect is for a browser's page loads only), so a redirect to the same origin is refused too.
11
+ */
12
+ export const MODEL_REQUEST_REDIRECT = 'manual';
13
+ /** The statuses fetch would follow. */
14
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
15
+ /**
16
+ * A model request whose endpoint answered with a redirect, which ZTC did not follow: the request went to the endpoint it
17
+ * was made for and nowhere else. Its message is shown as written, and it is never retried: the endpoint would only
18
+ * redirect it again.
19
+ */
20
+ export class ModelRequestRedirectError extends RequestRefusedError {
21
+ redirectStatus;
22
+ target;
23
+ constructor(
24
+ /** The redirect's HTTP status. */ redirectStatus,
25
+ /** Where the redirect pointed: its origin, or what it was when it named no web origin; a credential in it withheld. */ target, from) {
26
+ super(`The model endpoint at ${from} answered this request with a redirect (HTTP ${redirectStatus}) to ${target}. `
27
+ + 'ZTC never sends a model request on to where a redirect points, so nothing was sent there. '
28
+ + 'If the endpoint has moved, set its new address.');
29
+ this.redirectStatus = redirectStatus;
30
+ this.target = target;
31
+ }
32
+ }
33
+ /**
34
+ * What a Location says, as it can be shown: an http(s) origin, never its path or query, which can hold a token. A host
35
+ * or scheme named after a credential, one the request went with (SENT, its headers) or one of ZTC's own, is shown with
36
+ * that credential withheld: a Router that echoes its bearer there would name the host's grant.
37
+ */
38
+ function redirectTarget(location, base, sent) {
39
+ if (!location)
40
+ return 'an address it did not name';
41
+ let url;
42
+ try {
43
+ url = new URL(location, base);
44
+ }
45
+ catch {
46
+ return 'an address that is not a URL';
47
+ }
48
+ return withholdCredentials(url.protocol === 'http:' || url.protocol === 'https:' ? url.origin : `a ${url.protocol} address`, sent);
49
+ }
50
+ /**
51
+ * A request to Zerg Router that sends no model request (its catalog read, a turn's cancel), answered with a redirect
52
+ * ZTC did not follow. It carries the Router's bearer and ZTC's workspace and turn headers, which go to the Router they
53
+ * are for and nowhere else, so it went there alone, and nothing another address says is read as the Router's.
54
+ */
55
+ export class RouterRequestRedirectError extends Error {
56
+ redirectStatus;
57
+ target;
58
+ name = 'RouterRequestRedirectError';
59
+ constructor(
60
+ /** The redirect's HTTP status. */ redirectStatus,
61
+ /** Where the redirect pointed: its origin, or what it was when it named no web origin; a credential in it withheld. */ target, from,
62
+ /** The request, as a sentence names it: "the model catalog read". */ request) {
63
+ super(`Zerg Router at ${from} answered ${request} with a redirect (HTTP ${redirectStatus}) to ${target}. `
64
+ + 'ZTC never sends a Router request on to where a redirect points, so nothing was sent there.');
65
+ this.redirectStatus = redirectStatus;
66
+ this.target = target;
67
+ }
68
+ }
69
+ /**
70
+ * The redirect RESPONSE (the answer to a request sent to URL with SENT, its headers, unfollowed) is, its body let go
71
+ * unread; null for any other answer.
72
+ */
73
+ async function unfollowedRedirect(response, url, sent) {
74
+ if (response.type !== 'opaqueredirect' && !REDIRECT_STATUSES.has(response.status))
75
+ return null;
76
+ await response.body?.cancel().catch(() => undefined);
77
+ const base = new URL(url);
78
+ return { status: response.status, target: redirectTarget(response.headers.get('location'), base, sent), from: base.origin };
79
+ }
80
+ /**
81
+ * Throws ModelRequestRedirectError when RESPONSE, the answer to a model request sent to URL with
82
+ * MODEL_REQUEST_REDIRECT and SENT, its headers, is a redirect; its body is let go unread. Any other answer passes.
83
+ */
84
+ export async function refuseModelRedirect(response, url, sent) {
85
+ const redirect = await unfollowedRedirect(response, url, sent);
86
+ if (redirect)
87
+ throw new ModelRequestRedirectError(redirect.status, redirect.target, redirect.from);
88
+ }
89
+ /**
90
+ * Throws RouterRequestRedirectError when RESPONSE, the answer to REQUEST ("the model catalog read") sent to URL with
91
+ * MODEL_REQUEST_REDIRECT and SENT, its headers, is a redirect; its body is let go unread. Any other answer passes.
92
+ */
93
+ export async function refuseRouterRedirect(response, url, request, sent) {
94
+ const redirect = await unfollowedRedirect(response, url, sent);
95
+ if (redirect)
96
+ throw new RouterRequestRedirectError(redirect.status, redirect.target, redirect.from, request);
97
+ }
@@ -1,5 +1,6 @@
1
1
  import { fireworksRequestModel, modelContract, reasoningRequestParams } from '@zerg/model-contracts';
2
2
  import { measureResponse, measureStream } from './request_metrics.js';
3
+ import { MODEL_REQUEST_REDIRECT, refuseModelRedirect } from './model_redirect.js';
3
4
  import { BackendHttpError, readHttpErrorBody } from './http_error.js';
4
5
  import { parseSSEStream } from './sse.js';
5
6
  import { parseTokenUsage } from './token_usage.js';
@@ -107,12 +108,14 @@ export class OpenAICompatibleBackend {
107
108
  headers,
108
109
  body: JSON.stringify(body),
109
110
  signal: request.signal,
111
+ redirect: MODEL_REQUEST_REDIRECT,
110
112
  });
111
113
  }
112
114
  catch (err) {
113
115
  throw new Error(`OpenAI-compatible chat request failed for model ${request.model} at ${url}: ${describeFetchError(err)}. ` +
114
116
  'Check network access, proxy configuration, and API key/model access.');
115
117
  }
118
+ await refuseModelRedirect(response, url);
116
119
  if (!response.ok) {
117
120
  const failure = await readHttpErrorBody(response, request.signal);
118
121
  throw new OpenAICompatibleApiError(response.status, failure.body, { headers, bodyReadState: failure.bodyReadState });
@@ -178,12 +181,14 @@ export class OpenAICompatibleBackend {
178
181
  headers,
179
182
  body: JSON.stringify({ ...body, stream: true, stream_options: { include_usage: true } }),
180
183
  signal: request.signal,
184
+ redirect: MODEL_REQUEST_REDIRECT,
181
185
  });
182
186
  }
183
187
  catch (err) {
184
188
  throw new Error(`OpenAI-compatible stream request failed for model ${request.model} at ${url}: ${describeFetchError(err)}. ` +
185
189
  'Check network access, proxy configuration, and API key/model access.');
186
190
  }
191
+ await refuseModelRedirect(response, url);
187
192
  if (!response.ok) {
188
193
  const failure = await readHttpErrorBody(response, request.signal);
189
194
  throw new OpenAICompatibleApiError(response.status, failure.body, { headers, bodyReadState: failure.bodyReadState });
@@ -150,6 +150,8 @@ export declare function parseResponsesOutput(data: {
150
150
  export declare function streamResponsesSSE(response: Response, maxBytes?: number, options?: {
151
151
  rejectIncomplete?: boolean;
152
152
  failureError?: string;
153
+ /** The headers the request went with: a failure the stream reports is shown without their credentials. */
154
+ sentHeaders?: RequestInit['headers'];
153
155
  }): AsyncIterable<StreamEvent>;
154
156
  export declare class OpenAIResponsesBackend extends BaseBackend {
155
157
  readonly preservesNativeHistory: boolean;
@@ -165,7 +167,13 @@ export declare class OpenAIResponsesBackend extends BaseBackend {
165
167
  private buildBody;
166
168
  /** The request body as sent, within the largest request the provider takes (Router's Atlas service): fittedBody. */
167
169
  private serializeBody;
168
- /** POST to /responses, throwing a descriptive error on transport / API failure. */
170
+ /** The headers a /responses request goes with: the key as its bearer, unless the caller's own name another (Router's grant). */
171
+ private requestHeaders;
172
+ /**
173
+ * POST to /responses, throwing a descriptive error on transport / API failure. The error repeats what the endpoint
174
+ * answered without the credentials the request went with: a Router that echoes its bearer in a failure echoes the
175
+ * host's grant.
176
+ */
169
177
  private fetchResponses;
170
178
  generate(request: BackendRequest): Promise<BackendResponse>;
171
179
  generateStream(request: BackendRequest): AsyncIterable<StreamEvent>;
@@ -2,6 +2,8 @@ import { IncompleteStreamError } from './transport_errors.js';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
  import { responsesReasoning } from './responses_reasoning.js';
4
4
  import { BaseBackend } from './base.js';
5
+ import { redactSentCredentials } from './http_error.js';
6
+ import { MODEL_REQUEST_REDIRECT, refuseModelRedirect } from './model_redirect.js';
5
7
  import { parseTokenUsage } from './token_usage.js';
6
8
  import { fittedBody, OPENAI_IMAGE_LIMITS, olderToolImages, olderToolImagesLine, planToolImages, TOOL_IMAGE_BUDGET } from './tool_result_images.js';
7
9
  function isRecord(value) {
@@ -452,8 +454,8 @@ export async function* streamResponsesSSE(response, maxBytes = MAX_RESPONSES_SSE
452
454
  // output fall through to a silent, successful end_turn.
453
455
  const resp = event.response;
454
456
  const errObj = (resp?.error ?? event.error);
455
- const msg = errObj?.message || 'the provider reported a stream failure';
456
- throw new Error(options.failureError ?? `Responses API stream failed: ${msg}`);
457
+ const msg = String(errObj?.message || 'the provider reported a stream failure');
458
+ throw new Error(options.failureError ?? `Responses API stream failed: ${redactSentCredentials(msg, options.sentHeaders)}`);
457
459
  }
458
460
  };
459
461
  if (response.body) {
@@ -631,30 +633,36 @@ export class OpenAIResponsesBackend extends BaseBackend {
631
633
  serializeBody(request, stream) {
632
634
  return fittedBody((this.toolImages || undefined)?.maxRequestBytes, sent => JSON.stringify(this.buildBody(request, stream, sent)));
633
635
  }
634
- /** POST to /responses, throwing a descriptive error on transport / API failure. */
636
+ /** The headers a /responses request goes with: the key as its bearer, unless the caller's own name another (Router's grant). */
637
+ requestHeaders() {
638
+ return { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}`, ...this.extraHeaders };
639
+ }
640
+ /**
641
+ * POST to /responses, throwing a descriptive error on transport / API failure. The error repeats what the endpoint
642
+ * answered without the credentials the request went with: a Router that echoes its bearer in a failure echoes the
643
+ * host's grant.
644
+ */
635
645
  async fetchResponses(request, stream) {
636
646
  const url = `${this.baseUrl}/responses`;
647
+ const headers = this.requestHeaders();
637
648
  let response;
638
649
  try {
639
650
  response = await this.fetcher(url, {
640
651
  method: 'POST',
641
- headers: {
642
- 'Content-Type': 'application/json',
643
- Authorization: `Bearer ${this.apiKey}`,
644
- ...this.extraHeaders,
645
- },
652
+ headers,
646
653
  body: this.serializeBody(request, stream),
647
654
  signal: request.signal,
648
- redirect: 'error',
655
+ redirect: MODEL_REQUEST_REDIRECT,
649
656
  });
650
657
  }
651
658
  catch (err) {
652
659
  throw new Error(`OpenAI Responses request failed for model ${request.model} at ${url}: ${describeFetchError(err)}. ` +
653
660
  'Check network access, proxy configuration, and API key/model access.');
654
661
  }
662
+ await refuseModelRedirect(response, url, headers);
655
663
  if (!response.ok) {
656
664
  const errorText = await readBoundedProviderError(response);
657
- throw new Error(`API error (${response.status}): ${errorText}`);
665
+ throw new Error(`API error (${response.status}): ${redactSentCredentials(errorText, headers)}`);
658
666
  }
659
667
  return response;
660
668
  }
@@ -676,7 +684,8 @@ export class OpenAIResponsesBackend extends BaseBackend {
676
684
  // Surface it rather than returning parseResponsesOutput's empty end_turn — the
677
685
  // buffered-fallback twin of the streamResponsesSSE failure branch.
678
686
  if (data.status === 'failed' || data.error) {
679
- throw new Error(`Responses API failed: ${data.error?.message || 'the provider reported a failed response'}`);
687
+ const reason = String(data.error?.message || 'the provider reported a failed response');
688
+ throw new Error(`Responses API failed: ${redactSentCredentials(reason, this.requestHeaders())}`);
680
689
  }
681
690
  if (Array.isArray(data.output)) {
682
691
  data.output.forEach(requireValidResponsesOutputItem);
@@ -694,7 +703,7 @@ export class OpenAIResponsesBackend extends BaseBackend {
694
703
  // streamsSyntheticallyFor=false below only matters if this backend is consumed
695
704
  // directly.
696
705
  async *generateStream(request) {
697
- yield* streamResponsesSSE(await this.fetchResponses(request, true));
706
+ yield* streamResponsesSSE(await this.fetchResponses(request, true), undefined, { sentHeaders: this.requestHeaders() });
698
707
  }
699
708
  // Real streaming above — NOT the BaseBackend buffer-then-replay default. Tell
700
709
  // the agent so it consumes generateStream instead of taking the buffered path.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * ZTC_PROMPT_CACHE_TTL, the prompt cache ZTC asks for: `1h` (the default, also when the variable is set empty), `5m` or
3
+ * `off`, in any letter case, as read here; any other value is the default. AnthropicBackend reads it for the
4
+ * cache_control its own requests carry, Zerg Router's chat route (ZRouterStreamBackend) for whether a Claude model's
5
+ * request asks Router for no prompt cache either, and idle compaction (utils/idle_compaction.ts) for how long that
6
+ * cache lives, none when it is off. Nothing else reads the variable.
7
+ */
8
+ export declare function promptCacheTtl(): string;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * ZTC_PROMPT_CACHE_TTL, the prompt cache ZTC asks for: `1h` (the default, also when the variable is set empty), `5m` or
3
+ * `off`, in any letter case, as read here; any other value is the default. AnthropicBackend reads it for the
4
+ * cache_control its own requests carry, Zerg Router's chat route (ZRouterStreamBackend) for whether a Claude model's
5
+ * request asks Router for no prompt cache either, and idle compaction (utils/idle_compaction.ts) for how long that
6
+ * cache lives, none when it is off. Nothing else reads the variable.
7
+ */
8
+ export function promptCacheTtl() {
9
+ return (process.env.ZTC_PROMPT_CACHE_TTL || '1h').toLowerCase();
10
+ }
@@ -15,7 +15,7 @@ export declare function getProviderDisplayName(provider: string): string;
15
15
  /**
16
16
  * Providers whose key, when this machine holds one, goes to the provider itself even when ZTC is logged in to Zerg
17
17
  * Router: a Morph plan's key is its holder's own. Without a local key, Router serves Morph from the key its owner saved
18
- * there (#866), so the login routes it.
18
+ * there (#866), so the login routes it, and so does ZTC_LLM_AUTH_MODE=zrouter with one (ConfigStore.routingOf).
19
19
  */
20
20
  export declare function ownKeyGoesDirect(provider: string): boolean;
21
21
  export declare function isLocalSubscriptionProvider(provider: string): boolean;
@@ -45,7 +45,7 @@ export function getProviderDisplayName(provider) {
45
45
  /**
46
46
  * Providers whose key, when this machine holds one, goes to the provider itself even when ZTC is logged in to Zerg
47
47
  * Router: a Morph plan's key is its holder's own. Without a local key, Router serves Morph from the key its owner saved
48
- * there (#866), so the login routes it.
48
+ * there (#866), so the login routes it, and so does ZTC_LLM_AUTH_MODE=zrouter with one (ConfigStore.routingOf).
49
49
  */
50
50
  export function ownKeyGoesDirect(provider) {
51
51
  return normalizeProviderId(provider) === 'morph';
@@ -280,6 +280,14 @@ export interface BackendRequest {
280
280
  * images, which go no more): display-only, never sent to the model. Optional; a backend without one says nothing.
281
281
  */
282
282
  onNotice?: (message: string) => void;
283
+ /**
284
+ * Zerg Router refused this request as one it can't price under a spending limit while it carried images the person
285
+ * attached, and took it once it went again with NOTE in place of each one but those of a media type in KEEP (those
286
+ * Router prices on the route; none when KEEP is empty or absent; agent/attached_images.ts): the caller puts NOTE in
287
+ * their place in its conversation and saved session, so no later request carries them again. Optional; a backend
288
+ * without it never withholds them.
289
+ */
290
+ onAttachedImagesWithheld?: (note: string, keep?: readonly string[]) => void;
283
291
  /** Per HTTP attempt diagnostics for Router and OpenAI-compatible transports. */
284
292
  onMetrics?: (metrics: RequestMetrics) => void;
285
293
  /**
@@ -1,4 +1,5 @@
1
1
  import { BaseBackend } from './base.js';
2
+ import { MODEL_REQUEST_REDIRECT, refuseModelRedirect } from './model_redirect.js';
2
3
  import { configStore } from '../../config.js';
3
4
  import { inferDefaultProvider } from '../../config/defaults.js';
4
5
  import { buildKimiRequestParams } from './kimi_params.js';
@@ -98,7 +99,8 @@ export class ZergAPIBackend extends BaseBackend {
98
99
  };
99
100
  }
100
101
  async post(body, signal) {
101
- const response = await fetch(`${this.baseUrl}/api/zrouter/llm/chat/`, {
102
+ const url = `${this.baseUrl}/api/zrouter/llm/chat/`;
103
+ const response = await fetch(url, {
102
104
  method: 'POST',
103
105
  headers: {
104
106
  'Content-Type': 'application/json',
@@ -106,7 +108,9 @@ export class ZergAPIBackend extends BaseBackend {
106
108
  },
107
109
  body: JSON.stringify(body),
108
110
  signal,
111
+ redirect: MODEL_REQUEST_REDIRECT,
109
112
  });
113
+ await refuseModelRedirect(response, url);
110
114
  if (!response.ok) {
111
115
  const errorText = await response.text();
112
116
  let errorMessage;
@@ -75,6 +75,8 @@ export declare class ZRouterStreamBackend implements AgentBackend {
75
75
  private signInNow;
76
76
  /** On the person's own sign-in, the provider a 401 inside a turn is worded with (see routerFailure); otherwise none. */
77
77
  private signInTarget;
78
+ /** Whether this backend's requests go with the host's Router runtime grant, whose refusal is worded as the grant's. */
79
+ private onHostGrant;
78
80
  /** What a refusal is worded with: this backend's provider, by the name Router's catalog gives it, and its link. */
79
81
  private refusalRequest;
80
82
  private endpointFor;
@@ -114,6 +116,31 @@ export declare class ZRouterStreamBackend implements AgentBackend {
114
116
  private routeModels;
115
117
  /** The fallbacks REQUEST's route plan reaches, as written: none when it has no plan or turns them off. */
116
118
  private planFallbacks;
119
+ /**
120
+ * The providers REQUEST's route may reach, by name: this backend's, then each of its plan's fallbacks' (`provider/model`,
121
+ * or a model of this backend's provider), since Router sends each of them the same body.
122
+ */
123
+ private routeProviders;
124
+ /** What promptCacheRefused knows REQUEST's Router and account by. */
125
+ private promptCacheKey;
126
+ /**
127
+ * Whether REQUEST's chat body asks Router for no prompt cache (`prompt_cache: false`): when ZTC_PROMPT_CACHE_TTL is off
128
+ * (promptCacheTtl, as AnthropicBackend reads it, whose requests then carry no cache_control), for a route whose every
129
+ * provider is Anthropic. Router's translation to Anthropic's Messages API caches a system prompt of 1024 characters or
130
+ * more unless the body says so, and records a request carrying cache_control without a price, which a dollar limit
131
+ * counts at its whole hold. Router hands the body to every other provider's API as it came, a field that API doesn't
132
+ * know included, so a body that asks with no route plan of its own also says it has no fallbacks (buildOpenAIBody):
133
+ * Router would take the deck's or the workspace's stored plan, which ZTC can't see. Never on a Router and account
134
+ * that refused the field (refusedPromptCache).
135
+ */
136
+ private asksNoPromptCache;
137
+ /**
138
+ * Whether Router refused REQUEST, whose body asked for no prompt cache, for a field its account doesn't take, as a
139
+ * service-account key's allowlist refuses prompt_cache and the route that goes with it: then that Router and account
140
+ * get the field no more (promptCacheRefused), which the runtime diagnostics say once, and the caller sends the request
141
+ * once more without it, and so without that route (buildOpenAIBody).
142
+ */
143
+ private refusedPromptCache;
117
144
  /**
118
145
  * What toolImagesRefused knows this request's route, account, provider and model by, and its plan's fallbacks: Router
119
146
  * doesn't say which model of a plan refused, so a refusal on a plan is that plan's, not its model's alone.
@@ -134,24 +161,55 @@ export declare class ZRouterStreamBackend implements AgentBackend {
134
161
  * one within TAKES (a refusal another request met first), its transcript is told.
135
162
  */
136
163
  private toolImagesGoNoMore;
164
+ /**
165
+ * The media types of an image Router may price on REQUEST's route under a spending limit: what it prices for this
166
+ * route's provider and for each provider its plan falls back to, since Router sends each the same body.
167
+ */
168
+ private pricedImageTypes;
169
+ /**
170
+ * REQUEST to send again when Router refused it as one it can't price under a spending limit while it carried images
171
+ * the person attached: the same request with a note in place of each of theirs of a format Router never prices on the
172
+ * route (pricedImageTypes: all but a PNG, JPEG or WebP for OpenAI's models, every image for another provider's), or of
173
+ * 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.
174
+ * Every Zerg Router route does this: a host's (its Router runtime grant, as ZergCloud's resident runs, or a host's own
175
+ * credential provider) and the person's own key or sign-in, as desktop and npm owners run ZTC. Undefined for any
176
+ * other failure, or a request without such images.
177
+ */
178
+ private withoutRefusedAttachedImages;
179
+ /**
180
+ * Router took REQUEST, sent again without the images the person attached that WITHHELD names: the transcript says
181
+ * why, and the caller puts its note in their place in its conversation, so no later request carries them again.
182
+ */
183
+ private tellAttachedImagesWithheld;
184
+ /**
185
+ * What to send once more after Router refused REQUEST with ERROR, before any output, when it carried tool images if
186
+ * CARRIES_TOOL_IMAGES (and went WITHOUT_TOOL_IMAGES, WITHHELD the person's images already), and asked for no prompt
187
+ * cache if ASKS_NO_PROMPT_CACHE: without that field when Router refused it (refusedPromptCache), as a turn of its own,
188
+ * whose body is built again; else first without the person's images in a format Router never prices on the route,
189
+ * which Router can't price whatever else goes, so a tool's images that it does price aren't held off the route for
190
+ * them; then without the tool images, for what they can cause (refusedForToolImages, which holds them off the route);
191
+ * then without every image the person attached. Undefined when none applies, and the refusal stands.
192
+ */
193
+ private afterRefusal;
137
194
  /**
138
195
  * The chat completions body for REQUEST, with at most SENT of the latest tool images, whether it carries one, and
139
196
  * what the route takes as one. WITHOUT_TOOL_IMAGES sends none, as a request Router refused for them goes again.
140
197
  */
141
198
  private buildOpenAIBody;
142
199
  /**
143
- * The body first sent under each recent turn id, and whether it carries a tool image. Router binds a turn id to one
144
- * body and refuses a retry whose body differs ("Turn id was reused with a different request body", forge3d hub
145
- * 2026-11-06); the body reads settings, such as the model catalog that loads at startup, that can change between two
146
- * tries of a turn. A turn sent again with another body (without its tool images or its order's fields) goes under a
147
- * new id (renewTurn), so it never meets a body cached here for the id before.
200
+ * The body first sent under each recent turn id, and whether it carries a tool image or asks for no prompt cache. Router
201
+ * binds a turn id to one body and refuses a retry whose body differs ("Turn id was reused with a different request
202
+ * body", forge3d hub 2026-11-06); the body reads settings, such as the model catalog that loads at startup, that can
203
+ * change between two tries of a turn. A turn sent again with another body (without its tool images, its order's fields
204
+ * or prompt_cache) goes under a new id (renewTurn), so it never meets a body cached here for the id before.
148
205
  */
149
206
  private readonly turnBodies;
150
207
  /** The body REQUEST's turn sends: the one its first try sent (turnBodies), else bodyFor's. */
151
208
  private serializeBody;
152
209
  /**
153
- * The body as sent, and whether it carries a tool image; WITHOUT_TOOL_IMAGES as buildOpenAIBody takes it. A route
154
- * whose models limit the whole request (Gemini) gets only as many of the latest tool images as fit (fittedBody).
210
+ * The body as sent, and whether it carries a tool image or asks for no prompt cache; WITHOUT_TOOL_IMAGES as
211
+ * buildOpenAIBody takes it. A route whose models limit the whole request (Gemini) gets only as many of the latest tool
212
+ * images as fit (fittedBody).
155
213
  */
156
214
  private bodyFor;
157
215
  private buildHeaders;
@@ -170,13 +228,21 @@ export declare class ZRouterStreamBackend implements AgentBackend {
170
228
  private hostPolicyTurn;
171
229
  prepareTurn(options: BackendTurnOptions): Promise<PreparedBackendTurn | undefined>;
172
230
  generate(request: BackendRequest): Promise<BackendResponse>;
173
- /** REQUEST's answer; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
231
+ /**
232
+ * REQUEST's answer; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. WITHHELD is the
233
+ * note that stands in for the person's images in a request sent again without them, which the caller is told of once
234
+ * Router answers it (tellAttachedImagesWithheld).
235
+ */
174
236
  private generateResponse;
175
237
  private parseOpenAIResponse;
176
238
  generateStream(request: BackendRequest): AsyncIterable<StreamEvent>;
177
239
  /** A stream the process gate admits; Router answering with output clears whatever held it. */
178
240
  private gatedStream;
179
- /** REQUEST's stream; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. */
241
+ /**
242
+ * REQUEST's stream; WITHOUT_TOOL_IMAGES sends it with none, as one Router refused for them goes again. WITHHELD is the
243
+ * note that stands in for the person's images in a request sent again without them, which the caller is told of once
244
+ * Router streams its answer (tellAttachedImagesWithheld).
245
+ */
180
246
  private streamResponse;
181
247
  }
182
248
  /**