@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
@@ -3,6 +3,7 @@
3
3
  * it needs; and a switch to one, which sets the default for new panes and switches this pane in one step.
4
4
  */
5
5
  import { buildProviderChoices } from '../../app/runtime_choices.js';
6
+ import { routerCredentialsUrl, routerKeyAdvice } from '../backends/router_keys.js';
6
7
  import { isLocalSubscriptionProvider, normalizeProviderId } from '../backends/provider_ids.js';
7
8
  import { canonicalProvider, canonicalRoute, isRouterOnlyProvider, modelRouteStatus, PROVIDER_CHOICES, routerServesProvider, } from './provider_choices.js';
8
9
  import { profileDirectory, refreshRouterModels, selectProviderModel } from './provider_selection.js';
@@ -19,7 +20,7 @@ function choicesFor(ctx, current) {
19
20
  /** Router's Credentials page, where a provider key is added: only for the person's own Router sign-in. */
20
21
  function credentialsUrl(ctx) {
21
22
  const origin = ctx.config.getPersonalRouterCredential?.()?.origin;
22
- return origin ? `${origin.replace(/\/+$/, '')}/dashboard?tab=credentials` : undefined;
23
+ return origin ? routerCredentialsUrl(origin) : undefined;
23
24
  }
24
25
  function detail(choice, url) {
25
26
  return choice.state === 'unavailable' && url ? `${choice.detail} · add it at ${url}` : choice.detail;
@@ -154,8 +155,9 @@ async function applyChoice(resolved, model, ctx) {
154
155
  const { provider, route, choice } = resolved;
155
156
  if (choice?.state === 'unavailable') {
156
157
  const url = credentialsUrl(ctx);
158
+ // Where the key goes, once: a personal-only provider's (Morph's) serves only the Router account it is in.
157
159
  ctx.addMessage({ role: 'system', content: `${choice.short_label} has no key on Zerg Router yet. `
158
- + `${url ? `Add it at ${url}` : 'Add it on Zerg Router\'s Credentials page'}, then run /provider refresh.` });
160
+ + routerKeyAdvice({ provider, label: choice.short_label, ...(url ? { credentialsUrl: url } : {}) }, 'it', { otherModel: false }) });
159
161
  return;
160
162
  }
161
163
  const confirm = (applied, kept) => {
@@ -10,8 +10,10 @@ import { getDefaultModel } from '../../utils/models.js';
10
10
  import { resolveRouterModel, RouterCatalogAuthenticationError, routerModelForSwitch } from '../../utils/router_catalog.js';
11
11
  import { ROUTER_MODELS_NEED_LOGIN, ZERGAI_LOGIN_BENEFITS } from '../../onboarding/zergai_login.js';
12
12
  import { runAuthAction } from './auth.js';
13
+ import { ROUTER_SIGN_IN_REJECTED } from '../../router_auth.js';
13
14
  import { offerReasoningPicker } from './reasoning_picker.js';
14
15
  import { isRetiredModel, isRetiredProvider, retiredModelMessage, retiredProviderMessage } from '../../config/retired_routes.js';
16
+ import { keylessRouterModelRefusal } from './router_availability.js';
15
17
  /**
16
18
  * Where this configuration keeps its profile: the models remembered per provider live beside its config.json. A
17
19
  * configuration without a file (a renderer's stand-in) remembers nothing.
@@ -42,7 +44,10 @@ export async function refreshRouterModels(ctx) {
42
44
  }
43
45
  try {
44
46
  const catalog = await ctx.models.catalog(undefined, { refresh: true });
45
- ctx.addMessage({ role: 'system', content: `${catalog.authRequired ? 'Router authentication rejected. Run ztc auth login again. Showing cached catalog' : catalog.cached ? 'Router unavailable. Showing cached catalog' : 'Router catalog refreshed'}: ${catalog.models.length} models. Active responses continue with their current selection.` });
47
+ // Router turned the sign-in away (its 401 or 403): the person signs in again in this session.
48
+ ctx.addMessage({ role: 'system', content: `${catalog.authRequired ? `${ROUTER_SIGN_IN_REJECTED} Showing the list Router sent before`
49
+ : catalog.cached ? 'Router unavailable. Showing cached catalog' : 'Router catalog refreshed'}: ${catalog.models.length} models. `
50
+ + 'Active responses continue with their current selection.' });
46
51
  }
47
52
  catch (error) {
48
53
  ctx.addMessage({ role: 'system', content: `Could not refresh Router models: ${error.message}` });
@@ -174,11 +179,13 @@ export async function selectProviderModel(args, ctx, options = {}) {
174
179
  : keptDirect || resolveModelAndProvider(defaultModel, provider).model);
175
180
  try {
176
181
  if (routed && ctx.models.catalog) {
177
- const catalog = await ctx.models.catalog(undefined, { refresh: !explicitModel }).catch(error => {
182
+ const listCatalog = ctx.models.catalog;
183
+ const readCatalog = (refresh) => listCatalog(undefined, { refresh }).catch(error => {
178
184
  if (error instanceof RouterCatalogAuthenticationError)
179
185
  throw error;
180
186
  return undefined;
181
187
  });
188
+ const catalog = await readCatalog(!explicitModel);
182
189
  if (catalog?.authRequired)
183
190
  throw new Error('Router authentication rejected. Run /auth login and retry.');
184
191
  if (catalog?.version === 1) {
@@ -190,6 +197,13 @@ export async function selectProviderModel(args, ctx, options = {}) {
190
197
  const selected = resolveRouterModel(catalog, provider, model);
191
198
  if (!selected?.capabilities?.chat)
192
199
  throw new Error('Model is not in the Router catalog. Run /model zergrouter to choose an available model.');
200
+ // A model Router has no key for is refused with where the key goes, once Router has been asked again: a choice
201
+ // with no model named just did, one naming its model read the cached list.
202
+ const refusal = await keylessRouterModelRefusal(provider, selected.id, { catalog,
203
+ ...(explicitModel ? { refresh: () => readCatalog(true) } : {}),
204
+ ...(ctx.config.getPersonalRouterCredential?.()?.origin ? { origin: ctx.config.getPersonalRouterCredential().origin } : {}) });
205
+ if (refusal)
206
+ throw new Error(refusal);
193
207
  model = selected.id;
194
208
  }
195
209
  }
@@ -0,0 +1,15 @@
1
+ import { type RouterCatalog } from '../../utils/router_catalog.js';
2
+ export interface RouterAvailabilityCheck {
3
+ /** Router's catalog as the choice read it. */
4
+ catalog: RouterCatalog | undefined;
5
+ /** Router's catalog asked for again; omitted when the choice has just asked Router itself (`catalog` is its answer). */
6
+ refresh?: () => Promise<RouterCatalog | undefined>;
7
+ /** The origin of the person's own Router sign-in, whose Credentials page the refusal links. */
8
+ origin?: string;
9
+ }
10
+ /**
11
+ * What refuses PROVIDER's MODEL through Router: the words when its catalog still marks it unavailable after one
12
+ * refresh, or undefined when it may be chosen (available, or a model the catalog doesn't describe, which the caller
13
+ * checks for itself).
14
+ */
15
+ export declare function keylessRouterModelRefusal(provider: string, model: string, check: RouterAvailabilityCheck): Promise<string | undefined>;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A Router model chosen while Router's catalog marks it unavailable: no key for its provider on this account. Every way
3
+ * of choosing a model refuses it (/model, /model set, the agent's /model, a pane's model picker, /settings, the web
4
+ * mirror's model menu), with where the key goes, after asking Router once more: a key added since the list was cached
5
+ * must never be refused. So only a list Router has just sent says the key is missing; when Router can't be asked, the
6
+ * refusal says so instead, and a sign-in Router turned away is told to log in again. /provider refuses a provider with
7
+ * no usable model in its own words (provider.ts).
8
+ */
9
+ import { routerCredentialsUrl, routerProviderLabel, uncheckedRouterModelMessage, unavailableRouterModelMessage, } from '../backends/router_keys.js';
10
+ import { resolveRouterModel } from '../../utils/router_catalog.js';
11
+ import { PROVIDER_CHOICES } from './provider_choices.js';
12
+ /** What refuses a choice Router turned the sign-in away for, as /model's own catalog read says it. */
13
+ const ROUTER_AUTH_REJECTED = 'Router authentication rejected. Run /auth login and retry.';
14
+ /** CATALOG when it is a list Router has just sent: a refresh that couldn't reach Router answers with the cached one. */
15
+ function justSent(catalog) {
16
+ return catalog?.version === 1 && catalog.cached === false && catalog.authRequired !== true ? catalog : undefined;
17
+ }
18
+ /**
19
+ * What refuses PROVIDER's MODEL through Router: the words when its catalog still marks it unavailable after one
20
+ * refresh, or undefined when it may be chosen (available, or a model the catalog doesn't describe, which the caller
21
+ * checks for itself).
22
+ */
23
+ export async function keylessRouterModelRefusal(provider, model, check) {
24
+ let catalog = check.catalog;
25
+ let row = catalog?.version === 1 ? resolveRouterModel(catalog, provider, model) : undefined;
26
+ if (row?.available !== false)
27
+ return undefined;
28
+ const answer = check.refresh ? await check.refresh().catch(() => undefined) : catalog;
29
+ const asked = justSent(answer);
30
+ if (asked) {
31
+ catalog = asked;
32
+ row = resolveRouterModel(asked, provider, model) ?? row;
33
+ if (row.available !== false)
34
+ return undefined;
35
+ }
36
+ else if (answer?.authRequired) {
37
+ return ROUTER_AUTH_REJECTED;
38
+ }
39
+ const target = {
40
+ provider, model: row.display_name || row.id,
41
+ label: routerProviderLabel(catalog, provider) ?? PROVIDER_CHOICES.find(choice => choice.id === provider)?.label,
42
+ ...(check.origin ? { credentialsUrl: routerCredentialsUrl(check.origin) } : {}),
43
+ };
44
+ return asked ? unavailableRouterModelMessage(target) : uncheckedRouterModelMessage(target);
45
+ }
@@ -16,6 +16,7 @@ import { CODEX_REASONING_EFFORTS } from '../../config/types.js';
16
16
  import { customPaneOptions, storedCustomPaneOptions, withCustomPaneOptions, } from '../../config/panes.js';
17
17
  import { getMcpServerStatuses } from '../../mcp/registry.js';
18
18
  import { claudeBadgesOn } from '../../panes/claude_notifications.js';
19
+ import { agentPermissionsSetting } from '../../panes/agent_cli.js';
19
20
  import { CLAUDE_SUBSCRIPTION_POLICY, isRetiredModel, isRetiredProvider, retiredProviderMessage } from '../../config/retired_routes.js';
20
21
  import { subsCommand } from './subs.js';
21
22
  import { modelForProviderSwitch } from './provider_model_defaults.js';
@@ -25,6 +26,7 @@ import { activeReasoning } from './reasoning_settings.js';
25
26
  import { isBuildableResolvedConfig, unbuildableSelectionMessage } from './config.js';
26
27
  import { hasRemovableKey, manageApiKey, promptForMissingDirectKey, removeApiKey, } from './direct_credential_prompt.js';
27
28
  import { offerKeyedProviderSwitch, ownRouteModelSelection, profileDirectory, stillListed } from './provider_selection.js';
29
+ import { keylessRouterModelRefusal } from './router_availability.js';
28
30
  import { API_KEY_PROVIDER_CHOICES, DIRECT_PROVIDER_CHOICES, PROVIDER_CHOICES, ROUTER_CHOICE_PREFIX, canonicalProvider, describeKeySource, isLocalSubscription, isRouterOnlyProvider, modelRouteStatus, providerChoiceId, } from './provider_choices.js';
29
31
  import { rememberedModel, rememberProviderModel } from '../../config/provider_models.js';
30
32
  import { describeActiveRoute, describeConnection, describeKeyRow } from './credential_status.js';
@@ -928,6 +930,17 @@ export async function buildSettingsCategories(ctx) {
928
930
  ],
929
931
  description: 'Desktop app only. A --settings you give a pane yourself still wins.',
930
932
  },
933
+ {
934
+ name: 'panesAgentPermissions',
935
+ label: 'Claude Code and Codex permissions',
936
+ value: agentPermissionsSetting(config.panes),
937
+ type: 'select',
938
+ options: [
939
+ { value: 'bypass', label: 'bypass', description: 'Claude Code and Codex panes you open run commands without asking, Codex outside its sandbox: ZTC starts them with --dangerously-skip-permissions and --dangerously-bypass-approvals-and-sandbox. Claude Code asks you once to accept that mode.' },
940
+ { value: 'ask', label: 'ask', description: 'ZTC passes neither flag: Claude Code and Codex ask before running commands as their own settings say' },
941
+ ],
942
+ description: 'Claude Code and Codex panes you open. Panes an agent opens always ask. A permission flag you give a pane yourself still wins; delegated workers always stay read-only.',
943
+ },
931
944
  ],
