@zergai/ztc 0.20.0-beta.1 → 0.21.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 (43) hide show
  1. package/bin/zmux-darwin-arm64 +0 -0
  2. package/bin/ztc-audio-darwin-arm64 +0 -0
  3. package/bin/ztc-capture-darwin-arm64 +0 -0
  4. package/bin/ztc-tui-darwin-arm64 +0 -0
  5. package/bin/zterm-darwin-arm64 +2 -2
  6. package/dist/agent/commands/config.js +7 -1
  7. package/dist/agent/commands/model.js +9 -5
  8. package/dist/agent/commands/models.js +2 -4
  9. package/dist/agent/commands/provider.d.ts +12 -0
  10. package/dist/agent/commands/provider.js +38 -2
  11. package/dist/agent/commands/provider_selection.d.ts +24 -1
  12. package/dist/agent/commands/provider_selection.js +70 -36
  13. package/dist/agent/commands/runtime_model.d.ts +11 -2
  14. package/dist/agent/commands/runtime_model.js +23 -5
  15. package/dist/agent/commands/settings.js +12 -3
  16. package/dist/agent/commands/types.d.ts +24 -4
  17. package/dist/app/runtime_choices.d.ts +78 -1
  18. package/dist/app/runtime_choices.js +229 -0
  19. package/dist/app/runtime_choices_source.d.ts +45 -0
  20. package/dist/app/runtime_choices_source.js +127 -0
  21. package/dist/app/selection_completion.js +1 -14
  22. package/dist/cli_ratatui.d.ts +94 -16
  23. package/dist/cli_ratatui.js +510 -124
  24. package/dist/config/provider_models.d.ts +15 -0
  25. package/dist/config/provider_models.js +28 -0
  26. package/dist/config.d.ts +114 -4
  27. package/dist/config.js +306 -62
  28. package/dist/headless.js +13 -5
  29. package/dist/panes/pane_registry.d.ts +16 -1
  30. package/dist/panes/pane_registry.js +17 -0
  31. package/dist/panes/types.d.ts +14 -0
  32. package/dist/panes/ztc_launch.d.ts +3 -0
  33. package/dist/panes/ztc_launch.js +10 -7
  34. package/dist/simulation/toolkit/dynamic_meetings.d.ts +2 -2
  35. package/dist/simulation/toolkit/dynamic_story_review.d.ts +3 -3
  36. package/dist/ui/ratatui/pane_relay.d.ts +22 -1
  37. package/dist/ui/ratatui/pane_relay.js +57 -6
  38. package/dist/ui/ratatui/protocol.d.ts +97 -1
  39. package/dist/ui/ratatui/protocol.js +136 -6
  40. package/dist/utils/router_catalog_facts.d.ts +3 -0
  41. package/dist/utils/router_catalog_facts.js +14 -0
  42. package/dist/zlm-embed.mjs +275 -52
  43. package/package.json +16 -16
@@ -1,5 +1,20 @@
1
+ import type { NativeToolPaneRecord } from '../desktop/daily/native_tool.js';
1
2
  import type { MuxPaneState, MuxSessionState } from '../ui/ratatui/protocol.js';
2
- import type { PaneLaunchSpec, PaneRunStatus, PaneRuntimeRecord, PaneSessionSpec, PaneType } from './types.js';
3
+ import type { NativePaneLaunchSpec, PaneLaunchSpec, PaneRunStatus, PaneRuntimeRecord, PaneSessionSpec, PaneType } from './types.js';
4
+ /**
5
+ * Whether `pane` is a native interactive ZTC pane (#860's More… → ZTC in the New pane chooser): registered as a process
6
+ * pane, its launch spec its native record. A ZTC pane all the same, whose ZTC reports its own route; a delegated ZTC
7
+ * worker is not one.
8
+ */
9
+ export declare function isNativeZtcPane(pane: PaneRuntimeRecord | undefined): pane is PaneRuntimeRecord & {
10
+ launchSpec: NativePaneLaunchSpec;
11
+ };
12
+ /**
13
+ * The Zerg Router origin a native pane's record was launched with (its --router-url), if it names one: read from the
14
+ * record the desktop's native owner launched, since a record kept or saved is rebuilt from its recipe, without its
15
+ * launch flags.
16
+ */
17
+ export declare function nativeLaunchRouterOrigin(record: NativeToolPaneRecord): string | undefined;
3
18
  export declare function inferPaneSessionSpecFromMuxPane(pane: MuxPaneState): PaneSessionSpec | undefined;
4
19
  export declare function inferPaneSessionSpecsFromMuxState(muxState: MuxSessionState | undefined): PaneSessionSpec[];
5
20
  export declare function mergeSessionPaneSpecs(muxState: MuxSessionState | undefined, explicitSpecs: PaneSessionSpec[] | undefined): PaneSessionSpec[];
@@ -13,6 +13,23 @@ function parseFlagValue(args, flag) {
13
13
  }
14
14
  return undefined;
15
15
  }
