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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +144 -33
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/App.js +2 -2
  8. package/dist/agent/agent.d.ts +13 -3
  9. package/dist/agent/agent.js +179 -91
  10. package/dist/agent/backends/codex_app_server.d.ts +1 -0
  11. package/dist/agent/backends/codex_app_server.js +3 -1
  12. package/dist/agent/backends/host_effort_policy.d.ts +12 -0
  13. package/dist/agent/backends/host_effort_policy.js +132 -0
  14. package/dist/agent/backends/index.d.ts +3 -2
  15. package/dist/agent/backends/index.js +4 -0
  16. package/dist/agent/backends/router_gate.d.ts +11 -0
  17. package/dist/agent/backends/router_gate.js +27 -2
  18. package/dist/agent/backends/router_keys.d.ts +63 -0
  19. package/dist/agent/backends/router_keys.js +94 -0
  20. package/dist/agent/backends/router_refusal.d.ts +12 -15
  21. package/dist/agent/backends/router_refusal.js +29 -5
  22. package/dist/agent/backends/types.d.ts +10 -0
  23. package/dist/agent/backends/zrouter_stream.d.ts +48 -1
  24. package/dist/agent/backends/zrouter_stream.js +215 -24
  25. package/dist/agent/commands/agent_cli.js +11 -3
  26. package/dist/agent/commands/config.js +12 -0
  27. package/dist/agent/commands/index.js +2 -1
  28. package/dist/agent/commands/mirror.js +15 -5
  29. package/dist/agent/commands/provider.js +4 -2
  30. package/dist/agent/commands/provider_selection.js +16 -2
  31. package/dist/agent/commands/router_availability.d.ts +15 -0
  32. package/dist/agent/commands/router_availability.js +45 -0
  33. package/dist/agent/commands/settings.js +38 -5
  34. package/dist/agent/commands/subs.d.ts +4 -1
  35. package/dist/agent/commands/subs.js +15 -5
  36. package/dist/agent/commands/types.d.ts +10 -0
  37. package/dist/agent/commands/ztc_pane.d.ts +20 -0
  38. package/dist/agent/commands/ztc_pane.js +239 -0
  39. package/dist/agent/factory.js +10 -2
  40. package/dist/agent/host_model_context.d.ts +9 -0
  41. package/dist/agent/host_model_context.js +40 -0
  42. package/dist/agent/request_encoder.d.ts +3 -0
  43. package/dist/agent/request_encoder.js +11 -4
  44. package/dist/agent/runtime/tool_runtime.js +8 -2
  45. package/dist/agent/subagent.d.ts +9 -0
  46. package/dist/agent/subagent.js +65 -46
  47. package/dist/agent/tools/file.js +10 -6
  48. package/dist/agent/tools/pane.d.ts +7 -0
  49. package/dist/agent/tools/pane.js +31 -6
  50. package/dist/agent/tools/ztc_command.d.ts +12 -0
  51. package/dist/agent/tools/ztc_command.js +21 -6
  52. package/dist/app/agent_runner.js +5 -2
  53. package/dist/app/command_context.js +10 -4
  54. package/dist/app/mirror_startup.d.ts +16 -0
  55. package/dist/app/mirror_startup.js +10 -0
  56. package/dist/app/runtime_choices.d.ts +2 -0
  57. package/dist/app/runtime_choices.js +1 -1
  58. package/dist/app/runtime_choices_source.js +2 -1
  59. package/dist/app/tool_callbacks.js +1 -0
  60. package/dist/cli_args.d.ts +2 -0
  61. package/dist/cli_args.js +5 -0
  62. package/dist/cli_ratatui.d.ts +14 -0
  63. package/dist/cli_ratatui.js +113 -27
  64. package/dist/config/permissions.d.ts +13 -0
  65. package/dist/config/permissions.js +63 -1
  66. package/dist/config/retired_routes.d.ts +23 -3
  67. package/dist/config/retired_routes.js +62 -11
  68. package/dist/config/types.d.ts +18 -1
  69. package/dist/config.d.ts +42 -0
  70. package/dist/config.js +102 -3
  71. package/dist/desktop/daily/desktop_wiring.js +9 -0
  72. package/dist/desktop/daily/recipes.js +7 -1
  73. package/dist/headless.js +2 -2
  74. package/dist/library.js +2 -2
  75. package/dist/mcp/client.js +6 -3
  76. package/dist/mcp/workspace_server.d.ts +6 -1
  77. package/dist/mcp/workspace_server.js +58 -9
  78. package/dist/onboarding/first_run.d.ts +3 -1
  79. package/dist/onboarding/first_run.js +21 -6
  80. package/dist/onboarding/router_tips.js +10 -7
  81. package/dist/panes/agent_cli.d.ts +48 -0
  82. package/dist/panes/agent_cli.js +145 -0
  83. package/dist/panes/agent_panes.d.ts +11 -0
  84. package/dist/panes/agent_panes.js +25 -4
  85. package/dist/panes/initial_input.d.ts +6 -0
  86. package/dist/panes/initial_input.js +6 -0
  87. package/dist/panes/motsi.d.ts +22 -7
  88. package/dist/panes/motsi.js +36 -9
  89. package/dist/panes/worker_route.d.ts +123 -0
  90. package/dist/panes/worker_route.js +464 -0
  91. package/dist/panes/ztc_launch.d.ts +9 -0
  92. package/dist/panes/ztc_launch.js +58 -2
  93. package/dist/router_auth.d.ts +18 -0
  94. package/dist/router_auth.js +78 -2
  95. package/dist/types.d.ts +5 -0
  96. package/dist/ui/ratatui/headless_pane_manager.d.ts +2 -0
  97. package/dist/ui/ratatui/headless_pane_manager.js +6 -3
  98. package/dist/ui/ratatui/pane_relay.d.ts +11 -1
  99. package/dist/ui/ratatui/pane_relay.js +14 -2
  100. package/dist/ui/ratatui/protocol.d.ts +9 -1
  101. package/dist/utils/atomic_write.js +26 -1
  102. package/dist/utils/docker_target.js +4 -1
  103. package/dist/utils/subprocess_env.d.ts +18 -0
  104. package/dist/utils/subprocess_env.js +45 -0
  105. package/dist/web/mirror_authenticator.d.ts +6 -0
  106. package/dist/web/mirror_authenticator.js +15 -12
  107. package/dist/web/mirror_stream.d.ts +50 -0
  108. package/dist/web/mirror_stream.js +121 -30
  109. package/dist/worker/worker_models.d.ts +11 -0
  110. package/dist/worker/worker_models.js +19 -7
  111. package/dist/zlm-embed.mjs +1349 -429
  112. package/dist/zlm.js +1 -1
  113. package/package.json +32 -16