932
945
  },
933
946
  {
@@ -1301,6 +1314,11 @@ function applySettingChange(ctx, setting, value, selection) {
1301
1314
  throw new Error('Claude Code badges must be on or off.');
1302
1315
  ctx.config.set('panes', { ...ctx.config.get().panes, claudeBadges: value === 'true' });
1303
1316
  break;
1317
+ case 'panesAgentPermissions':
1318
+ if (value !== 'bypass' && value !== 'ask')
1319
+ throw new Error('Claude Code and Codex permissions must be bypass or ask.');
1320
+ ctx.config.set('panes', { ...ctx.config.get().panes, agentPermissions: value });
1321
+ break;
1304
1322
  case 'authMode':
1305
1323
  if (ctx.config.setAuthMode)
1306
1324
  ctx.config.setAuthMode(value);
@@ -1915,14 +1933,30 @@ function selectionRoute(ctx, selection) {
1915
1933
  return ctx.config.getAuthMode?.() === 'zrouter' ? 'zergrouter' : 'direct';
1916
1934
  }
1917
1935
  }
1936
+ /** How a row's choice of a Router model is checked against Router's catalog (see keylessRouterModelRefusal). */
1937
+ function routerAvailability(ctx) {
1938
+ const listCatalog = ctx.models.catalog;
1939
+ const origin = ctx.config.getPersonalRouterCredential?.()?.origin;
1940
+ return { catalog: ctx.config.getRouterCatalog?.(), ...(listCatalog ? { refresh: () => listCatalog(undefined, { refresh: true }) } : {}),
1941
+ ...(origin ? { origin } : {}) };
1942
+ }
1943
+ /** Throw what refuses a Router model Router has no key for, so the row reverts with it. */
1944
+ async function refuseKeylessRouterModel(ctx, provider, model) {
1945
+ const refusal = await keylessRouterModelRefusal(provider, model, routerAvailability(ctx));
1946
+ if (refusal)
1947
+ throw new Error(`${refusal} Keeping the current selection.`);
1948
+ }
1918
1949
  /** The provider, model and route a provider or model row selects. */
1919
1950
  async function plannedModelSelection(ctx, setting, value) {
1920
1951
  const current = ctx.config.getProvider();
1921
1952
  if (setting === 'model') {
1922
1953
  // A pane running a route of its own saves that provider and route with the model, so the default stays a pair.
1923
1954
  const own = ownRouteModelSelection(ctx, value);
1924
- return own ? { provider: own[1], model: value, authMode: own[0] === 'zergrouter' ? 'zrouter' : 'direct' }
1955
+ const selection = own ? { provider: own[1], model: value, authMode: own[0] === 'zergrouter' ? 'zrouter' : 'direct' }
1925
1956
  : { provider: current, model: value };
1957
+ if (selectionRoute(ctx, selection) === 'zergrouter')
1958
+ await refuseKeylessRouterModel(ctx, selection.provider, value);
1959
+ return selection;
1926
1960
  }
1927
1961
  const choice = value.startsWith(ROUTER_CHOICE_PREFIX) ? value.slice(ROUTER_CHOICE_PREFIX.length) : value;
1928
1962
  if (isRetiredProvider(choice))
@@ -1942,8 +1976,9 @@ async function plannedModelSelection(ctx, setting, value) {
1942
1976
  : routerModelForSwitch(catalog, provider, current, getEffectiveModel(ctx));
1943
1977
  if (!selected)
1944
1978
  throw new Error(`${providerChoiceLabel(provider)} is not in the Zerg Router catalog. Keeping the current selection.`);
1945
- return { provider, model: selected.id, authMode: 'zrouter',
1946
- ...(selected.available === false ? { warning: `Zerg Router lists no ${providerChoiceLabel(provider)} model your account can use now; selected ${selected.id} anyway.` } : {}) };
1979
+ // A provider Router has no key for is refused with where the key goes, as /provider refuses it.
1980
+ await refuseKeylessRouterModel(ctx, provider, selected.id);
1981
+ return { provider, model: selected.id, authMode: 'zrouter' };
1947
1982
  }
1948
1983
  return { provider, model: modelForProviderSwitch(provider, current, getEffectiveModel(ctx)), authMode: 'zrouter' };
1949
1984
  }
@@ -2179,8 +2214,6 @@ async function openSettings(ctx, open = {}) {
2179
2214
  invalidateSkillsCache();
2180
2215
  await preloadSkillsManifest();
2181
2216
  }
2182
- if (selection?.warning)
2183
- ctx.addMessage({ role: 'system', content: selection.warning });
2184
2217
  try {
2185
2218
  if (selection) {
2186
2219
  applyRuntimeModelSelection(ctx, selection.provider, selection.model, selection.authMode);
@@ -4,7 +4,10 @@
4
4
  *
5
5
  * A profile keeps the CLI's own sign-in in a directory of ZTC's (see
6
6
  * panes/agent_profiles.ts), so choosing one here never changes the CLI's
7
- * sign-in in iTerm or Ghostty. Nothing switches on its own: the user picks.
7
+ * sign-in in iTerm or Ghostty. Without one, a pane uses this computer's normal
8
+ * sign-in, as any other terminal does. Nothing switches on its own: the user
9
+ * picks, and the choice is saved as theirs (panes.agentProfileChosen), so the
10
+ * one-time repair of an earlier release's Claude Code default never undoes it.
8
11
  */
9
12
  import type { Command } from './types.js';
10
13
  export interface SubsCommandDeps {
@@ -4,12 +4,17 @@
4
4
  *
5
5
  * A profile keeps the CLI's own sign-in in a directory of ZTC's (see
6
6
  * panes/agent_profiles.ts), so choosing one here never changes the CLI's
7
- * sign-in in iTerm or Ghostty. Nothing switches on its own: the user picks.
7
+ * sign-in in iTerm or Ghostty. Without one, a pane uses this computer's normal
8
+ * sign-in, as any other terminal does. Nothing switches on its own: the user
9
+ * picks, and the choice is saved as theirs (panes.agentProfileChosen), so the
10
+ * one-time repair of an earlier release's Claude Code default never undoes it.
8
11
  */
9
12
  import { homedir } from 'node:os';
10
13
  import { AGENT_CLIS } from '../../panes/agent_cli.js';
11
14
  import { ensureAgentProfile, isProfileName, listAgentProfiles } from '../../panes/agent_profiles.js';
12
- const USAGE = 'Usage: /subs · /subs use claude|codex [profile] (no profile: the CLI\'s own sign-in)';
15
+ /** Where a pane on no profile signs in: the CLI's own sign-in on this computer, as in any other terminal. */
16
+ const NORMAL_SIGN_IN = 'this computer\'s normal sign-in';
17
+ const USAGE = `Usage: /subs · /subs use claude|codex [profile] (no profile: ${NORMAL_SIGN_IN})`;
13
18
  export function createSubsCommand(deps = {}) {
14
19
  return {
15
20
  name: 'subs',
@@ -19,12 +24,13 @@ export function createSubsCommand(deps = {}) {
19
24
  const home = (deps.home ?? homedir)();
20
25
  const panes = ctx.config.get().panes ?? {};
21
26
  const chosen = panes.agentProfiles ?? {};
27
+ const own = panes.agentProfileChosen ?? {};
22
28
  const registered = (cli) => panes.agentProfileDirs?.[cli] ?? {};
23
29
  if (args.length === 0) {
24
30
  const lines = ['claude', 'codex'].map(cli => {
25
31
  const label = AGENT_CLIS[cli].label;
26
32
  const profiles = listAgentProfiles(cli, home, registered(cli));
27
- const using = chosen[cli] ? `the "${chosen[cli]}" profile` : `${label}'s own sign-in`;
33
+ const using = chosen[cli] ? `the "${chosen[cli]}" profile` : NORMAL_SIGN_IN;
28
34
  const known = profiles.length > 0 ? `Profiles: ${profiles.join(', ')}.` : 'No ZTC profiles yet.';
29
35
  return `${label}: new panes use ${using}. ${known}`;
30
36
  });
@@ -41,6 +47,7 @@ export function createSubsCommand(deps = {}) {
41
47
  const label = AGENT_CLIS[cli].label;
42
48
  const name = args[2];
43
49
  const next = { ...chosen };
50
+ const nextOwn = { ...own };
44
51
  if (name) {
45
52
  if (!isProfileName(name)) {
46
53
  ctx.addMessage({ role: 'system', content: `"${name}" is not a profile name: use letters, digits, ".", "_" or "-", up to 32.` });
@@ -48,16 +55,19 @@ export function createSubsCommand(deps = {}) {
48
55
  }
49
56
  ensureAgentProfile(cli, name, home, registered(cli));
50
57
  next[cli] = name;
58
+ nextOwn[cli] = name;
51
59
  }
52
60
  else {
53
61
  delete next[cli];
62
+ delete nextOwn[cli];
54
63
  }
55
- ctx.config.set('panes', { ...panes, agentProfiles: next });
64
+ ctx.config.set('panes', { ...panes, agentProfiles: next, agentProfileChosen: nextOwn });
65
+ await ctx.config.save();
56
66
  ctx.addMessage({
57
67
  role: 'system',
58
68
  content: name
59
69
  ? `New ${label} panes use the "${name}" profile. Sign in there the first time one opens; ${label}'s sign-in in other terminals doesn't change.`
60
- : `New ${label} panes use ${label}'s own sign-in.`,
70
+ : `New ${label} panes use ${NORMAL_SIGN_IN}.`,
61
71
  });
62
72
  },
63
73
  };
@@ -13,6 +13,7 @@ import type { SlashUsage } from './usage_spec.js';
13
13
  import type { KeyEvent } from '../../ui/widgets/types.js';
14
14
  import type { EvidenceSnapshot } from '../runtime/evidence.js';
15
15
  import type { CheckedCommandResult } from '../runtime/checked_commands.js';
16
+ import type { ToolCapability } from '../runtime/capabilities.js';
16
17
  import type { CommandExecutionPolicy } from '../runtime/command_execution_policy.js';
17
18
  import type { WorkspaceCollisionSnapshot } from '../../workspace_collision.js';
18
19
  import type { DiagnosticSnapshot } from '../../diagnostics/session_export.js';
@@ -314,6 +315,8 @@ export interface MirrorController {
314
315
  type: string;
315
316
  data: Record<string, unknown>;
316
317
  }) => void;
318
+ /** What a started mirror says once about connecting from other machines (an open one: they need sign-in). */
319
+ accessNotice?: () => string | null | undefined;
317
320
  sharing?: {
318
321
  create(label: string, ttlSeconds: number): {
319
322
  id: string;
@@ -756,6 +759,13 @@ export interface Command {
756
759
  handler: (args: string[], ctx: CommandContext) => void | Promise<void>;
757
760
  /** Whether this command is safe/intended for the agent to invoke via ztc_command. Default: false. */
758
761
  agentRunnable?: boolean;
762
+ /**
763
+ * What the command does, run by the agent through ztc_command, that the agent's permission profile governs: the tool
764
+ * runtime checks them as that call's own capabilities, so a profile refuses the command, or asks first, as it does
765
+ * a tool with them. /claude and /codex start a program that runs commands (shell_exec). Absent: nothing beyond
766
+ * ztc_command's own.
767
+ */
768
+ agentCapabilities?: readonly ToolCapability[];
759
769
  /** Grouping label for the agent-facing description (e.g. "zerg", "manifest", "config"). */
760
770
  category?: string;
761
771
  /**
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `/ztc` — open ZTC in a new pane next to this one, the sibling of `/claude` and `/codex`.
3
+ *
4
+ * The pane opens in this pane's directory and is placed as theirs are, on the route this pane runs on now: its
5
+ * provider, model, auth mode and reasoning effort, as a split of it starts (resolveSiblingRoute). `--provider`,
6
+ * `--model` and `--effort` name another, checked as open_pane checks a worker's route (resolveWorkerRoute) before
7
+ * anything opens. Text after the flags is the new pane's first task, delivered as open_pane delivers a ZTC worker's:
8
+ * after every launch flag, behind `--`. `--` ends /ztc's own flags too, so a task may start with a dash. Nothing is
9
+ * saved: the route is the new pane's own launch flags, and the default for new panes stays as it was.
10
+ *
11
+ * An agent's /ztc (ztc_command) follows the rules of the ZTC workers an agent opens with create_ztc_pane: a ZTC pane
12
+ * runs an agent that runs commands, so the agent's permission profile governs it as it governs a shell (shell_exec),
13
+ * as for /claude and /codex. A new ZTC pane runs under the profile's saved permissions, so one an agent opens opens
14
+ * only when those allow nothing more than the agent's own pane runs under, and, as every pane ZTC's own agent opens,
15
+ * without MotSi.
16
+ */
17
+ import type { Command } from './types.js';
18
+ /** /ztc's usage, as /help and its refusals show it. */
19
+ export declare const ZTC_USAGE = "/ztc [--provider <id>] [--model <id>] [--effort <level>] [--] [task]";
20
+ export declare const ztcPaneCommand: Command;
@@ -0,0 +1,239 @@
1
+ /**
2
+ * `/ztc` — open ZTC in a new pane next to this one, the sibling of `/claude` and `/codex`.
3
+ *
4
+ * The pane opens in this pane's directory and is placed as theirs are, on the route this pane runs on now: its
5
+ * provider, model, auth mode and reasoning effort, as a split of it starts (resolveSiblingRoute). `--provider`,
6
+ * `--model` and `--effort` name another, checked as open_pane checks a worker's route (resolveWorkerRoute) before
7
+ * anything opens. Text after the flags is the new pane's first task, delivered as open_pane delivers a ZTC worker's:
8
+ * after every launch flag, behind `--`. `--` ends /ztc's own flags too, so a task may start with a dash. Nothing is
9
+ * saved: the route is the new pane's own launch flags, and the default for new panes stays as it was.
10
+ *
11
+ * An agent's /ztc (ztc_command) follows the rules of the ZTC workers an agent opens with create_ztc_pane: a ZTC pane
12
+ * runs an agent that runs commands, so the agent's permission profile governs it as it governs a shell (shell_exec),
13
+ * as for /claude and /codex. A new ZTC pane runs under the profile's saved permissions, so one an agent opens opens
14
+ * only when those allow nothing more than the agent's own pane runs under, and, as every pane ZTC's own agent opens,
15
+ * without MotSi.
16
+ */
17
+ import { randomUUID } from 'node:crypto';
18
+ import { homedir } from 'node:os';
19
+ import { sep } from 'node:path';
20
+ import { buildProviderChoices, routeWord } from '../../app/runtime_choices.js';
21
+ import { configStore } from '../../config.js';
22
+ import { permissionsBeyond, savedPermissionSettings } from '../../config/permissions.js';
23
+ import { nextPaneTitle } from '../../panes/agent_cli.js';
24
+ import { PANE_TASK_AS_MESSAGE_ENV } from '../../panes/initial_input.js';
25
+ import { MOTSI_PANE_ENV, remoteViewMotsi, throughMotsi } from '../../panes/motsi.js';
26
+ import { resolveSiblingRoute, resolveWorkerRoute, signInNeeded } from '../../panes/worker_route.js';
27
+ import { buildZtcPaneLaunchCommand, createZtcLaunchSpec } from '../../panes/ztc_launch.js';
28
+ import { knownRouterProviderName } from '../backends/router_keys.js';
29
+ import { ToolCapability } from '../runtime/capabilities.js';
30
+ import { childZtcPaneEnv, getMuxTransport, listWorkspacePanes, notePendingPaneLaunch, waitForPaneCreatedOrError } from '../tools/pane.js';
31
+ import { modelRouteStatus } from './provider_choices.js';
32
+ /** /ztc's usage, as /help and its refusals show it. */
33
+ export const ZTC_USAGE = '/ztc [--provider <id>] [--model <id>] [--effort <level>] [--] [task]';
34
+ const USAGE_LINE = `Usage: ${ZTC_USAGE}`;
35
+ const HELP = `${USAGE_LINE}\n`
36
+ + 'Opens ZTC in a new pane next to this one, in this pane\'s directory, on the route this pane runs on now: its '
37
+ + 'provider, model, auth mode and reasoning effort. --provider, --model and --effort start it on the route they name '
38
+ + 'instead, checked against Zerg Router\'s list first; a model named alone finds its provider. Text after the flags '
39
+ + 'is the new pane\'s first task; -- ends the flags, so a task can start with a dash. Nothing is saved.';
40
+ const NEEDS_PANES = '/ztc opens ZTC in a new pane, which needs ZTC\'s panes: start ZTC with zmux (plain `ztc`) or use the desktop app.';
41
+ /** The parts of the new pane's route /ztc's flags name. */
42
+ const ROUTE_FLAGS = new Map([['--provider', 'provider'], ['--model', 'model'], ['--effort', 'effort']]);
43
+ /**
44
+ * Read BODY, the text after `/ztc`: its flags (`--model x` or `--model=x`), up to the first word that doesn't start
45
+ * with a dash or up to `--`, then the task, the rest as typed. A flag /ztc doesn't take, or one with no value, is
46
+ * refused: the answer is then why, said with the usage line, and nothing opens.
47
+ */
48
+ function parseZtcPaneRequest(body) {
49
+ const route = {};
50
+ let help = false;
51
+ let rest = body.trimStart();
52
+ /** The next word, taken off REST. */
53
+ const take = () => {
54
+ const word = rest.match(/^\S+/)?.[0] ?? '';
55
+ rest = rest.slice(word.length).trimStart();
56
+ return word;
57
+ };
58
+ while (rest.startsWith('-')) {
59
+ const word = take();
60
+ if (word === '--')
61
+ break;
62
+ const equals = word.indexOf('=');
63
+ const flag = equals < 0 ? word : word.slice(0, equals);
64
+ if (flag === '--help') {
65
+ help = true;
66
+ continue;
67
+ }
68
+ const part = ROUTE_FLAGS.get(flag);
69
+ if (!part)
70
+ return `/ztc doesn't take ${flag}.`;
71
+ // A value is the next word, unless that is another flag: none was given.
72
+ const value = equals >= 0 ? word.slice(equals + 1) : rest.startsWith('-') ? '' : take();
73
+ if (!value)
74
+ return `/ztc: ${flag} needs a value.`;
75
+ route[part] = value;
76
+ }
77
+ return { ...route, task: rest.trim(), help };
78
+ }
79
+ /** CWD as the person reads it: the home directory as ~. */
80
+ function shownPath(cwd) {
81
+ const home = homedir();
82
+ if (cwd === home)
83
+ return '~';
84
+ return cwd.startsWith(home + sep) ? `~${cwd.slice(home.length)}` : cwd;
85
+ }
86
+ /**
87
+ * ROUTE as the panes' menus name it, by how it is reached, then the provider and model, and the effort it starts at:
88
+ * "Zerg Router · Morph · morph/morph-kimik31 · high effort", "your key · OpenAI · gpt-5.4", "… · high effort (saved)".
89
+ */
90
+ function describeRoute(route) {
91
+ const provider = route.providerOverride;
92
+ const routed = route.authMode === 'zrouter';
93
+ const status = modelRouteStatus(configStore);
94
+ const catalog = configStore.getRouterCatalog();
95
+ const listed = buildProviderChoices({ catalog, routerSession: status.routerSession, directReady: status.directProviders,
96
+ selected: { provider, routed } }).find(choice => choice.selected).short_label;
97
+ // With no list of Router's to name it (Router out of reach), a provider ZTC knows as Router's still goes by its name.
98
+ const label = listed === provider ? knownRouterProviderName(catalog, provider) ?? listed : listed;
99
+ const level = route.extraArgs[0] === '--effort' ? route.extraArgs[1] : undefined;
100
+ // With no effort of its own, the new pane starts at the one the profile saves for its model, if any.
101
+ const saved = level === undefined ? configStore.getSavedCodexEffort(provider, route.modelOverride) : undefined;
102
+ const effort = level ? ` · ${level} effort` : saved ? ` · ${saved} effort (saved)` : '';
103
+ return `${routeWord(provider, routed)} · ${label} · ${route.modelOverride}${effort}`;
104
+ }
105
+ /**
106
+ * Why a ZTC pane an agent opens now would run under more than the agent's own pane does, or undefined when it
107
+ * wouldn't: it runs under the profile's saved permission settings, and this pane may run under narrower ones for this
108
+ * session.
109
+ */
110
+ function widerThanThisPane() {
111
+ const saved = savedPermissionSettings(configStore.getConfigPath());
112
+ const current = configStore.get();
113
+ const beyond = permissionsBeyond(saved, current);
114
+ if (beyond.length === 0)
115
+ return undefined;
116
+ return `a new ZTC pane runs under the saved permissions (${saved.permissionProfile}), which allow more than this pane's `
117
+ + `(${configStore.getActivePermissionProfileId()}): ${beyond.join(', ')}. An agent can't open a pane that can do more than its own.`;
118
+ }
119
+ /** The names the workspace's panes go by, for the new pane's ("ZTC", else "ZTC 2" and on). */
120
+ async function paneTitles(transport) {
121
+ const panes = await listWorkspacePanes(transport, 3000);
122
+ return panes instanceof Error ? [] : panes.map(pane => pane.labels?.manual_title || pane.title);
123
+ }
124
+ export const ztcPaneCommand = {
125
+ name: 'ztc',
126
+ description: 'Open ZTC in a new pane next to this one, on the route this pane runs on or the provider, model and effort you name',
127
+ usage: ZTC_USAGE,
128
+ agentRunnable: true,
129
+ // A ZTC pane runs an agent that runs commands: the profile governs opening one as it governs a shell, as
130
+ // create_ztc_pane's shell_exec does for a ZTC agent's own panes and as for /claude and /codex.
131
+ agentCapabilities: [ToolCapability.SHELL_EXEC],
132
+ category: 'panes',
133
+ handler: async (args, ctx) => {
134
+ const say = (content) => ctx.addMessage({ role: 'system', content });
135
+ const request = parseZtcPaneRequest(args.join(' '));
136
+ if (typeof request === 'string') {
137
+ say(`${request}\n${USAGE_LINE}`);
138
+ return;
139
+ }
140
+ if (request.help) {
141
+ say(HELP);
142
+ return;
143
+ }
144
+ // A hosted workbench (ZTC_HOSTED=1) runs one agent pane per thread, whose pane manager would open any ZTC pane it is
145
+ // sent: refused as the app's own ZTC pane opener refuses one there (cli_ratatui.ts spawnZtcPane).
146
+ if (process.env.ZTC_HOSTED === '1') {
147
+ say('No ZTC pane was opened: Hosted workbenches allow one agent pane per thread.');
148
+ return;
149
+ }
150
+ // zmux and the desktop app alike: both open panes through the mux transport's create_pane.
151
+ const transport = getMuxTransport();
152
+ if (!transport) {
153
+ say(NEEDS_PANES);
154
+ return;
155
+ }
156
+ // As /claude and /codex read it: the ztc_command tool runs commands as the agent; what the person types in a ZTC
157
+ // pane, relayed input included, is the person's.
158
+ const byPerson = ctx.commandOrigin !== 'agent';
159
+ if (!byPerson) {
160
+ let wider;
161
+ try {
162
+ wider = widerThanThisPane();
163
+ }
164
+ catch (error) {
165
+ // A saved permission profile ZTC can't resolve: a pane started on it would not run.
166
+ wider = error.message;
167
+ }
168
+ if (wider) {
169
+ say(`No ZTC pane was opened: ${wider}`);
170
+ return;
171
+ }
172
+ }
173
+ const cwd = ctx.shell.getCwd();
174
+ // A provider or model named is checked as open_pane checks a worker's; otherwise this pane's own route, at the effort named.
175
+ // A Router route named with no current Router sign-in is refused as this pane's own is.
176
+ const route = request.provider !== undefined || request.model !== undefined
177
+ ? await resolveWorkerRoute({ provider: request.provider, model: request.model, effort: request.effort }, {
178
+ codexItself: 'use /codex', opens: 'ztc_pane',
179
+ signInNeeded: (expired, named) => signInNeeded(expired, named.model ?? named.label ?? named.provider)
180
+ })
181
+ : await resolveSiblingRoute(cwd, request.effort);
182
+ if (!route.ok) {
183
+ say(`No ZTC pane was opened: ${route.message}`);
184
+ return;
185
+ }
186
+ const title = nextPaneTitle('ZTC', await paneTitles(transport));
187
+ // The new pane's effort is the route's, or none of its own ("default"): never one this pane was launched with.
188
+ const extraArgs = route.extraArgs.length > 0 ? route.extraArgs : ['--effort', 'default'];
189
+ const spec = createZtcLaunchSpec({ cwd, title, providerOverride: route.providerOverride, modelOverride: route.modelOverride,
190
+ authMode: route.authMode, routerOrigin: route.routerOrigin, extraArgs });
191
+ const built = buildZtcPaneLaunchCommand(spec);
192
+ if (built instanceof Error) {
193
+ say(`No ZTC pane was opened: ${built.message.replace(/^Error: /, '')}`);
194
+ return;
195
+ }
196
+ // The task is the child's first message, after every flag of its own, as open_pane's worker gets its task. An agent's
197
+ // reaches the new pane's agent as a message, never as a command that pane would run as the person's.
198
+ const child = { command: built.command, args: request.task ? [...built.args, '--', request.task] : built.args };
199
+ const taskAsMessage = !byPerson && request.task ? { [PANE_TASK_AS_MESSAGE_ENV]: '1' } : {};
200
+ // The panes the person opens show in Zerg Router's Command Central while MotSi's remote view is on; the panes ZTC's
201
+ // own agent opens start without it (panes/motsi.ts).
202
+ const motsi = byPerson ? remoteViewMotsi(configStore.get().panes) : null;
203
+ const launched = motsi ? throughMotsi(motsi, title, child) : child;
204
+ const requestId = `ztc-pane-${randomUUID()}`;
205
+ // Main records the pane's route, as for create_ztc_pane's panes: a split or a restore of it starts there. The spec
206
+ // carries no task, so a restored session never replays it.
207
+ notePendingPaneLaunch(requestId, spec);
208
+ const created = waitForPaneCreatedOrError(transport, { requestId }, 15000);
209
+ const sent = transport.send({
210
+ type: 'create_pane',
211
+ request_id: requestId,
212
+ command: launched.command,
213
+ args: launched.args,
214
+ cwd,
215
+ title,
216
+ pane_type: 'ztc',
217
+ env: { ...childZtcPaneEnv(), ...(motsi ? MOTSI_PANE_ENV : {}), ...taskAsMessage },
218
+ });
219
+ if (!sent) {
220
+ created.catch(() => { });
221
+ say('Could not open ZTC: the renderer is not connected.');
222
+ return;
223
+ }
224
+ let event;
225
+ try {
226
+ event = await created;
227
+ }
228
+ catch (error) {
229
+ say(`Could not open ZTC: no pane appeared (${error.message}).`);
230
+ return;
231
+ }
232
+ if (event.type !== 'pane_created') {
233
+ // The wait ends on this request's pane or on the renderer's refusal of it.
234
+ say(`Could not open ZTC: the renderer refused the pane (${event.message}).`);
235
+ return;
236
+ }
237
+ say(`Opened ${title} in pane ${event.pane_id} (${shownPath(cwd)}) on ${describeRoute(route)}${request.task ? ', and sent it the task' : ''}.`);
238
+ },
239
+ };