16
+ /**
17
+ * Whether `pane` is a native interactive ZTC pane (#860's More… → ZTC in the New pane chooser): registered as a process
18
+ * pane, its launch spec its native record. A ZTC pane all the same, whose ZTC reports its own route; a delegated ZTC
19
+ * worker is not one.
20
+ */
21
+ export function isNativeZtcPane(pane) {
22
+ const launch = pane?.launchSpec?.kind === 'native_tool' ? pane.launchSpec.record.launch : undefined;
23
+ return launch?.tool === 'ztc' && launch.mode === 'interactive';
24
+ }
25
+ /**
26
+ * The Zerg Router origin a native pane's record was launched with (its --router-url), if it names one: read from the
27
+ * record the desktop's native owner launched, since a record kept or saved is rebuilt from its recipe, without its
28
+ * launch flags.
29
+ */
30
+ export function nativeLaunchRouterOrigin(record) {
31
+ return parseFlagValue(record.launch.args, '--router-url');
32
+ }
16
33
  function inferZtcLaunchSpec(pane) {
17
34
  const args = pane.args || [];
18
35
  let sessionMode = 'new';
@@ -55,6 +55,20 @@ export interface PaneRuntimeRecord {
55
55
  status: PaneRunStatus;
56
56
  lastError?: string;
57
57
  requestId?: string;
58
+ /**
59
+ * The provider, model and auth mode a native ZTC pane (#860's More… → ZTC) last reported running on. Its launch spec
60
+ * is its native record, which only the desktop's native owner writes, so the route it switched to is kept here.
61
+ */
62
+ reportedRoute?: {
63
+ provider: string;
64
+ model: string;
65
+ authMode?: 'direct' | 'zrouter';
66
+ };
67
+ /**
68
+ * The Zerg Router origin a native ZTC pane was launched or resumed with (its --router-url), when it names one. Its
69
+ * native record is rebuilt from its recipe and keeps none of its launch flags.
70
+ */
71
+ launchRouterOrigin?: string;
58
72
  }
59
73
  export interface PaneSessionSpec {
60
74
  paneId: number;
@@ -19,5 +19,8 @@ export declare function createZtcLaunchSpec(options?: {
19
19
  title?: string;
20
20
  providerOverride?: PaneProvider;
21
21
  modelOverride?: string;
22
+ /** The route the pane starts on, when it has one of its own (a split's): its auth mode and Router origin. */
23
+ authMode?: 'auto' | 'direct' | 'zrouter';
24
+ routerOrigin?: string;
22
25
  extraArgs?: string[];
23
26
  }): ZtcPaneLaunchSpec;
@@ -136,14 +136,15 @@ export function buildZtcPaneLaunchCommand(spec, argv = process.argv) {
136
136
  /**
137
137
  * A ZTC pane's route flags: its --auth-mode (direct for a local subscription), Zerg Router's origin when routed, and
138
138
  * the provider and model the pane names, or that this run's own launch flags chose while the profile waits for a route
139
- * choice (`inherited`). One that names none starts on the saved profile's provider, which another pane may have saved
140
- * since this process read it (ConfigStore.getNewPaneProvider).
139
+ * choice (`inherited`). One that names none starts on the route new panes start on: the saved profile's, which another
140
+ * pane may have saved since this process read it, and never this pane's own (ConfigStore.getNewPaneRoute).
141
141
  */
142
142
  function paneRouteArgs(route, inherited) {
143
- const local = isLocalSubscriptionProvider(route.providerOverride ?? inherited?.provider ?? configStore.getNewPaneProvider());
144
- const authMode = local ? 'direct' : inherited?.authMode ?? route.authMode ?? configStore.getChildAuthMode();
143
+ const started = configStore.getNewPaneRoute();
144
+ const local = isLocalSubscriptionProvider(route.providerOverride ?? inherited?.provider ?? started.provider);
145
+ const authMode = local ? 'direct' : inherited?.authMode ?? route.authMode ?? started.authMode;
145
146
  const args = ['--auth-mode', authMode];
146
- const origin = route.routerOrigin ?? configStore.get().zergProxyUrl;
147
+ const origin = route.routerOrigin ?? started.routerOrigin;
147
148
  if (authMode !== 'direct' && origin)
148
149
  args.push('--router-url', origin);
149
150
  const provider = route.providerOverride ?? inherited?.provider;
@@ -164,13 +165,15 @@ export function newZtcPaneRouteArgs() {
164
165
  export function createZtcLaunchSpec(options) {
165
166
  const sessionMode = options?.sessionMode || 'new';
166
167
  const sessionId = options?.sessionId || generateSessionId();
168
+ const started = configStore.getNewPaneRoute();
169
+ const local = isLocalSubscriptionProvider(options?.providerOverride ?? started.provider);
167
170
  return {
168
171
  kind: 'ztc',
169
172
  session: { mode: sessionMode, id: sessionId },
170
173
  cwd: options?.cwd,
171
174
  title: options?.title || 'ZTC',
172
- authMode: isLocalSubscriptionProvider(options?.providerOverride ?? configStore.getNewPaneProvider()) ? 'direct' : configStore.getChildAuthMode(),
173
- routerOrigin: configStore.get().zergProxyUrl,
175
+ authMode: local ? 'direct' : options?.authMode ?? started.authMode,
176
+ routerOrigin: options?.routerOrigin ?? started.routerOrigin,
174
177
  providerOverride: options?.providerOverride,
175
178
  modelOverride: options?.modelOverride,
176
179
  extraArgs: options?.extraArgs,
@@ -183,8 +183,8 @@ export declare const meetingSchema: z.ZodObject<{
183
183
  }>;
184
184
  reasoningEffort: z.ZodLiteral<"low">;
185
185
  status: z.ZodEnum<{
186
- accepted: "accepted";
187
186
  rejected: "rejected";
187
+ accepted: "accepted";
188
188
  declined: "declined";
189
189
  }>;
190
190
  failureCode: z.ZodOptional<z.ZodString>;
@@ -194,8 +194,8 @@ export declare const meetingSchema: z.ZodObject<{
194
194
  maxTokens: z.ZodLiteral<512>;
195
195
  }, z.core.$strict>>;
196
196
  status: z.ZodEnum<{
197
- accepted: "accepted";
198
197
  rejected: "rejected";
198
+ accepted: "accepted";
199
199
  }>;
200
200
  decision: z.ZodNullable<z.ZodObject<{
201
201
  id: z.ZodEnum<{
@@ -96,8 +96,8 @@ export declare const storyReviewReceiptSchema: z.ZodObject<{
96
96
  outputBytes: z.ZodNumber;
97
97
  requested: z.ZodBoolean;
98
98
  status: z.ZodEnum<{
99
- accepted: "accepted";
100
99
  rejected: "rejected";
100
+ accepted: "accepted";
101
101
  }>;
102
102
  decision: z.ZodNullable<z.ZodDiscriminatedUnion<[z.ZodObject<{
103
103
  kind: z.ZodLiteral<"close">;
@@ -187,8 +187,8 @@ export declare const storyReviewViewSchema: z.ZodObject<{
187
187
  outputBytes: z.ZodNumber;
188
188
  requested: z.ZodBoolean;
189
189
  status: z.ZodEnum<{
190
- accepted: "accepted";
191
190
  rejected: "rejected";
191
+ accepted: "accepted";
192
192
  }>;
193
193
  decision: z.ZodNullable<z.ZodDiscriminatedUnion<[z.ZodObject<{
194
194
  kind: z.ZodLiteral<"close">;
@@ -327,8 +327,8 @@ export declare const storyEpisodeSchema: (world: z.ZodType<SimulationDynamicWorl
327
327
  outputBytes: z.ZodNumber;
328
328
  requested: z.ZodBoolean;
329
329
  status: z.ZodEnum<{
330
- accepted: "accepted";
331
330
  rejected: "rejected";
331
+ accepted: "accepted";
332
332
  }>;
333
333
  decision: z.ZodNullable<z.ZodDiscriminatedUnion<[z.ZodObject<{
334
334
  kind: z.ZodLiteral<"close">;
@@ -19,17 +19,34 @@ export interface PaneCommandTransport {
19
19
  readonly isMuxMode: boolean;
20
20
  hasCapability?(name: string): boolean;
21
21
  }
22
+ /**
23
+ * A child's first line on a relay that advertises CAPABILITY_PANE_RELAY_IDENTITY: the pane its connection speaks for.
24
+ * The relay records it and never forwards it.
25
+ */
26
+ export interface PaneRelayHello {
27
+ type: 'relay_hello';
28
+ pane_id: number;
29
+ }
30
+ /** A command a child sent, with the pane its connection announced (null when it announced none). */
31
+ export type ChildCommandListener = (command: RustCommand, announcedPaneId: number | null) => void;
22
32
  export declare class PaneRelayServer {
23
33
  private transport;
24
34
  private server;
25
35
  private clients;
26
36
  private socketPath;
27
37
  private tuiUnsubscribe;
38
+ private readonly childCommandListeners;
28
39
  constructor(transport: PaneCommandTransport, socketPath: string);
29
40
  /** Start listening for child connections */
30
41
  start(): Promise<void>;
31
42
  /** Broadcast a pane event to all connected children */
32
43
  private broadcast;
44
+ /**
45
+ * See every command a child forwards, after the renderer gets it, with the pane its connection announced in its
46
+ * relay_hello (null for a child that announced none). Only a command whose own pane id is the announced one speaks
47
+ * for that pane. Returns an unsubscribe.
48
+ */
49
+ onChildCommand(listener: ChildCommandListener): () => void;
33
50
  /** Stop the relay server and clean up */
34
51
  stop(): void;
35
52
  }
@@ -40,7 +57,11 @@ export declare class PaneRelayClient implements PaneCommandTransport {
40
57
  private ready;
41
58
  private capabilities;
42
59
  private socketPath;
43
- constructor(socketPath: string);
60
+ private readonly paneId;
61
+ /** `paneId` is this child's pane (ZTC_PANE_ID): it names it to a relay that asks, before anything else it sends. */
62
+ constructor(socketPath: string, options?: {
63
+ paneId?: number;
64
+ });
44
65
  /** Connect to the parent's relay socket */
45
66
  connect(): Promise<void>;
46
67
  private setupHandlers;
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { createServer, createConnection } from 'net';
13
13
  import { createInterface } from 'readline';
14
- import { serializeCommand, parseEvent, CAPABILITY_PANE_DELIVERY_ACK, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_SYNCHRONIZED_OUTPUT, CAPABILITY_ATTENTION_BADGES } from './protocol.js';
14
+ import { serializeCommand, parseEvent, CAPABILITY_PANE_DELIVERY_ACK, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CHOICES, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_SYNCHRONIZED_OUTPUT, CAPABILITY_ATTENTION_BADGES, CAPABILITY_PANE_RELAY_IDENTITY, } from './protocol.js';
15
15
  import { runtimeDiag } from '../../utils/debug_log.js';
16
16
  import { generateIpcPath, removeOwnedIpcPath } from './ipc_path.js';
17
17
  import { markRelayed } from './pane_credential_broker.js';
@@ -32,12 +32,16 @@ const PANE_EVENT_TYPES = new Set([
32
32
  'desktop_runtime_action',
33
33
  'desktop_session_share_action',
34
34
  ]);
35
+ function isPaneId(value) {
36
+ return Number.isInteger(value) && value >= 0 && value <= 0xffff_ffff;
37
+ }
35
38
  export class PaneRelayServer {
36
39
  transport;
37
40
  server = null;
38
41
  clients = new Set();
39
42
  socketPath;
40
43
  tuiUnsubscribe = null;
44
+ childCommandListeners = new Set();
41
45
  constructor(transport, socketPath) {
42
46
  this.transport = transport;
43
47
  this.socketPath = socketPath;
@@ -54,10 +58,17 @@ export class PaneRelayServer {
54
58
  });
55
59
  this.server = createServer((client) => {
56
60
  this.clients.add(client);
61
+ // The renderer's capabilities a child may rely on, then the relay's own.
57
62
  client.write(JSON.stringify({ type: 'ready', version: 'pane-relay', cols: 0, rows: 0,
58
- capabilities: [CAPABILITY_PANE_DELIVERY_ACK, 'pane_labels_v1', CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_SYNCHRONIZED_OUTPUT, CAPABILITY_ATTENTION_BADGES]
59
- .filter(capability => this.transport.hasCapability?.(capability)),
63
+ capabilities: [...[CAPABILITY_PANE_DELIVERY_ACK, 'pane_labels_v1', CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CONTROLS,
64
+ CAPABILITY_DESKTOP_RUNTIME_CHOICES, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_SYNCHRONIZED_OUTPUT, CAPABILITY_ATTENTION_BADGES]
65
+ .filter(capability => this.transport.hasCapability?.(capability)), CAPABILITY_PANE_RELAY_IDENTITY],
60
66
  }) + '\n');
67
+ // A connection names its pane once, with its first relay_hello, whenever it comes: a child whose main ZTC was busy
68
+ // as it connected may have sent lines before its hello reached here (its connect() resolves after a short grace
69
+ // without the ready line). Those speak for no pane; a later relay_hello renames nothing.
70
+ let announced = null;
71
+ let named = false;
61
72
  const rl = createInterface({ input: client, crlfDelay: Infinity });
62
73
  // Readline re-emits input errors; one failed peer must not terminate its parent.
63
74
  rl.on('error', () => {
@@ -68,10 +79,28 @@ export class PaneRelayServer {
68
79
  const parsed = parseEvent(line);
69
80
  if (!parsed)
70
81
  return;
82
+ const hello = parsed;
83
+ if (hello.type === 'relay_hello') {
84
+ if (!named) {
85
+ named = true;
86
+ if (isPaneId(hello.pane_id))
87
+ announced = hello.pane_id;
88
+ }
89
+ return;
90
+ }
71
91
  // Treat incoming lines as commands (same JSON shape as RustCommand)
72
92
  // Forward to parent's TuiProcess, marked as a pane's: a pane it opens gets a plain credential of its own,
73
93
  // never a workspace monitor's, and a pane it relaunches in place gets none (PaneCredentialBroker).
74
- this.transport.send(markRelayed(parsed));
94
+ const command = markRelayed(parsed);
95
+ this.transport.send(command);
96
+ for (const listener of [...this.childCommandListeners]) {
97
+ try {
98
+ listener(command, announced);
99
+ }
100
+ catch (error) {
101
+ runtimeDiag('error', `Pane relay listener failed: ${String(error)}`);
102
+ }
103
+ }
75
104
  });
76
105
  client.on('error', () => {
77
106
  this.clients.delete(client);
@@ -117,6 +146,15 @@ export class PaneRelayServer {
117
146
  }
118
147
  }
119
148
  }
149
+ /**
150
+ * See every command a child forwards, after the renderer gets it, with the pane its connection announced in its
151
+ * relay_hello (null for a child that announced none). Only a command whose own pane id is the announced one speaks
152
+ * for that pane. Returns an unsubscribe.
153
+ */
154
+ onChildCommand(listener) {
155
+ this.childCommandListeners.add(listener);
156
+ return () => { this.childCommandListeners.delete(listener); };
157
+ }
120
158
  /** Stop the relay server and clean up */
121
159
  stop() {
122
160
  if (this.tuiUnsubscribe) {
@@ -155,8 +193,11 @@ export class PaneRelayClient {
155
193
  ready = false;
156
194
  capabilities = new Set();
157
195
  socketPath;
158
- constructor(socketPath) {
196
+ paneId;
197
+ /** `paneId` is this child's pane (ZTC_PANE_ID): it names it to a relay that asks, before anything else it sends. */
198
+ constructor(socketPath, options = {}) {
159
199
  this.socketPath = socketPath;
200
+ this.paneId = isPaneId(options.paneId) ? options.paneId : undefined;
160
201
  }
161
202
  /** Connect to the parent's relay socket */
162
203
  connect() {
@@ -205,8 +246,18 @@ export class PaneRelayClient {
205
246
  const event = parseEvent(line);
206
247
  if (!event)
207
248
  return;
208
- if (event.type === 'ready')
249
+ if (event.type === 'ready') {
209
250
  this.capabilities = new Set(event.capabilities ?? []);
251
+ // Usually before connect() resolves, so the hello is this connection's first line; when the ready line came after
252
+ // the grace, the relay still takes this first hello for what follows.
253
+ if (this.paneId !== undefined && this.capabilities.has(CAPABILITY_PANE_RELAY_IDENTITY)) {
254
+ const hello = { type: 'relay_hello', pane_id: this.paneId };
255
+ try {
256
+ this.socket?.write(JSON.stringify(hello) + '\n');
257
+ }
258
+ catch { /* the close handler retires this transport */ }
259
+ }
260
+ }
210
261
  for (const handler of this.handlers) {
211
262
  try {
212
263
  handler(event);
@@ -34,6 +34,16 @@ export declare const CAPABILITY_DESKTOP_UPDATE_RESTART = "desktop_update_restart
34
34
  export declare const CAPABILITY_DESKTOP_ROUTER_CHROME = "desktop_router_chrome_v1";
35
35
  export declare const CAPABILITY_DESKTOP_TASK_CONTROLS = "desktop_task_controls_v1";
36
36
  export declare const CAPABILITY_DESKTOP_RUNTIME_CONTROLS = "desktop_runtime_controls_v1";
37
+ /**
38
+ * The renderer draws provider and model menus in a ZTC pane's header from the pane's `runtime_choices`, and sends
39
+ * select_runtime, refresh_choices, router_login and save_as_default only for a pane whose latest state carries them.
40
+ */
41
+ export declare const CAPABILITY_DESKTOP_RUNTIME_CHOICES = "desktop_runtime_choices_v1";
42
+ /**
43
+ * The pane relay's own (never a renderer's): a child that sees it names its pane with a `relay_hello` line before
44
+ * anything else, so the main ZTC knows which pane each child connection speaks for (see PaneRelayServer).
45
+ */
46
+ export declare const CAPABILITY_PANE_RELAY_IDENTITY = "pane_relay_identity_v1";
37
47
  export declare const CAPABILITY_DESKTOP_SESSION_SHARE = "desktop_session_share_v1";
38
48
  export declare const CAPABILITY_TERMINAL_FRAME_METRICS = "terminal_frame_metrics_v1";
39
49
  export declare const CAPABILITY_TERMINAL_INTERACTION = "terminal_interaction_v1";
@@ -224,6 +234,8 @@ export interface DesktopTaskControlState {
224
234
  can_stop: boolean;
225
235
  entries: DesktopTaskControlEntry[];
226
236
  runtime?: DesktopRuntimeState;
237
+ /** Sent only with `runtime`, to a renderer with desktop_runtime_choices_v1, for a pane that isn't hosted. */
238
+ runtime_choices?: DesktopRuntimeChoices;
227
239
  /** A preview request with a zero package ID captures the current checkpoint. */
228
240
  share_available?: boolean;
229
241
  share?: DesktopSessionShareState;
@@ -292,6 +304,62 @@ export interface DesktopRuntimeState {
292
304
  switching_blocked_reason: string | null;
293
305
  context_notice: string;
294
306
  }
307
+ /** Limits on `runtime_choices`, the same as ztc-core's (protocol.rs). Byte limits are UTF-8 bytes. */
308
+ export declare const DESKTOP_RUNTIME_MAX_PROVIDER_CHOICES = 48;
309
+ export declare const DESKTOP_RUNTIME_MAX_MODEL_CHOICES = 128;
310
+ export declare const DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES = 96;
311
+ export declare const DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES = 48;
312
+ export declare const DESKTOP_RUNTIME_MAX_CHOICE_DETAIL_BYTES = 160;
313
+ export declare const DESKTOP_RUNTIME_MAX_URL_BYTES = 512;
314
+ /** A provider in a pane header's provider menu. ZTC never sends route `other`, and always sends `detail`. */
315
+ export interface DesktopProviderChoice {
316
+ /** `zergrouter:<provider>` through Zerg Router, otherwise the provider id. */
317
+ id: string;
318
+ provider: string;
319
+ route: 'router' | 'direct';
320
+ /** Menu text. */
321
+ label: string;
322
+ /** Chip text. */
323
+ short_label: string;
324
+ detail: string | null;
325
+ state: 'ready' | 'needs_setup' | 'unavailable';
326
+ }
327
+ /** A model of the pane's provider, as ZTC applies it (`morph/morph-dsv41flash-1017`). */
328
+ export interface DesktopModelChoice {
329
+ id: string;
330
+ label: string;
331
+ short_label: string;
332
+ detail: string | null;
333
+ available: boolean;
334
+ group: 'recent' | 'all' | 'older';
335
+ }
336
+ /** The lists a pane header's provider and model menus show, built from what this ZTC has cached. */
337
+ export interface DesktopRuntimeChoices {
338
+ /** Moves only when the lists or the selection change, never for usage or `observed_at` alone. */
339
+ revision: number;
340
+ /** One of `providers[].id`. */
341
+ selected_provider: string;
342
+ /** One of `models[].id`. */
343
+ selected_model: string;
344
+ /** What new panes start on, and so what "Use for new panes" compares against. */
345
+ new_pane_route: {
346
+ provider_choice: string;
347
+ model: string;
348
+ label: string;
349
+ };
350
+ providers: DesktopProviderChoice[];
351
+ /** The selected provider's models. */
352
+ models: DesktopModelChoice[];
353
+ /** False when the provider has more models than the list holds: the menu offers More models… (open_models). */
354
+ models_complete: boolean;
355
+ models_loading: boolean;
356
+ router: {
357
+ session: 'signed_in' | 'signed_out' | 'expired';
358
+ catalog: 'fresh' | 'cached' | 'loading' | 'unavailable' | 'rejected' | 'absent';
359
+ /** Zerg Router's Credentials page, only for the person's own Router sign-in. */
360
+ credentials_url: string | null;
361
+ };
362
+ }
295
363
  export type DesktopRuntimeAction = {
296
364
  type: 'desktop_runtime_action';
297
365
  request_id: string;
@@ -304,6 +372,17 @@ export type DesktopRuntimeAction = {
304
372
  account_id: string;
305
373
  } | {
306
374
  action: 'open_models';
375
+ } | {
376
+ action: 'select_runtime';
377
+ provider_choice: string;
378
+ model?: string;
379
+ } | {
380
+ action: 'refresh_choices';
381
+ force: boolean;
382
+ } | {
383
+ action: 'router_login';
384
+ } | {
385
+ action: 'save_as_default';
307
386
  });
308
387
  export interface DesktopTaskActionResult {
309
388
  request_id: string;
@@ -727,7 +806,24 @@ export declare function serializeCommand(cmd: RustCommand): string;
727
806
  export declare function parseEvent(json: string): RustEvent | null;
728
807
  /** Sharing intents carry only bounded identities and an explicit save destination. */
729
808
  export declare function isDesktopSessionShareAction(value: unknown): value is DesktopSessionShareAction;
730
- /** Runtime intents have no optional payload fields or unrecognized operations. */
809
+ /**
810
+ * Runtime intents carry exactly their action's keys: a select_runtime's model only when it names one, and nothing an
811
+ * action doesn't take.
812
+ */
731
813
  export declare function isDesktopRuntimeAction(value: unknown): value is DesktopRuntimeAction;
814
+ /**
815
+ * Zerg Router's Credentials page as zterm will open it, read as ztc-core's is_router_credentials_url reads it: a literal
816
+ * `https://`, or `http://` on this machine (localhost, 127.0.0.1 or [::1] exactly); an ASCII host name or a bracketed
817
+ * IPv6 address, with a port of one to five digits; no userinfo, whitespace, control, bidi mark or backslash; in at
818
+ * most 512 bytes.
819
+ */
820
+ export declare function isDesktopCredentialsUrl(value: unknown): value is string;
821
+ /**
822
+ * Whether zterm accepts `value` as a pane's `runtime_choices`, by ztc-core's rules: bounded, clean text; at most 48
823
+ * providers and 128 models, each id once; the selected provider and model listed; a Credentials page zterm will open.
824
+ * Unknown fields are ignored, and an unknown route, state, group, session or catalog name is accepted, as zterm reads
825
+ * it conservatively.
826
+ */
827
+ export declare function isDesktopRuntimeChoices(value: unknown): value is DesktopRuntimeChoices;
732
828
  /** Reject malformed native actions before any host queue operation sees them. */
733
829
  export declare function isDesktopTaskAction(value: unknown): value is DesktopTaskAction;
@@ -11,6 +11,16 @@ export const CAPABILITY_DESKTOP_UPDATE_RESTART = 'desktop_update_restart_v1';
11
11
  export const CAPABILITY_DESKTOP_ROUTER_CHROME = 'desktop_router_chrome_v1';
12
12
  export const CAPABILITY_DESKTOP_TASK_CONTROLS = 'desktop_task_controls_v1';
13
13
  export const CAPABILITY_DESKTOP_RUNTIME_CONTROLS = 'desktop_runtime_controls_v1';
14
+ /**
15
+ * The renderer draws provider and model menus in a ZTC pane's header from the pane's `runtime_choices`, and sends
16
+ * select_runtime, refresh_choices, router_login and save_as_default only for a pane whose latest state carries them.
17
+ */
18
+ export const CAPABILITY_DESKTOP_RUNTIME_CHOICES = 'desktop_runtime_choices_v1';
19
+ /**
20
+ * The pane relay's own (never a renderer's): a child that sees it names its pane with a `relay_hello` line before
21
+ * anything else, so the main ZTC knows which pane each child connection speaks for (see PaneRelayServer).
22
+ */
23
+ export const CAPABILITY_PANE_RELAY_IDENTITY = 'pane_relay_identity_v1';
14
24
  export const CAPABILITY_DESKTOP_SESSION_SHARE = 'desktop_session_share_v1';
15
25
  export const CAPABILITY_TERMINAL_FRAME_METRICS = 'terminal_frame_metrics_v1';
16
26
  export const CAPABILITY_TERMINAL_INTERACTION = 'terminal_interaction_v1';
@@ -29,6 +39,13 @@ export const CAPABILITY_SYNCHRONIZED_OUTPUT = 'synchronized_output_v1';
29
39
  * looking at it, and lists the badge as the pane's `attention`.
30
40
  */
31
41
  export const CAPABILITY_ATTENTION_BADGES = 'attention_badges_v1';
42
+ /** Limits on `runtime_choices`, the same as ztc-core's (protocol.rs). Byte limits are UTF-8 bytes. */
43
+ export const DESKTOP_RUNTIME_MAX_PROVIDER_CHOICES = 48;
44
+ export const DESKTOP_RUNTIME_MAX_MODEL_CHOICES = 128;
45
+ export const DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES = 96;
46
+ export const DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES = 48;
47
+ export const DESKTOP_RUNTIME_MAX_CHOICE_DETAIL_BYTES = 160;
48
+ export const DESKTOP_RUNTIME_MAX_URL_BYTES = 512;
32
49
  // ============================================================================
33
50
  // Serialization helpers
34
51
  // ============================================================================
@@ -83,7 +100,10 @@ export function isDesktopSessionShareAction(value) {
83
100
  return false;
84
101
  return Object.keys(event).every(key => keys.includes(key));
85
102
  }
86
- /** Runtime intents have no optional payload fields or unrecognized operations. */
103
+ /**
104
+ * Runtime intents carry exactly their action's keys: a select_runtime's model only when it names one, and nothing an
105
+ * action doesn't take.
106
+ */
87
107
  export function isDesktopRuntimeAction(value) {
88
108
  if (value === null || typeof value !== 'object' || Array.isArray(value))
89
109
  return false;
@@ -96,15 +116,125 @@ export function isDesktopRuntimeAction(value) {
96
116
  || !Number.isSafeInteger(event.revision) || event.revision < 0)
97
117
  return false;
98
118
  const keys = ['type', 'request_id', 'pane_id', 'session_id', 'owner_id', 'revision', 'action'];
99
- if (event.action === 'account_use') {
100
- if (!identity(event.account_id))
119
+ switch (event.action) {
120
+ case 'account_use':
121
+ if (!identity(event.account_id))
122
+ return false;
123
+ keys.push('account_id');
124
+ break;
125
+ case 'select_runtime':
126
+ if (!identity(event.provider_choice))
127
+ return false;
128
+ keys.push('provider_choice');
129
+ // A model is named only with one: 1 to 256 bytes.
130
+ if (Object.hasOwn(event, 'model')) {
131
+ if (!identity(event.model))
132
+ return false;
133
+ keys.push('model');
134
+ }
135
+ break;
136
+ case 'refresh_choices':
137
+ if (typeof event.force !== 'boolean')
138
+ return false;
139
+ keys.push('force');
140
+ break;
141
+ case 'open_models':
142
+ case 'router_login':
143
+ case 'save_as_default':
144
+ break;
145
+ default:
101
146
  return false;
102
- keys.push('account_id');
103
147
  }
104
- else if (event.action !== 'open_models')
105
- return false;
106
148
  return Object.keys(event).every(key => keys.includes(key));
107
149
  }
150
+ /** Characters no `runtime_choices` text may carry: C0 and C1 controls, and the bidi marks, embeddings and isolates. */
151
+ const CHOICE_FORBIDDEN = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/;
152
+ function choiceText(value, maxBytes) {
153
+ return typeof value === 'string' && Buffer.byteLength(value, 'utf8') <= maxBytes && !CHOICE_FORBIDDEN.test(value);
154
+ }
155
+ /** A desktop identity: 1 to 256 bytes. */
156
+ function choiceIdentity(value) {
157
+ return choiceText(value, 256) && value.length > 0;
158
+ }
159
+ /** An optional detail: absent or null, or up to 160 bytes. */
160
+ function choiceDetail(value) {
161
+ return value === undefined || value === null || choiceText(value, DESKTOP_RUNTIME_MAX_CHOICE_DETAIL_BYTES);
162
+ }
163
+ /** A name zterm reads with a string match; one it doesn't know maps to its conservative value, never an error. */
164
+ function choiceName(value, optional = false) {
165
+ return typeof value === 'string' || (optional && value === undefined);
166
+ }
167
+ function choiceRecord(value) {
168
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
169
+ }
170
+ /**
171
+ * Zerg Router's Credentials page as zterm will open it, read as ztc-core's is_router_credentials_url reads it: a literal
172
+ * `https://`, or `http://` on this machine (localhost, 127.0.0.1 or [::1] exactly); an ASCII host name or a bracketed
173
+ * IPv6 address, with a port of one to five digits; no userinfo, whitespace, control, bidi mark or backslash; in at
174
+ * most 512 bytes.
175
+ */
176
+ export function isDesktopCredentialsUrl(value) {
177
+ if (typeof value !== 'string' || Buffer.byteLength(value, 'utf8') > DESKTOP_RUNTIME_MAX_URL_BYTES
178
+ || /[\s\\]/.test(value) || CHOICE_FORBIDDEN.test(value))
179
+ return false;
180
+ const local = value.startsWith('http://');
181
+ if (!local && !value.startsWith('https://'))
182
+ return false;
183
+ const authority = value.slice(local ? 'http://'.length : 'https://'.length).split(/[/?#]/, 1)[0];
184
+ // Userinfo ("user@host") could make one host read as another.
185
+ if (!authority || authority.includes('@'))
186
+ return false;
187
+ const bracketEnd = authority.startsWith('[') ? authority.indexOf(']') : -1;
188
+ if (authority.startsWith('[') && bracketEnd < 0)
189
+ return false;
190
+ const hostEnd = bracketEnd >= 0 ? bracketEnd + 1 : authority.includes(':') ? authority.indexOf(':') : authority.length;
191
+ const host = authority.slice(0, hostEnd);
192
+ const port = authority.slice(hostEnd);
193
+ if (!host || !(port === '' || /^:\d{1,5}$/.test(port)))
194
+ return false;
195
+ if (local)
196
+ return ['localhost', '127.0.0.1', '[::1]'].includes(host);
197
+ if (bracketEnd >= 0)
198
+ return /^\[[0-9a-fA-F:.]+\]$/.test(host);
199
+ return /^[A-Za-z0-9.-]+$/.test(host);
200
+ }
201
+ /**
202
+ * Whether zterm accepts `value` as a pane's `runtime_choices`, by ztc-core's rules: bounded, clean text; at most 48
203
+ * providers and 128 models, each id once; the selected provider and model listed; a Credentials page zterm will open.
204
+ * Unknown fields are ignored, and an unknown route, state, group, session or catalog name is accepted, as zterm reads
205
+ * it conservatively.
206
+ */
207
+ export function isDesktopRuntimeChoices(value) {
208
+ if (!choiceRecord(value))
209
+ return false;
210
+ const { revision, selected_provider: provider, selected_model: model, new_pane_route: route, providers, models, router } = value;
211
+ if (!Number.isSafeInteger(revision) || revision < 0 || !choiceIdentity(provider) || !choiceText(model, 256))
212
+ return false;
213
+ if (!choiceRecord(route) || !choiceIdentity(route.provider_choice) || !choiceText(route.model, 256)
214
+ || !choiceText(route.label, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES))
215
+ return false;
216
+ if (typeof value.models_complete !== 'boolean' || typeof value.models_loading !== 'boolean')
217
+ return false;
218
+ if (!choiceRecord(router) || !choiceName(router.session) || !choiceName(router.catalog)
219
+ || !(router.credentials_url === undefined || router.credentials_url === null || isDesktopCredentialsUrl(router.credentials_url)))
220
+ return false;
221
+ if (!Array.isArray(providers) || providers.length > DESKTOP_RUNTIME_MAX_PROVIDER_CHOICES
222
+ || !providers.every(row => choiceRecord(row) && choiceIdentity(row.id) && choiceText(row.provider, 256)
223
+ && choiceName(row.route) && choiceText(row.label, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES)
224
+ && choiceText(row.short_label, DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES) && choiceDetail(row.detail)
225
+ && choiceName(row.state)))
226
+ return false;
227
+ if (!Array.isArray(models) || models.length > DESKTOP_RUNTIME_MAX_MODEL_CHOICES
228
+ || !models.every(row => choiceRecord(row) && choiceText(row.id, 256)
229
+ && choiceText(row.label, DESKTOP_RUNTIME_MAX_CHOICE_LABEL_BYTES)
230
+ && choiceText(row.short_label, DESKTOP_RUNTIME_MAX_CHOICE_SHORT_LABEL_BYTES) && choiceDetail(row.detail)
231
+ && typeof row.available === 'boolean' && choiceName(row.group, true)))
232
+ return false;
233
+ const providerIds = providers.map(row => row.id);
234
+ const modelIds = models.map(row => row.id);
235
+ return new Set(providerIds).size === providerIds.length && new Set(modelIds).size === modelIds.length
236
+ && providerIds.includes(provider) && modelIds.includes(model);
237
+ }
108
238
  /** Reject malformed native actions before any host queue operation sees them. */
109
239
  export function isDesktopTaskAction(value) {
110
240
  if (value === null || typeof value !== 'object' || Array.isArray(value))
@@ -0,0 +1,3 @@
1
+ import type { RouterModelDescriptor } from './router_catalog.js';
2
+ /** What a Router model offers, for its row: context, reasoning, images, limits and its price across providers. */
3
+ export declare function routerModelFacts(row: RouterModelDescriptor): string;