@@ -52,6 +52,7 @@ export interface CodexAppServerClientOptions {
52
52
  * codex CLI would bill that API key instead of the account's ChatGPT
53
53
  * subscription (auth.json under CODEX_HOME). It applies even with no
54
54
  * per-account home so an ambient key never hijacks the default ChatGPT login.
55
+ * A host's effort policy is ZTC's own and never reaches it either.
55
56
  */
56
57
  export declare function buildCodexAppServerEnv(codexHome?: string, base?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
57
58
  export interface CodexTurnOptions {
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { RateLimitError, parseResetAt } from './rate_limit.js';
4
4
  import { CODEX_APP_SERVER_PROVIDER } from './provider_ids.js';
5
5
  import { NativeObservationLimitError } from '../runtime/provider_native_evidence.js';
6
+ import { withoutHostEffortPolicy } from '../../utils/subprocess_env.js';
6
7
  export const MAX_CODEX_APP_SERVER_FRAME_BYTES = 1_048_576;
7
8
  export const MAX_CODEX_APP_SERVER_QUEUED_FRAMES = 1_024;
8
9
  /** Keep managed profiles on their own auth.json and ChatGPT subscription. */
@@ -25,9 +26,10 @@ const MAX_CODEX_APP_SERVER_MODELS = 2_000;
25
26
  * codex CLI would bill that API key instead of the account's ChatGPT
26
27
  * subscription (auth.json under CODEX_HOME). It applies even with no
27
28
  * per-account home so an ambient key never hijacks the default ChatGPT login.
29
+ * A host's effort policy is ZTC's own and never reaches it either.
28
30
  */
29
31
  export function buildCodexAppServerEnv(codexHome, base = process.env) {
30
- const env = { ...base };
32
+ const env = withoutHostEffortPolicy(base);
31
33
  if (codexHome)
32
34
  env.CODEX_HOME = codexHome;
33
35
  for (const name of [
@@ -0,0 +1,12 @@
1
+ import type { BackendRequest } from './types.js';
2
+ export type HostModelSelection = {
3
+ provider: string;
4
+ model: string;
5
+ };
6
+ type ResolvedPolicyTurn = {
7
+ request: BackendRequest;
8
+ supported: readonly string[] | undefined;
9
+ };
10
+ /** Host-owned policy is opt-in. Ordinary terminal clients retain their settings. */
11
+ export declare function applyHostEffortPolicy(request: BackendRequest, resolve: (model: HostModelSelection | null) => Promise<ResolvedPolicyTurn>): Promise<BackendRequest>;
12
+ export {};
@@ -0,0 +1,132 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { runtimeDiag } from '../../utils/debug_log.js';
3
+ const LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
4
+ const POLICIES = ['inherit', 'maximum', ...LEVELS];
5
+ /** Host-owned policy is opt-in. Ordinary terminal clients retain their settings. */
6
+ export async function applyHostEffortPolicy(request, resolve) {
7
+ const endpoint = process.env.ZTC_EFFORT_POLICY_URL;
8
+ const token = process.env.ZTC_EFFORT_POLICY_TOKEN;
9
+ if (!endpoint && !token)
10
+ return request;
11
+ let url;
12
+ try {
13
+ url = new URL(endpoint || '');
14
+ }
15
+ catch {
16
+ throw new Error('Invalid host effort policy configuration');
17
+ }
18
+ const loopbackHttp = url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
19
+ if (!token || !/^[A-Za-z0-9_-]{1,512}$/.test(token) || url.username || url.password || url.hash
20
+ || (url.protocol !== 'https:' && !loopbackHttp)) {
21
+ throw new Error('Invalid host effort policy configuration');
22
+ }
23
+ let payload;
24
+ // The policy is read before every model call. A host redeploy or a dropped connection must not end a multi-step
25
+ // turn, so a network error, timeout, 429 or 5xx is tried up to three times. A refusal or a malformed policy fails
26
+ // at once.
27
+ for (let attempt = 1;; attempt++) {
28
+ const timeout = AbortSignal.timeout(3000);
29
+ const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout;
30
+ let retryable = true;
31
+ try {
32
+ const response = await fetch(url, {
33
+ headers: { authorization: `Bearer ${token}`, 'cache-control': 'no-store' },
34
+ signal,
35
+ redirect: 'error',
36
+ });
37
+ if (!response.ok) {
38
+ await response.body?.cancel();
39
+ retryable = response.status === 429 || response.status >= 500;
40
+ throw new Error('Policy read failed');
41
+ }
42
+ const reader = response.body?.getReader();
43
+ if (!reader)
44
+ throw new Error('Empty policy');
45
+ const chunks = [];
46
+ let length = 0;
47
+ try {
48
+ for (;;) {
49
+ const chunk = await reader.read();
50
+ if (chunk.done)
51
+ break;
52
+ length += chunk.value.byteLength;
53
+ if (length > 4096) {
54
+ retryable = false;
55
+ throw new Error('Oversized policy');
56
+ }
57
+ chunks.push(chunk.value);
58
+ }
59
+ retryable = false;
60
+ payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
61
+ }
62
+ finally {
63
+ await reader.cancel();
64
+ }
65
+ break;
66
+ }
67
+ catch {
68
+ request.signal?.throwIfAborted();
69
+ if (!retryable || attempt >= 3) {
70
+ throw new Error('Host effort policy unavailable. Retry or ask the platform administrator to check connectivity.');
71
+ }
72
+ }
73
+ await sleep(250 * attempt, undefined, request.signal ? { signal: request.signal } : undefined).catch(() => undefined);
74
+ request.signal?.throwIfAborted();
75
+ }
76
+ if (!payload || typeof payload !== 'object')
77
+ throw new Error('Invalid host effort policy');
78
+ const policy = payload;
79
+ if ((policy.schemaVersion !== 1 && policy.schemaVersion !== 2)
80
+ || typeof policy.effort !== 'string' || !POLICIES.includes(policy.effort)
81
+ || typeof policy.revision !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(policy.revision)) {
82
+ throw new Error('Invalid host effort policy');
83
+ }
84
+ let model = null;
85
+ if (policy.schemaVersion === 2) {
86
+ const selection = policy.model;
87
+ const identifier = (value) => typeof value === 'string' && value.length > 0 && value.length <= 512 && !/[\x00-\x1f\x7f]/.test(value);
88
+ if (!selection || typeof selection !== 'object' || !identifier(selection.provider) || !identifier(selection.model)) {
89
+ throw new Error('Invalid host model policy');
90
+ }
91
+ model = { provider: selection.provider, model: selection.model };
92
+ }
93
+ else if (policy.model != null) {
94
+ throw new Error('Invalid host model policy version');
95
+ }
96
+ const resolved = await resolve(model);
97
+ request = resolved.request;
98
+ const supported = resolved.supported;
99
+ if (policy.effort === 'inherit') {
100
+ // A host-selected model may not offer the resident's own level. Use the highest level it offers at or below
101
+ // that level (or its lowest), rather than sending an effort the Router refuses on every turn.
102
+ const inherited = request.codexEffort;
103
+ if (!model || !inherited || !supported?.length || supported.includes(inherited))
104
+ return request;
105
+ const rank = LEVELS.indexOf(inherited);
106
+ const offered = LEVELS.filter(level => supported.includes(level));
107
+ const effort = (rank < 0 ? undefined : offered.filter(level => LEVELS.indexOf(level) <= rank).at(-1)) ?? offered[0];
108
+ runtimeDiag('info', `[ztc] host effort policy ${JSON.stringify({ revision: policy.revision, policy: 'inherit', model,
109
+ inheritedEffort: inherited, effectiveEffort: effort ?? null })}`);
110
+ return { ...request, codexEffort: effort };
111
+ }
112
+ if (supported === undefined) {
113
+ throw new Error('Host effort policy cannot verify supported effort levels for this model. Refresh the Router model catalog.');
114
+ }
115
+ const effort = policy.effort === 'maximum'
116
+ ? [...LEVELS].reverse().find(level => supported.includes(level))
117
+ : policy.effort;
118
+ if (policy.effort !== 'maximum' && !supported.includes(policy.effort)) {
119
+ throw new Error(`Host effort policy ${policy.effort} is not supported by this model.`);
120
+ }
121
+ if (policy.effort === 'maximum' && supported.length && !effort) {
122
+ throw new Error('Host effort policy cannot resolve the advertised reasoning levels.');
123
+ }
124
+ // An advertised non-reasoning model stays non-reasoning under adaptive maximum.
125
+ runtimeDiag('info', `[ztc] host effort policy ${JSON.stringify({
126
+ revision: policy.revision,
127
+ policy: policy.effort,
128
+ model,
129
+ effectiveEffort: effort ?? null,
130
+ })}`);
131
+ return { ...request, codexEffort: effort };
132
+ }
@@ -16,8 +16,8 @@ export { CODEX_APP_SERVER_PROVIDER, CODEX_APP_SERVER_SENTINEL, CODEX_LEGACY_PROV
16
16
  export { ClarifaiBackend, normalizeClarifaiModel, CLARIFAI_BASE_URL } from './clarifai.js';
17
17
  export { KimiCodeAuthBackend, KimiCodeAuthManager, KIMI_CODE_AUTH_SENTINEL, KIMI_CODE_PROVIDER, hasUsableKimiCodeAuth } from './kimi_code_auth.js';
18
18
  export { RetiredProviderError } from '../../config/retired_routes.js';
19
- export type { AgentBackend, BackendObservation, BackendRequest, BackendResponse, ContentBlock, TextBlock, ToolUseBlock, ThinkingBlock, RedactedThinkingBlock, LlmMessage, RequestContentBlock, RequestVideoBlock, ToolResultBlock, TokenUsage, StreamEvent } from './types.js';
20
- import type { AgentBackend, BackendRequest, BackendResponse, StreamEvent } from './types.js';
19
+ export type { AgentBackend, BackendObservation, BackendRequest, BackendTurnOptions, PreparedBackendTurn, BackendResponse, ContentBlock, TextBlock, ToolUseBlock, ThinkingBlock, RedactedThinkingBlock, LlmMessage, RequestContentBlock, RequestVideoBlock, ToolResultBlock, TokenUsage, StreamEvent } from './types.js';
20
+ import type { AgentBackend, BackendRequest, BackendResponse, BackendTurnOptions, PreparedBackendTurn, StreamEvent } from './types.js';
21
21
  import type { Message } from '../../types.js';
22
22
  export interface CreateBackendOptions {
23
23
  bedrock?: BedrockBackendConfig;
@@ -45,6 +45,7 @@ export declare class TracedBackend implements AgentBackend {
45
45
  isAuthenticationConfigured(): boolean;
46
46
  constructor(provider: string, backend: AgentBackend);
47
47
  getModelCapabilities(model: string): import("../../utils/router_catalog.js").RouterModelCapabilities | undefined;
48
+ prepareTurn(options: BackendTurnOptions): Promise<PreparedBackendTurn | undefined>;
48
49
  steerUserMessage(message: Message): Promise<boolean>;
49
50
  /** Forward disposal so a process-backed inner (a codex child) is closed when
50
51
  * the agent is. Without this, tracing (ZTC_BACKEND_TRACE=1)
@@ -41,6 +41,10 @@ export class TracedBackend {
41
41
  this.backend = backend;
42
42
  }
43
43
  getModelCapabilities(model) { return this.backend.getModelCapabilities?.(model); }
44
+ async prepareTurn(options) {
45
+ const turn = await this.backend.prepareTurn?.(options);
46
+ return turn ? { ...turn, backend: new TracedBackend(this.provider, turn.backend) } : undefined;
47
+ }
44
48
  async steerUserMessage(message) {
45
49
  return this.backend.steerUserMessage?.(message) ?? false;
46
50
  }
@@ -1,3 +1,4 @@
1
+ import { type RouterCatalog } from '../../utils/router_catalog.js';
1
2
  import type { RouterRefusal } from './router_refusal.js';
2
3
  import { RouterRefusalError } from './router_refusal.js';
3
4
  /** At most one real attempt per held route and model in this long. */
@@ -52,6 +53,16 @@ export declare class RouterRefusalGate {
52
53
  refuse(target: RouterGateTarget, error: RouterRefusalError): void;
53
54
  /** Router answered: whatever held this route and model is over. */
54
55
  succeed(target: RouterGateTarget): void;
56
+ /**
57
+ * Router's catalog, just sent for this route and account, lists as one it can run a model a hold for want of its
58
+ * provider's key (provider_key_unavailable) waited on: the key has been added, so that hold is over and the next
59
+ * request for it reaches Router, a relayed one included. A model the catalog doesn't describe counts once any model
60
+ * of its provider can run. Every other hold stays. Only a catalog Router has just sent says so, never a cached one.
61
+ */
62
+ keysListed(filter: {
63
+ route: string;
64
+ account: string;
65
+ }, catalog: RouterCatalog): void;
55
66
  /**
56
67
  * Would a request for this route and account (and provider and model, when given) be refused locally now? Asks
57
68
  * without taking the five-minute attempt, so a run can skip Router work it already knows is refused.
@@ -9,8 +9,10 @@
9
9
  * through, so a raised limit takes effect within minutes, and a success for that route, account, provider and model
10
10
  * clears its hold. The person's own new message always gets one real attempt, since they may have just raised the
11
11
  * limit, though what they type into a ZTC pane's or a colony cell's terminal, which the overseer types into too, is
12
- * relayed and gets none (see the TUI's takesRouterAttempt). A provider cooldown that ended a turn is the exception:
13
- * nothing the person can change shortens it, so no request, theirs included, is tried before it clears.
12
+ * relayed and gets none (see the TUI's takesRouterAttempt). So a hold for want of a provider's key also ends when
13
+ * Router's catalog lists the model it waited on again (keysListed), as /provider refresh after adding the key does. A
14
+ * provider cooldown that ended a turn is the exception: nothing the person can change shortens it, so no request,
15
+ * theirs included, is tried before it clears.
14
16
  *
15
17
  * The hold is keyed by the route (the Router or platform proxy URL), the account (a one-way fingerprint of the
16
18
  * credential, never the credential), the provider and the model. Keying every refusal by account, not only the credit
@@ -18,6 +20,8 @@
18
20
  * its own real attempt.
19
21
  */
20
22
  import { createHash } from 'node:crypto';
23
+ import { resolveRouterModel } from '../../utils/router_catalog.js';
24
+ import { PROVIDER_KEY_UNAVAILABLE } from './router_keys.js';
21
25
  import { RouterRefusalError } from './router_refusal.js';
22
26
  /** At most one real attempt per held route and model in this long. */
23
27
  export const ROUTER_REFUSAL_RETRY_MS = 5 * 60_000;
@@ -95,6 +99,27 @@ export class RouterRefusalGate {
95
99
  this.holds.delete(key);
96
100
  this.store?.released(hold);
97
101
  }
102
+ /**
103
+ * Router's catalog, just sent for this route and account, lists as one it can run a model a hold for want of its
104
+ * provider's key (provider_key_unavailable) waited on: the key has been added, so that hold is over and the next
105
+ * request for it reaches Router, a relayed one included. A model the catalog doesn't describe counts once any model
106
+ * of its provider can run. Every other hold stays. Only a catalog Router has just sent says so, never a cached one.
107
+ */
108
+ keysListed(filter, catalog) {
109
+ if (catalog.version !== 1)
110
+ return;
111
+ for (const [key, hold] of this.holds) {
112
+ if (hold.refusal.code !== PROVIDER_KEY_UNAVAILABLE || hold.route !== routerRoute(filter.route) || hold.account !== filter.account)
113
+ continue;
114
+ const row = resolveRouterModel(catalog, hold.provider, hold.model);
115
+ const runs = row ? row.available !== false
116
+ : catalog.models.some(model => model.owned_by === hold.provider && model.available !== false);
117
+ if (!runs)
118
+ continue;
119
+ this.holds.delete(key);
120
+ this.store?.released(hold);
121
+ }
122
+ }
98
123
  /**
99
124
  * Would a request for this route and account (and provider and model, when given) be refused locally now? Asks
100
125
  * without taking the five-minute attempt, so a run can skip Router work it already knows is refused.
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Zerg Router with no usable key for a provider: what ZTC says when Router refuses a request for want of one, and
3
+ * when a model Router's catalog marks unavailable is chosen, and where the person adds one.
4
+ *
5
+ * Router refuses before calling the provider (code provider_key_unavailable, `provider_dispatched: false`;
6
+ * zapps/zergrouter server/lib/missing-provider-key.ts), naming the provider in its error data or, on a ZTC stream's
7
+ * router_error frame, only in its sentence. Its catalog lists such a provider's models with `available: false`. Every
8
+ * provider's key is an API key the person adds on Router's Credentials page: never a Claude.ai or ChatGPT sign-in,
9
+ * Router's Subscriptions tab or MotSi, whatever the provider. A personal-only provider's key (Morph's) serves only the
10
+ * Router account it is in, so its refusals also say which account that is. ZTC never collects, reads or forwards the
11
+ * key.
12
+ */
13
+ import type { RouterCatalog } from '../../utils/router_catalog.js';
14
+ /** Router's code for a provider it has no usable key for, so nothing was sent to it. */
15
+ export declare const PROVIDER_KEY_UNAVAILABLE = "provider_key_unavailable";
16
+ /** Router's Credentials page on ORIGIN, where a person adds a provider's API key. */
17
+ export declare function routerCredentialsUrl(origin: string): string;
18
+ /** The name Router's catalog gives PROVIDER ("Morph"), if it lists one. */
19
+ export declare function routerProviderLabel(catalog: RouterCatalog | undefined, provider: string): string | undefined;
20
+ /** The provider a missing-key message is about, as the request or choice that met it knows it. */
21
+ export interface RouterKeyTarget {
22
+ /** The provider's id; absent when ZTC can't tell which provider Router meant. */
23
+ provider?: string;
24
+ /** Its name ("Morph"); the id when no name is known. */
25
+ label?: string;
26
+ /** Router's Credentials page for the account in use, when ZTC knows it (a personal Router sign-in). */
27
+ credentialsUrl?: string;
28
+ }
29
+ export declare const ROUTER_PERSONAL_ONLY_PROVIDERS: readonly string[];
30
+ /** PROVIDER's name as Router's catalog gives it, else a personal-only provider's own ("Morph"); undefined for none. */
31
+ export declare function knownRouterProviderName(catalog: RouterCatalog | undefined, provider: string): string | undefined;
32
+ /**
33
+ * Where TARGET's key goes and what else helps, said once. A personal-only provider's key (ROUTER_PERSONAL_ONLY_PROVIDERS)
34
+ * goes in the account this ZTC is signed in to, or ZTC signs in to the account that holds it; any other provider's a
35
+ * team or the platform can hold. `addIt` names the key ("your Morph API key", "it"); `otherModel` ends on picking
36
+ * another model.
37
+ */
38
+ export declare function routerKeyAdvice(target: RouterKeyTarget, addIt: string, { otherModel }?: {
39
+ otherModel?: boolean | undefined;
40
+ }): string;
41
+ /** What ZTC says when Router refused a request because it has no key for the provider: nothing reached it. */
42
+ export declare function missingRouterKeyMessage(target: RouterKeyTarget): string;
43
+ /**
44
+ * What ZTC says when the provider turned away the key Zerg Router holds for it: its 401, which Router passes on from
45
+ * inside a turn it started, so Router took this ZTC's sign-in. The key to check is the provider's, on Router.
46
+ */
47
+ export declare function rejectedRouterKeyMessage(target: RouterKeyTarget & {
48
+ provider: string;
49
+ }): string;
50
+ /** What ZTC says when a model chosen through Router is one its catalog marks unavailable: the choice changes nothing. */
51
+ export declare function unavailableRouterModelMessage(target: RouterKeyTarget & {
52
+ provider: string;
53
+ model: string;
54
+ }): string;
55
+ /**
56
+ * What ZTC says when a model chosen through Router is one its cached catalog marks unavailable and Router couldn't be
57
+ * asked again: the key may have been added since, so ZTC says only what the last list said, and the choice changes
58
+ * nothing.
59
+ */
60
+ export declare function uncheckedRouterModelMessage(target: RouterKeyTarget & {
61
+ provider: string;
62
+ model: string;
63
+ }): string;
@@ -0,0 +1,94 @@
1
+ /** Router's code for a provider it has no usable key for, so nothing was sent to it. */
2
+ export const PROVIDER_KEY_UNAVAILABLE = 'provider_key_unavailable';
3
+ /** Router's Credentials page on ORIGIN, where a person adds a provider's API key. */
4
+ export function routerCredentialsUrl(origin) {
5
+ return `${origin.replace(/\/+$/, '')}/dashboard?tab=credentials`;
6
+ }
7
+ /** The name Router's catalog gives PROVIDER ("Morph"), if it lists one. */
8
+ export function routerProviderLabel(catalog, provider) {
9
+ return catalog?.models.find(row => row.owned_by === provider && row.provider_display_name)?.provider_display_name;
10
+ }
11
+ /** Modal runs only on Zerg's own key, so there is no key to add: only another model helps. */
12
+ function zergKeyOnly(provider) {
13
+ return provider === 'modal';
14
+ }
15
+ /**
16
+ * Providers whose keys Zerg Router keeps personal (its PERSONAL_ONLY_PROVIDERS, zapps/zergrouter
17
+ * server/lib/personal-providers.ts), by the name a refusal gives each when Router's catalog gives none: a key serves
18
+ * only the logins of the Router account that holds it, never a team's or the platform's pool, so a key added in another
19
+ * Router account reaches nothing this ZTC sends.
20
+ */
21
+ const PERSONAL_ONLY_NAMES = Object.freeze({ morph: 'Morph' });
22
+ export const ROUTER_PERSONAL_ONLY_PROVIDERS = Object.freeze(Object.keys(PERSONAL_ONLY_NAMES));
23
+ /** PROVIDER's name as Router's catalog gives it, else a personal-only provider's own ("Morph"); undefined for none. */
24
+ export function knownRouterProviderName(catalog, provider) {
25
+ const id = provider.toLowerCase();
26
+ return routerProviderLabel(catalog, provider) ?? (Object.hasOwn(PERSONAL_ONLY_NAMES, id) ? PERSONAL_ONLY_NAMES[id] : undefined);
27
+ }
28
+ function where(target) {
29
+ return target.credentialsUrl ? `at ${target.credentialsUrl}` : 'on Zerg Router\'s Credentials page';
30
+ }
31
+ function personalOnly(target) {
32
+ return target.provider !== undefined && Object.hasOwn(PERSONAL_ONLY_NAMES, target.provider.toLowerCase());
33
+ }
34
+ /** The provider's name: Router's (or ZTC's) label, a personal-only provider's own name, else its id. */
35
+ function nameOf(target) {
36
+ if (!target.provider)
37
+ return undefined;
38
+ return target.label || (personalOnly(target) ? PERSONAL_ONLY_NAMES[target.provider.toLowerCase()] : undefined) || target.provider;
39
+ }
40
+ /**
41
+ * Where TARGET's key goes and what else helps, said once. A personal-only provider's key (ROUTER_PERSONAL_ONLY_PROVIDERS)
42
+ * goes in the account this ZTC is signed in to, or ZTC signs in to the account that holds it; any other provider's a
43
+ * team or the platform can hold. `addIt` names the key ("your Morph API key", "it"); `otherModel` ends on picking
44
+ * another model.
45
+ */
46
+ export function routerKeyAdvice(target, addIt, { otherModel = true } = {}) {
47
+ const another = otherModel ? ', or pick another model' : '';
48
+ if (!personalOnly(target))
49
+ return `Add ${addIt} ${where(target)}, then run /provider refresh${another}.`;
50
+ return `${nameOf(target)} keys are personal: Zerg Router uses the key in the account this ZTC is signed in to. Add ${addIt} to `
51
+ + `that account ${where(target)}, then run /provider refresh, or sign ZTC in to the account that holds it (/auth logout, then `
52
+ + `/auth login)${another}.`;
53
+ }
54
+ /** What ZTC says when Router refused a request because it has no key for the provider: nothing reached it. */
55
+ export function missingRouterKeyMessage(target) {
56
+ const name = nameOf(target);
57
+ if (!name) {
58
+ return 'Zerg Router has no key for this model\'s provider on your account, so nothing was sent to it. '
59
+ + `Add the provider's API key ${where(target)}, then run /provider refresh, or pick another model.`;
60
+ }
61
+ if (zergKeyOnly(target.provider))
62
+ return `Zerg Router has no key for ${name}, so it cannot run this model. Choose another model with /model.`;
63
+ return `Zerg Router has no ${name} key for your account, so nothing was sent to ${name}. ${routerKeyAdvice(target, `your ${name} API key`)}`;
64
+ }
65
+ /**
66
+ * What ZTC says when the provider turned away the key Zerg Router holds for it: its 401, which Router passes on from
67
+ * inside a turn it started, so Router took this ZTC's sign-in. The key to check is the provider's, on Router.
68
+ */
69
+ export function rejectedRouterKeyMessage(target) {
70
+ const name = nameOf(target);
71
+ return `${name} didn't accept the key Zerg Router has for it on your account, so nothing came back. Check your ${name} API key `
72
+ + `${where(target)}, or pick another model.`;
73
+ }
74
+ /** What ZTC says when a model chosen through Router is one its catalog marks unavailable: the choice changes nothing. */
75
+ export function unavailableRouterModelMessage(target) {
76
+ const name = nameOf(target);
77
+ if (zergKeyOnly(target.provider))
78
+ return `Zerg Router has no key for ${name}, so it cannot run ${target.model}. Choose another model.`;
79
+ return `Zerg Router has no ${name} key for your account, so ${target.model} can't run. ${routerKeyAdvice(target, `your ${name} API key`)}`;
80
+ }
81
+ /**
82
+ * What ZTC says when a model chosen through Router is one its cached catalog marks unavailable and Router couldn't be
83
+ * asked again: the key may have been added since, so ZTC says only what the last list said, and the choice changes
84
+ * nothing.
85
+ */
86
+ export function uncheckedRouterModelMessage(target) {
87
+ const name = nameOf(target);
88
+ const unchecked = `Couldn't check ${target.model} with Zerg Router just now; its last list says Router has`;
89
+ if (zergKeyOnly(target.provider)) {
90
+ return `${unchecked} no key for ${name}, so it can't run. Try again in a moment, or choose another model.`;
91
+ }
92
+ return `${unchecked} no ${name} key for your account. `
93
+ + `Try again in a moment, add your ${name} API key ${where(target)}, or pick another model.`;
94
+ }
@@ -1,16 +1,3 @@
1
- /**
2
- * Zerg Router's refusals that come before any provider is called (`provider_dispatched: false`), read from Router's
3
- * two error envelopes and from the ZergAI platform proxy's own answers, and the words ZTC shows for them.
4
- *
5
- * Router (zapps/zergrouter shared/usage-controls.ts): a usage refusal's error data carries `code` and
6
- * `provider_dispatched: false`; current builds add `period`, `resets_at` (null when waiting will not help), `scope`
7
- * and `help_url`, and word the message so a person can act on it. A platform key out of credit is a 429
8
- * `insufficient_quota` / `credit_balance_exhausted`, a provider still cooling down `provider_rate_limit_cooldown`
9
- * with `retryAfterSeconds`. These sit in `data` in the H3 envelope (a resumable turn's router_error frame and non-/v1
10
- * routes) and under `error` on the /v1 routes. The platform proxy (zergai/api/zrouter/proxy.py) passes Router's status
11
- * and body through but drops its headers, so retry timing is read from the body; its own workspace quota and request
12
- * throttles answer in their own shapes.
13
- */
14
1
  import { RequestRefusedError } from './types.js';
15
2
  export type RouterRefusalKind =
16
3
  /** Lasts until a reset or a change: the turn ends at once. */
@@ -79,11 +66,21 @@ export declare const ROUTER_USAGE_DENIALS: Readonly<Record<string, string>>;
79
66
  export declare const PLATFORM_TOKEN_QUOTA = "platform_token_quota_exceeded";
80
67
  /** The platform proxy's own request-rate or concurrency throttle for a CLI machine credential. */
81
68
  export declare const PLATFORM_THROTTLE = "platform_throttled";
69
+ /** What a refused request was for, which Router's missing-key refusal is worded with (see readRouterRefusal). */
70
+ export interface RouterRefusalRequest {
71
+ /** The provider the request went to Router for. */
72
+ provider: string;
73
+ /** Its name, as Router's catalog gives it ("Morph"). */
74
+ providerLabel?: string;
75
+ /** Router's Credentials page for the account the request used, when ZTC knows it. */
76
+ credentialsUrl?: string;
77
+ }
82
78
  /**
83
79
  * The refusal an error response describes, or null for any other error. `status` is the HTTP status (or a router_error
84
- * frame's), `body` the error body as text.
80
+ * frame's), `body` the error body as text. `request` words a missing-key refusal: the provider is named only when it
81
+ * is the one the request went to, so nothing Router sends picks the words.
85
82
  */
86
- export declare function readRouterRefusal(status: number, body: string): RouterRefusal | null;
83
+ export declare function readRouterRefusal(status: number, body: string, request?: RouterRefusalRequest): RouterRefusal | null;
87
84
  /**
88
85
  * Router's words as a terminal can show them: escape sequences removed, control characters made spaces, everything
89
86
  * else in Unicode's Other category (format characters such as bidi controls, zero-width and tag characters; lone
@@ -9,8 +9,11 @@
9
9
  * with `retryAfterSeconds`. These sit in `data` in the H3 envelope (a resumable turn's router_error frame and non-/v1
10
10
  * routes) and under `error` on the /v1 routes. The platform proxy (zergai/api/zrouter/proxy.py) passes Router's status
11
11
  * and body through but drops its headers, so retry timing is read from the body; its own workspace quota and request
12
- * throttles answer in their own shapes.
12
+ * throttles answer in their own shapes. A provider Router has no usable key for is `provider_key_unavailable`, read by
13
+ * its code whatever the provider (or, from an older Router that sent no code, by its exact sentence) and worded by ZTC
14
+ * (router_keys.ts), since Router's sentence names no way on.
13
15
  */
16
+ import { missingRouterKeyMessage, PROVIDER_KEY_UNAVAILABLE } from './router_keys.js';
14
17
  import { RequestRefusedError } from './types.js';
15
18
  /**
16
19
  * The longest provider cooldown a turn waits out. Router cools a rate-limited key for 60 seconds unless the provider
@@ -117,11 +120,20 @@ function envelopeOf(parsed) {
117
120
  return { fields: {}, message: parsed.detail, detail: true };
118
121
  return null;
119
122
  }
123
+ /** Router's sentence for a provider it has no key for (missingProviderKey), the provider's id and nothing else after it. */
124
+ const MISSING_KEY_SENTENCE = /^No API key available for provider: ([A-Za-z0-9._-]{1,128})$/;
125
+ /** The provider Router's missing-key refusal names: in its error data, or only in its sentence on a stream's frame. */
126
+ function providerNamed(fields, said) {
127
+ if (typeof fields.provider === 'string')
128
+ return fields.provider;
129
+ return MISSING_KEY_SENTENCE.exec(said)?.[1];
130
+ }
120
131
  /**
121
132
  * The refusal an error response describes, or null for any other error. `status` is the HTTP status (or a router_error
122
- * frame's), `body` the error body as text.
133
+ * frame's), `body` the error body as text. `request` words a missing-key refusal: the provider is named only when it
134
+ * is the one the request went to, so nothing Router sends picks the words.
123
135
  */
124
- export function readRouterRefusal(status, body) {
136
+ export function readRouterRefusal(status, body, request) {
125
137
  if (!Number.isInteger(status) || status < 400)
126
138
  return null;
127
139
  let parsed;
@@ -143,7 +155,19 @@ export function readRouterRefusal(status, body) {
143
155
  let name = code ?? '';
144
156
  let fallback;
145
157
  let retryAfterSeconds;
146
- if (code && Object.hasOwn(ROUTER_USAGE_DENIALS, code) && dispatched !== true) {
158
+ /** ZTC's words replace Router's, which say only that the key is missing. */
159
+ let ownWords = false;
160
+ // An older Router sent the refusal's sentence alone, with no code: that exact sentence is the same refusal.
161
+ const untagged = code === undefined && status === 400 && MISSING_KEY_SENTENCE.test(said);
162
+ if ((code === PROVIDER_KEY_UNAVAILABLE || untagged) && dispatched !== true) {
163
+ // Lasts until a key is added: the person's own next message still gets a real attempt (router_gate.ts).
164
+ kind = 'lasting';
165
+ name = PROVIDER_KEY_UNAVAILABLE;
166
+ const named = request && providerNamed(fields, said) === request.provider ? request : undefined;
167
+ fallback = missingRouterKeyMessage({ provider: named?.provider, label: named?.providerLabel, credentialsUrl: request?.credentialsUrl });
168
+ ownWords = true;
169
+ }
170
+ else if (code && Object.hasOwn(ROUTER_USAGE_DENIALS, code) && dispatched !== true) {
147
171
  kind = code === CONCURRENCY ? 'concurrency' : 'lasting';
148
172
  fallback = ROUTER_USAGE_DENIALS[code];
149
173
  }
@@ -177,7 +201,7 @@ export function readRouterRefusal(status, body) {
177
201
  else {
178
202
  return null;
179
203
  }
180
- const refusal = { kind, code: name, status, message: said || fallback };
204
+ const refusal = { kind, code: name, status, message: ownWords ? fallback : said || fallback };
181
205
  if (fields.period === null || (typeof fields.period === 'string' && PERIODS.includes(fields.period)))
182
206
  refusal.period = fields.period;
183
207
  if (fields.resets_at === null)
@@ -365,7 +365,17 @@ export type StreamEvent = {
365
365
  stopReason: string;
366
366
  stopDetails?: Record<string, unknown>;
367
367
  };
368
+ export type BackendTurnOptions = Pick<BackendRequest, 'model' | 'maxTokens' | 'codexEffort' | 'routePlan' | 'signal'>;
369
+ export interface PreparedBackendTurn {
370
+ /** A turn-local backend. Shared parent/worker backends must remain unchanged. */
371
+ backend: AgentBackend;
372
+ options: BackendTurnOptions;
373
+ /** Catalog-aware identity check for replaying this managed model's history. */
374
+ isModelCompatible?: (model: string) => boolean;
375
+ }
368
376
  export interface AgentBackend {
377
+ /** Resolve host routing before callers encode history or budget context. */
378
+ prepareTurn?(options: BackendTurnOptions): Promise<PreparedBackendTurn | undefined>;
369
379
  /** Preserve ordered provider blocks and previously submitted context bytes. */
370
380
  readonly preservesNativeHistory?: boolean;
371
381
  getModelCapabilities?(model: string): import('../../utils/router_catalog.js').RouterModelCapabilities | undefined;