@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
@@ -1,6 +1,6 @@
1
1
  import type { RouterCatalog, RouterModelCapabilities } from '../../utils/router_catalog.js';
2
2
  import type { OpenRouterPreferences } from '../../config/types.js';
3
- import { AgentBackend, BackendRequest, BackendResponse, StreamEvent } from './types.js';
3
+ import { AgentBackend, BackendRequest, BackendResponse, BackendTurnOptions, PreparedBackendTurn, RequestRefusedError, StreamEvent } from './types.js';
4
4
  export interface ZRouterStreamConfig {
5
5
  model?: string;
6
6
  catalog?: RouterCatalog;
@@ -23,6 +23,25 @@ export interface ZRouterStreamConfig {
23
23
  clientName?: string;
24
24
  /** Read on every request, so a changed preference applies to the next one. */
25
25
  openRouterPreferences?: () => OpenRouterPreferences | undefined;
26
+ /** The provider's name when Router's catalog gives none, for what a refusal says. */
27
+ providerLabel?: string;
28
+ /**
29
+ * Router's Credentials page for this account, where a provider's API key goes, when the route is the person's own
30
+ * Router sign-in: a refusal for want of a key links it.
31
+ */
32
+ credentialsUrl?: string;
33
+ /**
34
+ * The person's own Zerg Router sign-in as the profile holds it now, read for every request when the route runs on it.
35
+ * Router retires this computer's previous device key at every login, so a login made in another pane (or `ztc auth
36
+ * login`) since this backend was built is the one sent, with its account. With none now (signed out, or expired),
37
+ * what the request is refused with before anything is sent.
38
+ */
39
+ routerSignIn?: () => {
40
+ token: string;
41
+ workspaceId: string;
42
+ } | {
43
+ refused: string;
44
+ };
26
45
  }
27
46
  /**
28
47
  * Backend that streams LLM responses through ZRouter proxy.
@@ -34,6 +53,8 @@ export interface ZRouterStreamConfig {
34
53
  export declare class ZRouterStreamBackend implements AgentBackend {
35
54
  readonly preservesNativeHistory: boolean;
36
55
  private readonly initialCatalog?;
56
+ private policyCatalog?;
57
+ private hostPolicyPrepared;
37
58
  private get catalog();
38
59
  private apiKey;
39
60
  private proxyUrl;
@@ -43,7 +64,22 @@ export declare class ZRouterStreamBackend implements AgentBackend {
43
64
  private conversationId?;
44
65
  private clientName;
45
66
  private openRouterPreferences?;
67
+ private readonly providerLabel?;
68
+ private readonly credentialsUrl?;
69
+ private readonly routerSignIn?;
70
+ private readonly config;
46
71
  constructor(config: ZRouterStreamConfig);
72
+ /**
73
+ * The key and account a request goes with: the person's sign-in as the profile holds it now, else the backend's own.
74
+ * A route on that sign-in with none now is refused before anything is sent.
75
+ */
76
+ private signIn;
77
+ /** The sign-in Router's catalog and the refusal gate are keyed by: the current one, else the backend's own. */
78
+ private signInNow;
79
+ /** On the person's own sign-in, the provider a 401 inside a turn is worded with (see routerFailure); otherwise none. */
80
+ private signInTarget;
81
+ /** What a refusal is worded with: this backend's provider, by the name Router's catalog gives it, and its link. */
82
+ private refusalRequest;
47
83
  private endpointFor;
48
84
  isAuthenticationConfigured(): boolean;
49
85
  allowsBufferedFallbackAfterStreamFailure(): boolean;
@@ -86,6 +122,8 @@ export declare class ZRouterStreamBackend implements AgentBackend {
86
122
  * the host-selected workspace; a fixed key is its own fingerprint.
87
123
  */
88
124
  private gateTarget;
125
+ private hostPolicyTurn;
126
+ prepareTurn(options: BackendTurnOptions): Promise<PreparedBackendTurn | undefined>;
89
127
  generate(request: BackendRequest): Promise<BackendResponse>;
90
128
  private generateResponse;
91
129
  private parseOpenAIResponse;
@@ -94,3 +132,12 @@ export declare class ZRouterStreamBackend implements AgentBackend {
94
132
  private gatedStream;
95
133
  private streamResponse;
96
134
  }
135
+ /**
136
+ * A 401 on the person's own Zerg Router sign-in, worded by whose it was: shown as written and never retried, like a
137
+ * refusal. Router checks a request's sign-in before it starts the turn, so its own 401 means it didn't accept this
138
+ * ZTC's sign-in, and nothing reached a provider; one inside a turn it started (a router_error frame), or one it passed on
139
+ * from the provider as it came, is the provider's, turning away the key Router holds for it.
140
+ */
141
+ export declare class RouterAuthenticationError extends RequestRefusedError {
142
+ readonly status = 401;
143
+ }
@@ -1,5 +1,5 @@
1
1
  import { modelContract, normalizeContractModel } from '@zerg/model-contracts';
2
- import { readRouterCatalog, resolveRouterModel } from '../../utils/router_catalog.js';
2
+ import { fetchRouterCatalog, readRouterCatalog, resolveRouterModel } from '../../utils/router_catalog.js';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { measureResponse, measureStream } from './request_metrics.js';
5
5
  import { BackendHttpError, readHttpErrorBody, retryAfterDelayMs } from './http_error.js';
@@ -15,9 +15,12 @@ import { getVersion } from '../../utils/version.js';
15
15
  import { IncompleteStreamError, isTransportError } from './transport_errors.js';
16
16
  import { OpenAIResponsesBackend } from './openai_responses.js';
17
17
  import { endingRouterRefusal, readRouterRefusal, RouterRefusalError } from './router_refusal.js';
18
+ import { rejectedRouterKeyMessage, routerProviderLabel } from './router_keys.js';
19
+ import { ROUTER_SIGN_IN_REJECTED } from '../../router_auth.js';
18
20
  import { routerAccount, routerRefusalGate } from './router_gate.js';
19
21
  import { countRouterRequests } from './router_requests.js';
20
22
  import { requiredRouterModel } from '../../config/router_required.js';
23
+ import { applyHostEffortPolicy } from './host_effort_policy.js';
21
24
  const ZROUTER_HEADERS_TIMEOUT_MS = 90_000;
22
25
  // A process session is descriptive telemetry, never a registered machine identity.
23
26
  const routerClientSession = randomUUID();
@@ -32,6 +35,19 @@ const PINNABLE_DECORATION = /^[A-Za-z0-9._:-]{1,64}$/;
32
35
  function isPinnableDecoration(value) {
33
36
  return value !== undefined && PINNABLE_DECORATION.test(value);
34
37
  }
38
+ /** Catalog identity wins; legacy namespace aliases never fold opaque ID case. */
39
+ function sameRouterModel(catalog, provider, previous, selected) {
40
+ const resolved = catalog && resolveRouterModel(catalog, provider, previous);
41
+ if (resolved)
42
+ return resolved.id === selected;
43
+ const unprefix = (model) => {
44
+ let id = model.startsWith(`${provider}/`) ? model.slice(provider.length + 1) : model;
45
+ if (provider === 'fireworks' && id.startsWith('accounts/fireworks/models/'))
46
+ id = id.slice('accounts/fireworks/models/'.length);
47
+ return id;
48
+ };
49
+ return unprefix(previous) === unprefix(selected);
50
+ }
35
51
  // Allow Router restarts to recover through bounded, cancellable retries. Each
36
52
  // reconnect reports progress and resumes the same turn/cursor. Hosts can tune
37
53
  // the attempt count and backoff through the environment.
@@ -84,8 +100,10 @@ function routerLimits(profile, model) {
84
100
  export class ZRouterStreamBackend {
85
101
  preservesNativeHistory;
86
102
  initialCatalog;
103
+ policyCatalog;
104
+ hostPolicyPrepared = false;
87
105
  get catalog() {
88
- return readRouterCatalog({ origin: this.proxyUrl, token: this.apiKey, workspaceId: this.workspaceId }) ?? this.initialCatalog;
106
+ return this.policyCatalog ?? readRouterCatalog({ origin: this.proxyUrl, ...this.signInNow() }) ?? this.initialCatalog;
89
107
  }
90
108
  apiKey;
91
109
  proxyUrl;
@@ -95,7 +113,12 @@ export class ZRouterStreamBackend {
95
113
  conversationId;
96
114
  clientName;
97
115
  openRouterPreferences;
116
+ providerLabel;
117
+ credentialsUrl;
118
+ routerSignIn;
119
+ config;
98
120
  constructor(config) {
121
+ this.config = { ...config };
99
122
  this.preservesNativeHistory = config.provider === 'openai' && config.model === 'gpt-6.1-sol';
100
123
  this.initialCatalog = config.catalog ? structuredClone(config.catalog) : undefined;
101
124
  this.apiKey = config.apiKey;
@@ -106,6 +129,41 @@ export class ZRouterStreamBackend {
106
129
  this.conversationId = normalizeHeaderValue(config.conversationId, 'conversation id', 128);
107
130
  this.clientName = normalizeHeaderValue(config.clientName ?? 'ztc', 'client name', 64);
108
131
  this.openRouterPreferences = config.openRouterPreferences;
132
+ this.providerLabel = config.providerLabel;
133
+ this.credentialsUrl = config.credentialsUrl;
134
+ this.routerSignIn = config.routerSignIn;
135
+ }
136
+ /**
137
+ * The key and account a request goes with: the person's sign-in as the profile holds it now, else the backend's own.
138
+ * A route on that sign-in with none now is refused before anything is sent.
139
+ */
140
+ signIn() {
141
+ const current = this.routerSignIn?.();
142
+ if (current && 'refused' in current)
143
+ throw new RequestRefusedError(current.refused);
144
+ return current ? { token: current.token, workspaceId: normalizeHeaderValue(current.workspaceId, 'workspace id', 128) }
145
+ : { token: this.apiKey, workspaceId: this.workspaceId };
146
+ }
147
+ /** The sign-in Router's catalog and the refusal gate are keyed by: the current one, else the backend's own. */
148
+ signInNow() {
149
+ try {
150
+ return this.signIn();
151
+ }
152
+ catch {
153
+ return { token: this.apiKey, workspaceId: this.workspaceId };
154
+ }
155
+ }
156
+ /** On the person's own sign-in, the provider a 401 inside a turn is worded with (see routerFailure); otherwise none. */
157
+ signInTarget() {
158
+ if (!this.routerSignIn)
159
+ return undefined;
160
+ const { provider, providerLabel, credentialsUrl } = this.refusalRequest();
161
+ return { provider, label: providerLabel, credentialsUrl };
162
+ }
163
+ /** What a refusal is worded with: this backend's provider, by the name Router's catalog gives it, and its link. */
164
+ refusalRequest() {
165
+ const providerLabel = routerProviderLabel(this.catalog, this.provider) ?? this.providerLabel;
166
+ return { provider: this.provider, ...(providerLabel ? { providerLabel } : {}), ...(this.credentialsUrl ? { credentialsUrl: this.credentialsUrl } : {}) };
109
167
  }
110
168
  endpointFor() {
111
169
  return `${this.proxyUrl}/v1/chat/completions`;
@@ -120,6 +178,10 @@ export class ZRouterStreamBackend {
120
178
  return true;
121
179
  }
122
180
  allowsRequestRetryAfterFailure(request) {
181
+ // A prepared turn holds its policy snapshot, so a retry resends the same route. Only an unprepared backend
182
+ // would read the policy again mid-request.
183
+ if (process.env.ZTC_EFFORT_POLICY_URL && !this.hostPolicyPrepared)
184
+ return false;
123
185
  return !this.usesNativeResponses(request);
124
186
  }
125
187
  usesNativeResponses(request) {
@@ -294,9 +356,9 @@ export class ZRouterStreamBackend {
294
356
  return serialized;
295
357
  }
296
358
  async buildHeaders(request) {
297
- const token = this.authTokenProvider
298
- ? await this.authTokenProvider()
299
- : this.apiKey;
359
+ const { token, workspaceId } = this.authTokenProvider
360
+ ? { token: await this.authTokenProvider(), workspaceId: this.workspaceId }
361
+ : this.signIn();
300
362
  const normalizedToken = normalizeHeaderValue(token, 'authorization token', 16_384);
301
363
  if (!normalizedToken) {
302
364
  throw new Error('ZRouter authorization token provider returned an empty token');
@@ -310,7 +372,7 @@ export class ZRouterStreamBackend {
310
372
  'X-Zerg-Client-Version': getVersion(),
311
373
  'X-Zerg-Client-Platform': process.platform,
312
374
  'X-Zerg-Client-Session': routerClientSession,
313
- ...(this.workspaceId ? { 'X-Zerg-Workspace-ID': this.workspaceId } : {}),
375
+ ...(workspaceId ? { 'X-Zerg-Workspace-ID': workspaceId } : {}),
314
376
  ...(conversationPin ? { 'X-Zerg-Conversation-ID': conversationPin } : {}),
315
377
  };
316
378
  }
@@ -348,17 +410,84 @@ export class ZRouterStreamBackend {
348
410
  */
349
411
  gateTarget(request) {
350
412
  return { route: this.proxyUrl, provider: this.provider, model: request.model,
351
- account: this.authTokenProvider ? `host:${this.workspaceId ?? ''}` : routerAccount(this.apiKey) };
413
+ account: this.authTokenProvider ? `host:${this.workspaceId ?? ''}` : routerAccount(this.signInNow().token) };
414
+ }
415
+ async hostPolicyTurn(request) {
416
+ if (this.hostPolicyPrepared)
417
+ return { backend: this, request };
418
+ let backend = this;
419
+ const effective = await applyHostEffortPolicy(request, async (model) => {
420
+ if (model) {
421
+ // A route on the person's own sign-in with none now is refused here, as its request would be.
422
+ const own = this.authTokenProvider ? undefined : this.signIn();
423
+ let catalog;
424
+ try {
425
+ const signIn = own ?? { token: await this.authTokenProvider(), workspaceId: this.workspaceId };
426
+ catalog = await fetchRouterCatalog({ origin: this.proxyUrl, ...signIn }, request.signal, model.provider);
427
+ }
428
+ catch {
429
+ request.signal?.throwIfAborted();
430
+ throw new Error('Host model policy could not verify model access. Check this resident’s Router connection and refresh the catalog.');
431
+ }
432
+ const descriptor = catalog.version === 1 ? resolveRouterModel(catalog, model.provider, model.model) : undefined;
433
+ if (!descriptor || descriptor.available === false || !descriptor.capabilities?.chat || descriptor.capabilities.tools !== true) {
434
+ throw new Error('Host model policy requires an accessible Router chat model with tool support. Ask the platform administrator to choose another model.');
435
+ }
436
+ // Scope the route to this turn. Never mutate a backend shared by concurrent callers. The name ZTC gave the
437
+ // pane's provider is that provider's alone: another one is named by Router's catalog, else by its id.
438
+ backend = new ZRouterStreamBackend({ ...this.config, provider: model.provider, model: descriptor.id, catalog,
439
+ providerLabel: model.provider === this.provider ? this.providerLabel : undefined,
440
+ openRouterPreferences: () => {
441
+ const preferences = this.openRouterPreferences?.();
442
+ // A variant changes the exact model ID. Preserve privacy, price and provider restrictions.
443
+ return preferences ? { ...preferences, variant: undefined } : undefined;
444
+ } });
445
+ backend.policyCatalog = catalog;
446
+ const changed = this.provider !== model.provider
447
+ || !sameRouterModel(catalog, model.provider, request.model, descriptor.id);
448
+ request = { ...request, model: descriptor.id, routePlan: undefined,
449
+ // Direct callers still need this guard. Prepared agents encode with
450
+ // the selected model themselves; unchanged routes keep native state.
451
+ messages: !changed ? request.messages : request.messages.map(message => ({ ...message, responseItems: undefined, reasoning: undefined,
452
+ content: typeof message.content === 'string' ? message.content : message.content
453
+ .filter(block => block.type !== 'responses_reasoning' && block.type !== 'thinking' && block.type !== 'redacted_thinking')
454
+ .map(block => block.type === 'tool_use' ? { ...block, responsesItem: undefined } : block) })),
455
+ ...(request.maxTokens !== undefined && descriptor.capabilities.max_output_tokens !== undefined
456
+ ? { maxTokens: Math.min(request.maxTokens, descriptor.capabilities.max_output_tokens) } : {}) };
457
+ runtimeDiag('info', `[ztc] host model policy ${JSON.stringify({ provider: model.provider, model: descriptor.id })}`);
458
+ }
459
+ const descriptor = backend.catalog ? resolveRouterModel(backend.catalog, backend.provider, request.model) : undefined;
460
+ const supported = backend.usesNativeResponses(request)
461
+ ? modelContract('openai', request.model)?.reasoningEfforts
462
+ : descriptor?.capabilities ? descriptor.capabilities.reasoning?.choices ?? []
463
+ : modelContract(backend.provider, request.model, 'chat_tools')?.reasoningEfforts;
464
+ return { request, supported };
465
+ });
466
+ return { backend, request: effective };
467
+ }
468
+ async prepareTurn(options) {
469
+ if (!process.env.ZTC_EFFORT_POLICY_URL && !process.env.ZTC_EFFORT_POLICY_TOKEN)
470
+ return undefined;
471
+ const turn = await this.hostPolicyTurn({ ...options, system: '', messages: [], tools: [] });
472
+ // Even effort-only/inherit policies get an isolated snapshot. Dispatch must
473
+ // not fetch a newer policy after the caller has encoded and budgeted it.
474
+ const backend = turn.backend === this ? new ZRouterStreamBackend({ ...this.config, catalog: this.catalog }) : turn.backend;
475
+ backend.policyCatalog = turn.backend.catalog;
476
+ backend.hostPolicyPrepared = true;
477
+ return { backend, options: { model: turn.request.model, maxTokens: turn.request.maxTokens,
478
+ codexEffort: turn.request.codexEffort, routePlan: turn.request.routePlan, signal: options.signal },
479
+ isModelCompatible: model => sameRouterModel(backend.catalog, backend.provider, model, turn.request.model) };
352
480
  }
353
481
  generate(request) {
354
482
  const routedRequest = withTransportTurn(request);
355
483
  return measureResponse(routedRequest, async (fetcher) => {
356
- const target = this.gateTarget(routedRequest);
484
+ const turn = await this.hostPolicyTurn(routedRequest);
485
+ const target = turn.backend.gateTarget(turn.request);
357
486
  const held = routerRefusalGate.admit(target, { person: routedRequest.personInitiated === true });
358
487
  if (held)
359
488
  throw held;
360
489
  try {
361
- const response = await this.generateResponse(routedRequest, countRouterRequests(fetcher));
490
+ const response = await turn.backend.generateResponse(turn.request, countRouterRequests(fetcher));
362
491
  routerRefusalGate.succeed(target);
363
492
  return response;
364
493
  }
@@ -376,7 +505,7 @@ export class ZRouterStreamBackend {
376
505
  return await native.backend.generate(native.request);
377
506
  }
378
507
  catch (error) {
379
- throw nativeRouterFailure(error);
508
+ throw nativeRouterFailure(error, this.refusalRequest(), this.signInTarget());
380
509
  }
381
510
  finally {
382
511
  native.dispose();
@@ -399,7 +528,8 @@ export class ZRouterStreamBackend {
399
528
  });
400
529
  if (!response.ok) {
401
530
  const failure = await readHttpErrorBody(response, request.signal);
402
- throw routerFailure(response.status, failure.body, { headers, response, bodyReadState: failure.bodyReadState });
531
+ throw routerFailure(response.status, failure.body, { headers, response, bodyReadState: failure.bodyReadState, request: this.refusalRequest(),
532
+ ownSignIn: this.signInTarget() });
403
533
  }
404
534
  const data = await response.json();
405
535
  const parsed = this.parseOpenAIResponse(data);
@@ -452,13 +582,15 @@ export class ZRouterStreamBackend {
452
582
  }
453
583
  /** A stream the process gate admits; Router answering with output clears whatever held it. */
454
584
  async *gatedStream(request, fetcher) {
455
- const target = this.gateTarget(request);
585
+ const turn = await this.hostPolicyTurn(request);
586
+ request = turn.request;
587
+ const target = turn.backend.gateTarget(request);
456
588
  const held = routerRefusalGate.admit(target, { person: request.personInitiated === true });
457
589
  if (held)
458
590
  throw held;
459
591
  let answered = false;
460
592
  try {
461
- for await (const event of this.streamResponse(request, countRouterRequests(fetcher))) {
593
+ for await (const event of turn.backend.streamResponse(request, countRouterRequests(fetcher))) {
462
594
  if (!answered && event.type !== 'heartbeat') {
463
595
  answered = true;
464
596
  routerRefusalGate.succeed(target);
@@ -479,7 +611,7 @@ export class ZRouterStreamBackend {
479
611
  yield* native.backend.generateStream(native.request);
480
612
  }
481
613
  catch (error) {
482
- throw nativeRouterFailure(error);
614
+ throw nativeRouterFailure(error, this.refusalRequest(), this.signInTarget());
483
615
  }
484
616
  finally {
485
617
  native.dispose();
@@ -512,7 +644,8 @@ export class ZRouterStreamBackend {
512
644
  }, Math.min(ZROUTER_HEADERS_TIMEOUT_MS, Math.max(1, remaining())));
513
645
  if (!response.ok) {
514
646
  const failure = await readHttpErrorBody(response, request.signal);
515
- throw routerFailure(response.status, routerErrorFrameBody(failure.body), { headers, response, bodyReadState: failure.bodyReadState });
647
+ throw routerFailure(response.status, routerErrorFrameBody(failure.body), { headers, response, bodyReadState: failure.bodyReadState,
648
+ request: this.refusalRequest(), ownSignIn: this.signInTarget() });
516
649
  }
517
650
  if (!response.body) {
518
651
  throw new Error('ZRouter API error: no response body for streaming request');
@@ -541,7 +674,8 @@ export class ZRouterStreamBackend {
541
674
  ? suppliedStatus
542
675
  : 502;
543
676
  routerTurnEnded = true;
544
- throw routerFailure(status, JSON.stringify(ev.body ?? {}), { headers, turnEnded: true });
677
+ throw routerFailure(status, JSON.stringify(ev.body ?? {}), { headers, turnEnded: true, request: this.refusalRequest(),
678
+ ownSignIn: this.signInTarget() });
545
679
  }
546
680
  const mapped = mapEvent(ev);
547
681
  if (this.getModelCapabilities(request.model)?.tools === false && mapped.some(event => event.type.startsWith('tool_use'))) {
@@ -672,14 +806,65 @@ function failureHeaderSuffix(response) {
672
806
  }
673
807
  return parts.length > 0 ? ` [${parts.join(' ')}]` : '';
674
808
  }
809
+ /**
810
+ * A 401 on the person's own Zerg Router sign-in, worded by whose it was: shown as written and never retried, like a
811
+ * refusal. Router checks a request's sign-in before it starts the turn, so its own 401 means it didn't accept this
812
+ * ZTC's sign-in, and nothing reached a provider; one inside a turn it started (a router_error frame), or one it passed on
813
+ * from the provider as it came, is the provider's, turning away the key Router holds for it.
814
+ */
815
+ export class RouterAuthenticationError extends RequestRefusedError {
816
+ status = 401;
817
+ }
818
+ /** Whether a Router error body is an authentication_error, in either of its envelopes. */
819
+ function authenticationErrorBody(body) {
820
+ try {
821
+ const parsed = JSON.parse(body);
822
+ return parsed?.error?.type === 'authentication_error';
823
+ }
824
+ catch {
825
+ return false;
826
+ }
827
+ }
828
+ /**
829
+ * Whether BODY, an authentication failure Router answered with, is Router's own refusal of this ZTC's sign-in rather
830
+ * than a provider's 401 it passes on as it came (its native Responses route, and a chat request that isn't its resumable
831
+ * ZTC stream, do). Router's own is h3's envelope (statusCode, statusMessage), an error it says reached no provider, or on
832
+ * the native route (NATIVE) the authentication_error that route words a refusal of its own with; a body that isn't JSON
833
+ * is no provider's. An error Router says it sent on to the provider is the provider's.
834
+ */
835
+ function routersOwnAuthenticationFailure(body, native) {
836
+ let parsed;
837
+ try {
838
+ parsed = JSON.parse(body);
839
+ }
840
+ catch {
841
+ return true;
842
+ }
843
+ if (!parsed || typeof parsed !== 'object')
844
+ return true;
845
+ const { statusCode, statusMessage, error } = parsed;
846
+ if (typeof statusCode === 'number' && typeof statusMessage === 'string')
847
+ return true;
848
+ const failure = error && typeof error === 'object' ? error : undefined;
849
+ if (failure?.provider_dispatched !== undefined)
850
+ return failure.provider_dispatched === false;
851
+ return native && failure?.type === 'authentication_error';
852
+ }
675
853
  /**
676
854
  * The error a failed Router response, or a router_error frame, throws. A lasting refusal (a spending, token or access
677
855
  * limit, the monthly quota, a platform key out of credit, the platform proxy's own quota) or a provider cooldown
678
- * longer than a turn waits becomes a RouterRefusalError, which nothing retries. Any other failure stays a
679
- * BackendHttpError, carrying the wait a refusal's body names when no Retry-After header did: the platform proxy drops
680
- * Router's headers, and a frame has none.
856
+ * longer than a turn waits becomes a RouterRefusalError, which nothing retries. On the person's own sign-in
857
+ * (`ownSignIn`) a 401 becomes a RouterAuthenticationError. Any other failure stays a BackendHttpError, carrying the
858
+ * wait a refusal's body names when no Retry-After header did: the platform proxy drops Router's headers, and a frame
859
+ * has none.
681
860
  */
682
861
  function routerFailure(status, body, options) {
862
+ if (options.ownSignIn && (status === 401 || authenticationErrorBody(body))) {
863
+ // Router's own refusal of this ZTC's sign-in, before anything reached a provider; else the provider's, inside a turn
864
+ // Router started or passed on as it came.
865
+ const signInRefused = !options.turnEnded && routersOwnAuthenticationFailure(body, options.native === true);
866
+ return new RouterAuthenticationError(signInRefused ? ROUTER_SIGN_IN_REJECTED : rejectedRouterKeyMessage(options.ownSignIn));
867
+ }
683
868
  const header = options.response?.headers.get('retry-after') ?? null;
684
869
  const httpError = (retryAfter) => {
685
870
  const error = new BackendHttpError(status, body, { prefix: 'ZRouter API', headers: options.headers, bodyReadState: options.bodyReadState,
@@ -690,7 +875,7 @@ function routerFailure(status, body, options) {
690
875
  };
691
876
  const error = httpError(header);
692
877
  // Read from the redacted body: only its fixed fields and cleaned sentence are used.
693
- const refusal = readRouterRefusal(error.status, error.body);
878
+ const refusal = readRouterRefusal(error.status, error.body, options.request);
694
879
  if (!refusal)
695
880
  return error;
696
881
  const ending = endingRouterRefusal(refusal);
@@ -698,13 +883,19 @@ function routerFailure(status, body, options) {
698
883
  return ending;
699
884
  return header === null && refusal.retryAfterSeconds !== undefined ? httpError(String(refusal.retryAfterSeconds)) : error;
700
885
  }
701
- /** Router's refusal of a native Responses request, which that transport reports as `API error (NNN): body`. */
702
- function nativeRouterFailure(error) {
886
+ /**
887
+ * Router's refusal of a native Responses request, which that transport reports as `API error (NNN): body`. A refusal and
888
+ * an authentication failure are said as Router's, whoever's credential the request went with: never as the provider's
889
+ * own key, which ZTC didn't send. Any other failure keeps the native transport's own words.
890
+ */
891
+ function nativeRouterFailure(error, request, ownSignIn) {
703
892
  const failure = error instanceof Error ? /^API error \((\d{3})\): ([\s\S]*)$/.exec(error.message) : null;
704
893
  if (!failure)
705
894
  return error;
706
- const converted = routerFailure(Number(failure[1]), failure[2], { headers: {} });
707
- return converted instanceof RouterRefusalError ? converted : error;
895
+ const status = Number(failure[1]);
896
+ const converted = routerFailure(status, failure[2], { headers: {}, request, ownSignIn, native: true });
897
+ const unauthenticated = status === 401 || authenticationErrorBody(failure[2]);
898
+ return converted instanceof RouterRefusalError || converted instanceof RouterAuthenticationError || unauthenticated ? converted : error;
708
899
  }
709
900
  /**
710
901
  * A failed streamed turn can answer with an SSE router_error frame instead of a JSON body. Its body is the same error
@@ -8,10 +8,12 @@
8
8
  * is the opening prompt; text starting with a flag is the CLI's arguments.
9
9
  */
10
10
  import { getMuxTransport } from '../tools/pane.js';
11
+ import { ToolCapability } from '../runtime/capabilities.js';
11
12
  import { AGENT_CLIS, findAgentCli, formatCliArguments, parseAgentCommandBody, workspaceMcpProgram, } from '../../panes/agent_cli.js';
12
13
  import { openAgentPane } from '../../panes/agent_panes.js';
13
- function shownCommand(binary, request) {
14
- const words = [...request.words, ...(request.prompt ? ['--', request.prompt] : [])];
14
+ /** The command as the person reads it: the permission flag ZTC added, then their own words and prompt. */
15
+ function shownCommand(binary, request, permissionArgs = []) {
16
+ const words = [...permissionArgs, ...request.words, ...(request.prompt ? ['--', request.prompt] : [])];
15
17
  return words.length > 0 ? `${binary} ${formatCliArguments(words)}` : binary;
16
18
  }
17
19
  export function createAgentCliCommand(id, deps = {}) {
@@ -22,6 +24,8 @@ export function createAgentCliCommand(id, deps = {}) {
22
24
  description: `Open ${spec.label} in a new pane, signed in with your own ${account} account`,
23
25
  usage: '[prompt | flags]',
24
26
  agentRunnable: true,
27
+ // The CLI runs commands, so an agent's permission profile governs opening it as it governs a shell.
28
+ agentCapabilities: [ToolCapability.SHELL_EXEC],
25
29
  category: 'panes',
26
30
  handler: async (args, ctx) => {
27
31
  let request;
@@ -49,6 +53,10 @@ export function createAgentCliCommand(id, deps = {}) {
49
53
  server: (deps.server ?? workspaceMcpProgram)(),
50
54
  env: (deps.env ?? (() => process.env))(),
51
55
  ...(deps.motsi ? { motsi: deps.motsi() } : {}),
56
+ // The ztc_command tool runs commands as the agent ('agent'). What the person types in a ZTC pane reaches it as
57
+ // relayed input, so relayed is theirs here: what else types there (write_terminal_pane, a pane's message) is
58
+ // an agent already allowed to run commands, or a pane that can open a shell of its own.
59
+ openedBy: ctx.commandOrigin === 'agent' ? 'agent' : 'person',
52
60
  });
53
61
  if (result.error) {
54
62
  ctx.addMessage({ role: 'system', content: result.error });
@@ -56,7 +64,7 @@ export function createAgentCliCommand(id, deps = {}) {
56
64
  }
57
65
  ctx.addMessage({
58
66
  role: 'system',
59
- content: `Opened ${result.title} in pane ${result.paneId} (${cwd}): ${shownCommand(spec.binary, request)}`,
67
+ content: `Opened ${result.title} in pane ${result.paneId} (${cwd}): ${shownCommand(spec.binary, request, result.permissionArgs)}`,
60
68
  });
61
69
  if (result.notice)
62
70
  ctx.addMessage({ role: 'system', content: result.notice });
@@ -16,6 +16,7 @@ import { API_KEY_PROVIDER_CHOICES, canonicalProvider, describeKeySource, isLocal
16
16
  import { canAskForCredential, manageApiKey, promptForMissingDirectKey, removeApiKey, savedKeyNotes, useApiKeyVariable, } from './direct_credential_prompt.js';
17
17
  import { looksLikeApiKeyEnvName } from '../../config/provider_api_key_env.js';
18
18
  import { offerKeyedProviderSwitch, ownRouteModelSelection, selectProviderModel } from './provider_selection.js';
19
+ import { keylessRouterModelRefusal } from './router_availability.js';
19
20
  import { connectionStatusLines } from './credential_status.js';
20
21
  import { normalizeProviderId } from '../backends/provider_ids.js';
21
22
  import { unsupportedCodexEffort } from '../../config/defaults.js';
@@ -273,6 +274,17 @@ async function setConfigModel(value, ctx, credentialPrompted = false) {
273
274
  ctx.addMessage({ role: 'system', content: unbuildableSelectionMessage(activeProvider, llm, ctx.config) });
274
275
  return;
275
276
  }
277
+ // A model Router has no key for is refused with where the key goes, once Router has been asked again.
278
+ if (llm.useProxy) {
279
+ const listCatalog = ctx.models.catalog;
280
+ const origin = ctx.config.getPersonalRouterCredential?.()?.origin;
281
+ const refusal = await keylessRouterModelRefusal(llm.provider, value, { catalog: ctx.config.getRouterCatalog?.(),
282
+ ...(listCatalog ? { refresh: () => listCatalog(undefined, { refresh: true }) } : {}), ...(origin ? { origin } : {}) });
283
+ if (refusal) {
284
+ ctx.addMessage({ role: 'system', content: `✗ ${refusal} Keeping the current selection.` });
285
+ return;
286
+ }
287
+ }
276
288
  ctx.config.set('model', value);
277
289
  await ctx.config.save();
278
290
  applyRuntimeModelSelection(ctx, activeProvider, value);
@@ -32,6 +32,7 @@ import { reloadCommand, restartCommand } from './restart.js';
32
32
  import { initCommand } from './init.js';
33
33
  import { forkCommand, sideCommand } from './fork.js';
34
34
  import { claudeCommand, codexCommand } from './agent_cli.js';
35
+ import { ztcPaneCommand } from './ztc_pane.js';
35
36
  import { subsCommand } from './subs.js';
36
37
  import { diffCommand } from './diff.js';
37
38
  import { rawCommand } from './raw.js';
@@ -85,7 +86,7 @@ import { effortCommand, thinkingCommand, reasoningCommand, fastCommand } from '.
85
86
  import { runtimePluginRegistry } from '../../plugin/runtime_registry.js';
86
87
  const commandList = [];
87
88
  const helpCommand = makeHelpCommand(() => commandList);
88
- commandList.push(helpCommand, authCommand, loginCommand, logoutCommand, accountsCommand, zergCommand, zergsCommand, configCommand, debugCommand, clearCommand, handoffCommand, statusCommand, runtimeCommand, environmentCommand, jobCommand, shareCommand, hooksCommand, emulationCommand, shellCommand, cdCommand, clipboardCommand, modelsCommand, modelCommand, providerCommand, permissionsCommand, resourcesCommand, initCommand, forkCommand, sideCommand, claudeCommand, codexCommand, subsCommand, diffCommand, rawCommand, themeCommand, doctorCommand, intentCommand, profileCommand, skillsCommand, runbooksCommand, keybindingsCommand, keymapCommand, shortcutsCommand, updateCommand, desktopCommand, layoutCommand, setupCommand, connectCommand, keysCommand, restartCommand, reloadCommand, inputModeCommand, retryCommand, dictationStatusCommand, embeddedCommand, benchCommand, voiceCommand, sfxCommand, compactCommand, automodeCommand, sessionsCommand, resumeCommand, rewindCommand, renameCommand, labelCommand, inboxCommand, attentionCommand, contextCommand, evidenceCommand, boardCommand, usageCommand, shannonRunnerCommand, planCommand, executeCommand, modeCommand, modeListCommand, exitModeCommand, validateCommand, previewCommand, saveCommand, dcaigCommand, manifestCommand, swarmCommand, swarmStopCommand, swarmStatusCommand, superviseCommand, superviseStopCommand, superviseStatusCommand, zlickyCommand, zlickyStopCommand, zlickyStatusCommand, zlickyActCommand, zlickyPresenceCommand, zlickyPttCommand, simCommand, simStopCommand, simStatusCommand, simRunCommand, simCheckpointCommand, simResumeCommand, evolveCommand, evolveStopCommand, evolveStatusCommand, evolveBestCommand, optimizeCommand, batchCommand, batchStatusCommand, batchStopCommand, workflowsCommand, mirrorCommand, settingsCommand, mcpCommand, loopCommand, goalCommand, effortCommand, thinkingCommand, reasoningCommand, fastCommand, exitCommand);
89
+ commandList.push(helpCommand, authCommand, loginCommand, logoutCommand, accountsCommand, zergCommand, zergsCommand, configCommand, debugCommand, clearCommand, handoffCommand, statusCommand, runtimeCommand, environmentCommand, jobCommand, shareCommand, hooksCommand, emulationCommand, shellCommand, cdCommand, clipboardCommand, modelsCommand, modelCommand, providerCommand, permissionsCommand, resourcesCommand, initCommand, forkCommand, sideCommand, claudeCommand, codexCommand, ztcPaneCommand, subsCommand, diffCommand, rawCommand, themeCommand, doctorCommand, intentCommand, profileCommand, skillsCommand, runbooksCommand, keybindingsCommand, keymapCommand, shortcutsCommand, updateCommand, desktopCommand, layoutCommand, setupCommand, connectCommand, keysCommand, restartCommand, reloadCommand, inputModeCommand, retryCommand, dictationStatusCommand, embeddedCommand, benchCommand, voiceCommand, sfxCommand, compactCommand, automodeCommand, sessionsCommand, resumeCommand, rewindCommand, renameCommand, labelCommand, inboxCommand, attentionCommand, contextCommand, evidenceCommand, boardCommand, usageCommand, shannonRunnerCommand, planCommand, executeCommand, modeCommand, modeListCommand, exitModeCommand, validateCommand, previewCommand, saveCommand, dcaigCommand, manifestCommand, swarmCommand, swarmStopCommand, swarmStatusCommand, superviseCommand, superviseStopCommand, superviseStatusCommand, zlickyCommand, zlickyStopCommand, zlickyStatusCommand, zlickyActCommand, zlickyPresenceCommand, zlickyPttCommand, simCommand, simStopCommand, simStatusCommand, simRunCommand, simCheckpointCommand, simResumeCommand, evolveCommand, evolveStopCommand, evolveStatusCommand, evolveBestCommand, optimizeCommand, batchCommand, batchStatusCommand, batchStopCommand, workflowsCommand, mirrorCommand, settingsCommand, mcpCommand, loopCommand, goalCommand, effortCommand, thinkingCommand, reasoningCommand, fastCommand, exitCommand);
89
90
  export const commands = commandList;
90
91
  export function refreshPluginCommands() {
91
92
  const existing = new Set(commandList.map(command => command.name));
@@ -15,24 +15,34 @@ function validPort(port) {
15
15
  }
16
16
  /** What /mirror says when launching the browser is off, after the URL. */
17
17
  const BROWSER_OFF = 'Browser launch is off (ZTC_NO_BROWSER=1 or an automated run). Open the URL above yourself.';
18
+ /**
19
+ * Say CONTENT, which names the mirror's link, in this terminal only: the link can carry the mirror's credential, and
20
+ * the mirror serves its transcript to anyone on this computer while sign-in is off. Not saved with the session either.
21
+ */
22
+ function sayLink(ctx, content) {
23
+ ctx.addMessage({ role: 'system', content, metadata: { ephemeral: true, localOnly: true } });
24
+ }
18
25
  /**
19
26
  * Open the mirror in the browser and report it. `headline` names a started
20
- * mirror; a running one is named by its port. With browser launch off, the
21
- * URL is the result, so it is printed rather than failing the command.
27
+ * mirror, which also says once who can connect to it (accessNotice); a running
28
+ * one is named by its port. With browser launch off, the URL is the result, so
29
+ * it is printed rather than failing the command.
22
30
  */
23
31
  async function openMirror(ctx, params, headline) {
24
32
  const mirror = ctx.mirror;
25
33
  const url = mirror.getUrl(params);
34
+ const notice = headline ? mirror.accessNotice?.() : undefined;
35
+ const announced = `${url}${notice ? `\n${notice}` : ''}`;
26
36
  try {
27
37
  await mirror.open(params);
28
38
  }
29
39
  catch (error) {
30
40
  if (!(error instanceof BrowserLaunchOffError))
31
41
  throw error;
32
- ctx.addMessage({ role: 'system', content: `${headline ?? `Mirror running on port ${mirror.getPort()}`}\n${url}\n${BROWSER_OFF}` });
42
+ sayLink(ctx, `${headline ?? `Mirror running on port ${mirror.getPort()}`}\n${announced}\n${BROWSER_OFF}`);
33
43
  return;
34
44
  }
35
- ctx.addMessage({ role: 'system', content: headline ? `${headline}\n${url}` : `Opening mirror at ${url}` });
45
+ sayLink(ctx, headline ? `${headline}\n${announced}` : `Opening mirror at ${url}`);
36
46
  }
37
47
  export const mirrorCommand = {
38
48
  name: 'mirror',
@@ -76,7 +86,7 @@ export const mirrorCommand = {
76
86
  }
77
87
  const port = ctx.mirror.getPort();
78
88
  const url = ctx.mirror.getUrl();
79
- ctx.addMessage({ role: 'system', content: `Mirror running on port ${port}\n${url}` });
89
+ sayLink(ctx, `Mirror running on port ${port}\n${url}`);
80
90
  return;
81
91
  }
82
92
  case 'open': {