@zergai/ztc 0.26.6-dev.202611240947 → 0.27.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 (268) hide show
  1. package/README.md +629 -167
  2. package/RUST_THIRD_PARTY_LICENSES.txt +5 -5
  3. package/bin/zmux-darwin-arm64 +0 -0
  4. package/bin/zmux-linux-x64 +0 -0
  5. package/bin/ztc-audio-darwin-arm64 +0 -0
  6. package/bin/ztc-capture-darwin-arm64 +0 -0
  7. package/bin/ztc-computer-darwin-arm64 +0 -0
  8. package/bin/ztc-llm-darwin-arm64 +0 -0
  9. package/bin/ztc-tts-darwin-arm64 +0 -0
  10. package/bin/ztc-tui-darwin-arm64 +0 -0
  11. package/bin/ztc-tui-linux-x64 +0 -0
  12. package/bin/zterm-darwin-arm64 +2 -2
  13. package/dist/App.js +6 -1
  14. package/dist/agent/agent.d.ts +21 -15
  15. package/dist/agent/agent.js +389 -163
  16. package/dist/agent/backends/codex_app_server.d.ts +7 -1
  17. package/dist/agent/backends/codex_app_server.js +11 -1
  18. package/dist/agent/backends/gemini.js +22 -8
  19. package/dist/agent/commands/batch.js +8 -0
  20. package/dist/agent/commands/config.js +10 -0
  21. package/dist/agent/commands/environment.js +5 -5
  22. package/dist/agent/commands/goal.d.ts +1 -0
  23. package/dist/agent/commands/goal.js +2 -1
  24. package/dist/agent/commands/index.js +2 -1
  25. package/dist/agent/commands/manifest.js +4 -0
  26. package/dist/agent/commands/optimize.js +5 -2
  27. package/dist/agent/commands/pane_cli.d.ts +29 -0
  28. package/dist/agent/commands/pane_cli.js +303 -0
  29. package/dist/agent/commands/settings.js +13 -3
  30. package/dist/agent/commands/shannon.js +8 -0
  31. package/dist/agent/commands/update.js +15 -3
  32. package/dist/agent/commands/zerg.js +31 -1
  33. package/dist/agent/commands/ztc_pane.js +3 -1
  34. package/dist/agent/factory.d.ts +4 -0
  35. package/dist/agent/factory.js +11 -1
  36. package/dist/agent/loop_policy.d.ts +42 -5
  37. package/dist/agent/loop_policy.js +206 -3
  38. package/dist/agent/runtime/command_jobs.d.ts +5 -0
  39. package/dist/agent/runtime/command_jobs.js +241 -31
  40. package/dist/agent/runtime/command_wait.d.ts +2 -0
  41. package/dist/agent/runtime/command_wait.js +1 -0
  42. package/dist/agent/runtime/done_report.d.ts +18 -0
  43. package/dist/agent/runtime/done_report.js +130 -0
  44. package/dist/agent/runtime/execution_context.js +4 -1
  45. package/dist/agent/runtime/failure_cause.d.ts +2 -0
  46. package/dist/agent/runtime/failure_cause.js +35 -0
  47. package/dist/agent/runtime/policy.d.ts +14 -2
  48. package/dist/agent/runtime/policy.js +104 -12
  49. package/dist/agent/runtime/quiet_job.d.ts +18 -0
  50. package/dist/agent/runtime/quiet_job.js +48 -0
  51. package/dist/agent/runtime/recovery.d.ts +1 -5
  52. package/dist/agent/runtime/recovery.js +2 -44
  53. package/dist/agent/runtime/tool_runtime.d.ts +1 -0
  54. package/dist/agent/runtime/tool_runtime.js +2 -0
  55. package/dist/agent/subagent.js +6 -1
  56. package/dist/agent/tools/deferred.js +1 -0
  57. package/dist/agent/tools/index.d.ts +2 -0
  58. package/dist/agent/tools/index.js +1 -0
  59. package/dist/agent/tools/outcome.d.ts +15 -0
  60. package/dist/agent/tools/outcome.js +107 -0
  61. package/dist/agent/tools/pane.d.ts +2 -1
  62. package/dist/agent/tools/pane.js +21 -3
  63. package/dist/agent/tools/registry.js +2 -0
  64. package/dist/agent/tools/shell.d.ts +1 -0
  65. package/dist/agent/tools/shell.js +128 -17
  66. package/dist/agent/tools/sim_domain_tools.js +4 -2
  67. package/dist/agent/tools/supervision.js +4 -2
  68. package/dist/agent/tools/types.d.ts +3 -0
  69. package/dist/app/command_context.js +5 -9
  70. package/dist/app/conversation_compaction.d.ts +4 -2
  71. package/dist/app/conversation_compaction.js +16 -5
  72. package/dist/app/headless_shell_mode.d.ts +14 -0
  73. package/dist/app/headless_shell_mode.js +7 -0
  74. package/dist/app/hosted_resident.d.ts +356 -0
  75. package/dist/app/hosted_resident.js +677 -0
  76. package/dist/app/restart.js +11 -2
  77. package/dist/app/session_manager.d.ts +5 -0
  78. package/dist/app/session_manager.js +21 -6
  79. package/dist/app/session_messages.js +6 -6
  80. package/dist/app/workspace_layout_controller.js +7 -0
  81. package/dist/batch/worktree.d.ts +10 -0
  82. package/dist/batch/worktree.js +15 -0
  83. package/dist/bench/registry.js +4 -2
  84. package/dist/cli_args.js +1 -1
  85. package/dist/cli_main.js +80 -10
  86. package/dist/cli_ratatui.d.ts +75 -0
  87. package/dist/cli_ratatui.js +485 -84
  88. package/dist/components/InputArea.js +4 -4
  89. package/dist/config/execution.d.ts +10 -0
  90. package/dist/config/execution.js +10 -0
  91. package/dist/config/hosted_runtime.d.ts +4 -1
  92. package/dist/config/hosted_runtime.js +4 -1
  93. package/dist/config/permission_pin.d.ts +34 -2
  94. package/dist/config/permission_pin.js +52 -2
  95. package/dist/config/person_command_policy.d.ts +38 -0
  96. package/dist/config/person_command_policy.js +11 -0
  97. package/dist/config/profiles.d.ts +21 -0
  98. package/dist/config/profiles.js +56 -2
  99. package/dist/config/types.d.ts +4 -1
  100. package/dist/config.js +34 -19
  101. package/dist/desktop/daily/codex_exec_adapter.js +7 -2
  102. package/dist/desktop/daily/desktop_wiring.d.ts +7 -1
  103. package/dist/desktop/daily/desktop_wiring.js +11 -3
  104. package/dist/desktop/daily/recipes.js +20 -4
  105. package/dist/desktop/health.d.ts +24 -0
  106. package/dist/desktop/health.js +151 -0
  107. package/dist/desktop/native_dialogs.d.ts +37 -0
  108. package/dist/desktop/native_dialogs.js +105 -0
  109. package/dist/diagnostics/session_export.d.ts +1 -0
  110. package/dist/diagnostics/session_export.js +28 -0
  111. package/dist/embedded/registry.js +4 -2
  112. package/dist/emulation/tool_adapters.js +9 -4
  113. package/dist/emulation/ztc_addendum.js +3 -0
  114. package/dist/headless.d.ts +11 -4
  115. package/dist/headless.js +99 -34
  116. package/dist/headless_approval.d.ts +6 -0
  117. package/dist/headless_cli.js +1 -1
  118. package/dist/hooks/runner.js +7 -6
  119. package/dist/library.d.ts +4 -0
  120. package/dist/library.js +3 -0
  121. package/dist/mcp/client.js +3 -3
  122. package/dist/modes/registry.js +13 -4
  123. package/dist/onboarding/setup_environment.js +13 -1
  124. package/dist/optimize/adapters/kernelbench.js +88 -10
  125. package/dist/optimize/adapters/types.d.ts +5 -0
  126. package/dist/optimize/executor.js +21 -0
  127. package/dist/panes/cli_install.d.ts +54 -0
  128. package/dist/panes/cli_install.js +157 -0
  129. package/dist/panes/model_catalog.js +3 -0
  130. package/dist/panes/new_pane_choices.d.ts +6 -2
  131. package/dist/panes/new_pane_choices.js +24 -12
  132. package/dist/panes/pane_cli_launch.d.ts +50 -0
  133. package/dist/panes/pane_cli_launch.js +124 -0
  134. package/dist/panes/pane_clis.d.ts +171 -0
  135. package/dist/panes/pane_clis.js +325 -0
  136. package/dist/panes/person_only_panes.d.ts +45 -0
  137. package/dist/panes/person_only_panes.js +117 -0
  138. package/dist/plugin/simulation_living.js +0 -2
  139. package/dist/plugin/simulation_living_engine.d.ts +1 -0
  140. package/dist/plugin/simulation_living_engine.js +1 -0
  141. package/dist/plugin/simulation_living_labels.d.ts +3 -0
  142. package/dist/plugin/simulation_living_labels.js +2 -0
  143. package/dist/router_auth.js +12 -1
  144. package/dist/session.js +26 -1
  145. package/dist/simulation/art/gemini_image.js +11 -5
  146. package/dist/simulation/domains/loader.js +25 -3
  147. package/dist/simulation/living/cold.d.ts +23 -0
  148. package/dist/simulation/living/cold.js +41 -0
  149. package/dist/simulation/living/context.d.ts +591 -1283
  150. package/dist/simulation/living/context.js +378 -244
  151. package/dist/simulation/living/contradictions.d.ts +14 -0
  152. package/dist/simulation/living/contradictions.js +282 -0
  153. package/dist/simulation/living/core/ids.d.ts +53 -0
  154. package/dist/simulation/living/core/ids.js +39 -0
  155. package/dist/simulation/living/core/kind.d.ts +20 -0
  156. package/dist/simulation/living/core/kind.js +15 -0
  157. package/dist/simulation/living/core/laws.d.ts +179 -0
  158. package/dist/simulation/living/core/laws.js +184 -0
  159. package/dist/simulation/living/core/ops.d.ts +257 -0
  160. package/dist/simulation/living/core/ops.js +34 -0
  161. package/dist/simulation/living/definer.d.ts +17 -1
  162. package/dist/simulation/living/definer.js +130 -51
  163. package/dist/simulation/living/definition.d.ts +174 -65
  164. package/dist/simulation/living/definition.js +287 -180
  165. package/dist/simulation/living/director.d.ts +80 -0
  166. package/dist/simulation/living/director.js +363 -0
  167. package/dist/simulation/living/frame.d.ts +108 -21
  168. package/dist/simulation/living/frame.js +111 -66
  169. package/dist/simulation/living/identifiers.d.ts +0 -1
  170. package/dist/simulation/living/identifiers.js +0 -3
  171. package/dist/simulation/living/index.d.ts +18 -9
  172. package/dist/simulation/living/index.js +18 -9
  173. package/dist/simulation/living/inference.d.ts +92 -50
  174. package/dist/simulation/living/inference.js +319 -175
  175. package/dist/simulation/living/knowledge.d.ts +28 -0
  176. package/dist/simulation/living/knowledge.js +73 -0
  177. package/dist/simulation/living/library.json +1177 -0
  178. package/dist/simulation/living/mechanics.d.ts +31 -34
  179. package/dist/simulation/living/mechanics.js +222 -138
  180. package/dist/simulation/living/model-input.d.ts +6 -3
  181. package/dist/simulation/living/model-input.js +18 -26
  182. package/dist/simulation/living/open-world.d.ts +74 -94
  183. package/dist/simulation/living/open-world.js +151 -30
  184. package/dist/simulation/living/phrases.d.ts +3 -0
  185. package/dist/simulation/living/phrases.js +37 -0
  186. package/dist/simulation/living/phrases.json +560 -0
  187. package/dist/simulation/living/projection.d.ts +316 -2
  188. package/dist/simulation/living/projection.js +50 -2
  189. package/dist/simulation/living/prompts/example-spec.json +11 -0
  190. package/dist/simulation/living/prompts/role-text.json +14 -0
  191. package/dist/simulation/living/prompts.d.ts +5 -0
  192. package/dist/simulation/living/prompts.js +275 -0
  193. package/dist/simulation/living/recall.d.ts +2 -2
  194. package/dist/simulation/living/reduce.d.ts +51 -14
  195. package/dist/simulation/living/reduce.js +941 -579
  196. package/dist/simulation/living/replay.d.ts +5 -4
  197. package/dist/simulation/living/replay.js +10 -9
  198. package/dist/simulation/living/runtime.d.ts +135 -25
  199. package/dist/simulation/living/runtime.js +1641 -583
  200. package/dist/simulation/living/scale.d.ts +96 -0
  201. package/dist/simulation/living/scale.js +124 -0
  202. package/dist/simulation/living/script.d.ts +5 -0
  203. package/dist/simulation/living/script.js +115 -0
  204. package/dist/simulation/living/shared-kinds.d.ts +4 -11
  205. package/dist/simulation/living/shared-kinds.js +11 -81
  206. package/dist/simulation/living/space.d.ts +14 -0
  207. package/dist/simulation/living/space.js +132 -0
  208. package/dist/simulation/living/state.d.ts +100 -0
  209. package/dist/simulation/living/state.js +393 -0
  210. package/dist/simulation/living/types.d.ts +829 -512
  211. package/dist/simulation/living/types.js +162 -187
  212. package/dist/simulation/living/world-rules.d.ts +100 -0
  213. package/dist/simulation/living/world-rules.js +267 -0
  214. package/dist/simulation/plugins/loader.js +11 -0
  215. package/dist/skills/loader.js +4 -0
  216. package/dist/tools.d.ts +1 -0
  217. package/dist/tools.js +1 -0
  218. package/dist/ui/ratatui/headless_pane_manager.d.ts +4 -1
  219. package/dist/ui/ratatui/headless_pane_manager.js +13 -9
  220. package/dist/ui/ratatui/pane_relay.js +29 -0
  221. package/dist/ui/ratatui/pane_type.d.ts +10 -0
  222. package/dist/ui/ratatui/pane_type.js +11 -0
  223. package/dist/ui/ratatui/process.d.ts +30 -0
  224. package/dist/ui/ratatui/process.js +133 -19
  225. package/dist/ui/ratatui/protocol.d.ts +124 -2
  226. package/dist/ui/ratatui/protocol.js +35 -0
  227. package/dist/ui/ratatui/relay_policy.js +3 -0
  228. package/dist/ui/ratatui/ztc_launch_trust.d.ts +2 -1
  229. package/dist/ui/ratatui/ztc_launch_trust.js +8 -1
  230. package/dist/ui/terminal_image.d.ts +12 -0
  231. package/dist/ui/terminal_image.js +21 -1
  232. package/dist/utils/codex_project_trust.d.ts +19 -0
  233. package/dist/utils/codex_project_trust.js +37 -0
  234. package/dist/utils/compaction.js +103 -20
  235. package/dist/utils/git_program_files.d.ts +19 -12
  236. package/dist/utils/git_program_files.js +411 -83
  237. package/dist/utils/host_shell.d.ts +10 -1
  238. package/dist/utils/host_shell.js +14 -1
  239. package/dist/utils/mid_turn_compaction.d.ts +2 -0
  240. package/dist/utils/mid_turn_compaction.js +2 -0
  241. package/dist/utils/models.js +6 -1
  242. package/dist/utils/sandbox.d.ts +109 -8
  243. package/dist/utils/sandbox.js +981 -187
  244. package/dist/utils/shell.d.ts +2 -0
  245. package/dist/utils/shell.js +10 -4
  246. package/dist/utils/subprocess_env.d.ts +47 -11
  247. package/dist/utils/subprocess_env.js +107 -15
  248. package/dist/utils/system_ps.d.ts +8 -0
  249. package/dist/utils/system_ps.js +39 -7
  250. package/dist/utils/unattended_compaction.d.ts +9 -0
  251. package/dist/utils/unattended_compaction.js +13 -0
  252. package/dist/utils/ztc_own_state.d.ts +8 -5
  253. package/dist/utils/ztc_own_state.js +17 -11
  254. package/dist/web/mirror_client.js +1 -0
  255. package/dist/web/mirror_stream.d.ts +50 -6
  256. package/dist/web/mirror_stream.js +160 -15
  257. package/dist/workflows/registry.js +3 -1
  258. package/dist/workspace/controller.js +12 -0
  259. package/dist/workspace_collision.d.ts +3 -0
  260. package/dist/workspace_collision.js +14 -1
  261. package/dist/workspace_session_context.js +2 -1
  262. package/dist/zlm-embed.mjs +3823 -1970
  263. package/node_modules/@zerg/model-contracts/README.md +16 -4
  264. package/node_modules/@zerg/model-contracts/index.js +6 -1
  265. package/npm-shrinkwrap.json +1 -1
  266. package/package.json +42 -24
  267. package/packages/model-contracts/README.md +16 -4
  268. package/packages/model-contracts/index.js +6 -1
@@ -1,5 +1,6 @@
1
1
  import { RateLimitError } from './rate_limit.js';
2
2
  import { type CodexModel } from '../../utils/codex_models.js';
3
+ import { untrustedProjectsConfig, type UntrustedProject } from '../../utils/codex_project_trust.js';
3
4
  import type { Message, ToolDefinition } from '../../types.js';
4
5
  import type { AgentBackend, BackendObservation, BackendRequest, BackendResponse, ClientToolCallResult, LlmMessage, StreamEvent } from './types.js';
5
6
  type JsonObject = Record<string, unknown>;
@@ -103,6 +104,12 @@ export declare function codexPaneEnv(source?: NodeJS.ProcessEnv): {
103
104
  * and ZTC looks for none, so this says what its host does about it.
104
105
  */
105
106
  export declare const CODEX_HOSTED_NO_SIGN_IN: string;
107
+ /**
108
+ * The thread config that marks a thread's folder and every folder above it untrusted, as given and as it resolves, so a
109
+ * thread ZTC starts loads no project-local Codex config (utils/codex_project_trust.ts, which the desktop daily driver's
110
+ * delegated Codex workers mark their folders with too).
111
+ */
112
+ export { untrustedProjectsConfig, type UntrustedProject };
106
113
  export interface CodexTurnOptions {
107
114
  model: string;
108
115
  system: string;
@@ -282,4 +289,3 @@ export declare class CodexAppServerBackend implements AgentBackend {
282
289
  private streamTurn;
283
290
  close(): void;
284
291
  }
285
- export {};
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { RateLimitError, parseResetAt } from './rate_limit.js';
4
4
  import { CODEX_APP_SERVER_PROVIDER } from './provider_ids.js';
5
5
  import { parseCodexModelRow } from '../../utils/codex_models.js';
6
+ import { untrustedProjectsConfig } from '../../utils/codex_project_trust.js';
6
7
  import { ModelNotServedError } from './model_not_served.js';
7
8
  import { getVersion } from '../../utils/version.js';
8
9
  import { NativeObservationLimitError } from '../runtime/provider_native_evidence.js';
@@ -127,6 +128,12 @@ export const CODEX_HOSTED_NO_SIGN_IN = 'codex_app_server has no sign-in in its C
127
128
  + '(ZTC_CODEX_ENV_ALLOWLIST), Codex runs only on the sign-in its CODEX_HOME holds and is given no key from the environment '
128
129
  + 'in its place (OPENAI_API_KEY, CODEX_API_KEY, CODEX_AUTH_JSON). The host signs Codex in there (CODEX_HOME=<folder> codex '
129
130
  + 'login), or runs this thread through Zerg Router.';
131
+ /**
132
+ * The thread config that marks a thread's folder and every folder above it untrusted, as given and as it resolves, so a
133
+ * thread ZTC starts loads no project-local Codex config (utils/codex_project_trust.ts, which the desktop daily driver's
134
+ * delegated Codex workers mark their folders with too).
135
+ */
136
+ export { untrustedProjectsConfig };
130
137
  /** What ZTC answers a Codex server request it has no screen for. */
131
138
  function unsupportedServerRequestMessage(method) {
132
139
  const instead = method === 'item/tool/requestUserInput' ? ' Ask the person with the ask_user tool instead.' : '';
@@ -854,13 +861,16 @@ export class CodexAppServerClient {
854
861
  * Start a fresh codex thread. Required tools never degrade to a toolless turn.
855
862
  */
856
863
  async startThread(options, sendDynamicTools, dynamicToolsPayload) {
864
+ const cwd = process.cwd();
857
865
  const threadStartParams = {
858
866
  model: options.model,
859
- cwd: process.cwd(),
867
+ cwd,
860
868
  baseInstructions: options.system || null,
861
869
  ephemeral: true,
862
870
  approvalPolicy: 'never',
863
871
  sandbox: this.sandbox,
872
+ // No project-local Codex config: the thread's folder and every folder above it are untrusted.
873
+ config: untrustedProjectsConfig(cwd),
864
874
  };
865
875
  // Only add the key when tools are present — the param is experimental, so
866
876
  // older codex must never see it.
@@ -1,7 +1,20 @@
1
1
  import { reasoningRequestParams } from '@zerg/model-contracts';
2
2
  import { BaseBackend } from './base.js';
3
+ import { redactSentCredentials } from './http_error.js';
3
4
  import { MODEL_REQUEST_REDIRECT, refuseModelRedirect } from './model_redirect.js';
4
5
  import { fittedBody, GEMINI_IMAGE_LIMITS, olderToolImages, olderToolImagesLine, planToolImages, toolImageCaption } from './tool_result_images.js';
6
+ /** COUNTS as ZTC's usage: the thoughts are output, and the cached tokens part of the prompt, as Google bills them. */
7
+ function geminiUsage(counts) {
8
+ const inputTokens = (counts.promptTokenCount ?? 0) + (counts.toolUsePromptTokenCount ?? 0);
9
+ const outputTokens = (counts.candidatesTokenCount ?? 0) + (counts.thoughtsTokenCount ?? 0);
10
+ return {
11
+ inputTokens,
12
+ outputTokens,
13
+ totalTokens: counts.totalTokenCount ?? inputTokens + outputTokens,
14
+ ...(counts.cachedContentTokenCount === undefined ? {} : { cachedInputTokens: counts.cachedContentTokenCount }),
15
+ ...(counts.thoughtsTokenCount === undefined ? {} : { reasoningTokens: counts.thoughtsTokenCount }),
16
+ };
17
+ }
5
18
  export class GeminiBackend extends BaseBackend {
6
19
  apiKey;
7
20
  apiEndpoint;
@@ -13,20 +26,24 @@ export class GeminiBackend extends BaseBackend {
13
26
  this.toolImages = config.toolImages ?? GEMINI_IMAGE_LIMITS;
14
27
  }
15
28
  async generate(request) {
16
- const url = `${this.apiEndpoint}/${encodeURIComponent(request.model)}:generateContent?key=${this.apiKey}`;
29
+ // The key goes in x-goog-api-key (https://aistudio.google.com/docs/api-key), never in the URL, where an error, a
30
+ // redirect or a log line could carry it on.
31
+ const url = `${this.apiEndpoint}/${encodeURIComponent(request.model)}:generateContent`;
32
+ const headers = { 'Content-Type': 'application/json', 'x-goog-api-key': this.apiKey };
17
33
  // Gemini limits the whole request: the oldest of the latest tool images give way until it fits (fittedBody).
18
34
  const body = fittedBody((this.toolImages || undefined)?.maxRequestBytes, sent => JSON.stringify(this.buildBody(request, sent)));
19
35
  const response = await fetch(url, {
20
36
  method: 'POST',
21
- headers: { 'Content-Type': 'application/json' },
37
+ headers,
22
38
  body,
23
39
  signal: request.signal,
24
40
  redirect: MODEL_REQUEST_REDIRECT,
25
41
  });
26
- await refuseModelRedirect(response, url);
42
+ await refuseModelRedirect(response, url, headers);
27
43
  if (!response.ok) {
44
+ // What Google answered can echo the request, its key header included: the key is withheld from it.
28
45
  const errorText = await response.text();
29
- throw new Error(`API error (${response.status}): ${errorText}`);
46
+ throw new Error(`API error (${response.status}): ${redactSentCredentials(errorText, headers)}`);
30
47
  }
31
48
  const data = await response.json();
32
49
  const candidate = data.candidates?.[0];
@@ -49,13 +66,10 @@ export class GeminiBackend extends BaseBackend {
49
66
  });
50
67
  }
51
68
  }
52
- const inputTokens = data.usageMetadata?.promptTokenCount ?? 0;
53
- const outputTokens = data.usageMetadata?.candidatesTokenCount ?? 0;
54
- const totalTokens = data.usageMetadata?.totalTokenCount ?? (inputTokens + outputTokens);
55
69
  return {
56
70
  content: blocks,
57
71
  stopReason: candidate?.finishReason || 'unknown',
58
- usage: data.usageMetadata ? { inputTokens, outputTokens, totalTokens } : undefined
72
+ usage: data.usageMetadata ? geminiUsage(data.usageMetadata) : undefined
59
73
  };
60
74
  }
61
75
  /** REQUEST's body, with at most SENT of the latest tool images. */
@@ -6,6 +6,8 @@
6
6
  * /batch-stop - Cancel running batch and clean up worktrees
7
7
  */
8
8
  import { BatchOrchestrator, getCurrentBatch, setCurrentBatch, clearCurrentBatch, getRepoRoot, } from '../../batch/index.js';
9
+ import { BATCH_GIT_UNDER_PIN } from '../../batch/worktree.js';
10
+ import { personProgramRefusal } from '../../config/permission_pin.js';
9
11
  import { getWorkerExecutor } from '../../worker/index.js';
10
12
  import { formatDuration } from '../../utils/path_format.js';
11
13
  /**
@@ -24,6 +26,12 @@ export const batchCommand = {
24
26
  });
25
27
  return;
26
28
  }
29
+ // Its git runs the work tree's hooks and filters outside any sandbox: under its host's pin, no batch starts.
30
+ const pinned = personProgramRefusal('No batch was started', BATCH_GIT_UNDER_PIN.what, BATCH_GIT_UNDER_PIN.instead);
31
+ if (pinned) {
32
+ ctx.addMessage({ role: 'system', content: pinned });
33
+ return;
34
+ }
27
35
  // Validate git repo
28
36
  try {
29
37
  await getRepoRoot(process.cwd());
@@ -336,6 +336,9 @@ const CONFIG_HELP = [
336
336
  'Any other word searches the settings, for example /config compaction.',
337
337
  ].join('\n');
338
338
  /** Whether the permission profile CONFIG runs under now limits the agent (config/profile_limits.ts). */
339
+ /** The /config subcommands that move where ZTC sends a saved key. */
340
+ const ROUTE_SUBCOMMANDS = new Set(['endpoint', 'zrouter-url', 'zrouter', 'routing', 'auth-mode', 'authmode', 'provider', 'openai-compat',
341
+ 'openai_compatible', 'compat']);
339
342
  function agentLimited(config) {
340
343
  return profileLimitsAgent(config.getEffectivePermissionProfile?.(), config.get().sandbox);
341
344
  }
@@ -366,6 +369,13 @@ export const configCommand = {
366
369
  await ctx.config.withConfigScope('global', () => configCommand.handler(rest, ctx));
367
370
  return;
368
371
  }
372
+ // Where a saved key goes is the person's: under a profile that limits the agent, the agent's /config that moves it is
373
+ // refused, as its /config scope clear is. Asking what it is set to stays the agent's.
374
+ if (ctx.commandOrigin === 'agent' && agentLimited(ctx.config) && value.trim() && subCmd !== undefined
375
+ && ROUTE_SUBCOMMANDS.has(subCmd)) {
376
+ ctx.addMessage({ role: 'system', content: `Only you can change /config ${subCmd}: under a permission profile that limits the agent, it moves where a saved key goes. Nothing was changed.` });
377
+ return;
378
+ }
369
379
  switch (subCmd) {
370
380
  case 'max-tokens': {
371
381
  const input = value.trim().toLowerCase();
@@ -1,4 +1,6 @@
1
1
  import { createEnvironment, getEnvironment, listEnvironments, openEnvironment, releaseEnvironment, checkpointEnvironment, restoreEnvironment, pauseEnvironment, resumeEnvironment, discardEnvironment, addEnvironmentNote, startEnvironmentService, environmentForWorkspace, environmentSummary, } from '../../environment/store.js';
2
+ import { configStore } from '../../config.js';
3
+ import { personCommandPolicy } from '../../config/person_command_policy.js';
2
4
  import { activeProfile } from '../../config/profiles.js';
3
5
  const usage = '/environment [list|create <name>|open <name>|status [--json]|checkpoint [label]|restore <ID>|pause|resume|leave|note <text>|service start <name> <command>|discard]';
4
6
  const activeOperations = new Set();
@@ -78,11 +80,9 @@ export const environmentCommand = {
78
80
  message = 'Setup note saved. Future agent turns receive this note.';
79
81
  }
80
82
  else if (action === 'service' && args[1] === 'start') {
81
- const config = ctx.config.get();
82
- const permissionId = config.permissionProfile || 'trusted';
83
- const receipt = await startEnvironmentService(record.name, sessionId, args[2] ?? '', args.slice(3).join(' '), {
84
- profileId: permissionId, profile: ctx.config.getEffectivePermissionProfile?.(permissionId), sandbox: config.sandbox,
85
- }, ctx.shell.getCwd());
83
+ // The person's command, planned as the person's are: under its host's pin, with the OS sandbox required
84
+ // (config/person_command_policy.ts), which a pinned profile that runs no command of the agent's needs not.
85
+ const receipt = await startEnvironmentService(record.name, sessionId, args[2] ?? '', args.slice(3).join(' '), personCommandPolicy(configStore), ctx.shell.getCwd());
86
86
  message = `Service launching: ${receipt.name}\nDirectory: ${receipt.cwd}\nLog: ${receipt.logPath}\nUse /environment status to check its receipt; launch does not guarantee readiness.`;
87
87
  }
88
88
  else if (action === 'leave' || action === 'discard') {
@@ -145,6 +145,7 @@ export interface GoalTurnFacts extends GoalTurnAccounting {
145
145
  * report to the user.
146
146
  */
147
147
  turnSummary: string;
148
+ outcome?: 'done' | 'blocked' | 'needs_input';
148
149
  /**
149
150
  * True when this turn ran a command that failed. Paired with hadSuccessfulTool
150
151
  * to identify an execution-failure turn; see isExecutionFailureTurn. Required so
@@ -717,7 +717,8 @@ export function decideContinuation(goal, facts, now) {
717
717
  }
718
718
  // Adopted requests use the same completion channel as explicit goals. Caps
719
719
  // above still take precedence, and explicit measurement criteria stay authoritative.
720
- if (next.sustained && !next.plateau && detectGoalCompletion(facts.turnSummary)) {
720
+ if (next.sustained && !next.plateau
721
+ && (facts.outcome === 'done' || (facts.outcome === undefined && detectGoalCompletion(facts.turnSummary)))) {
721
722
  next.status = 'complete';
722
723
  next.exitReason = { kind: 'objective_complete', reason: 'Objective completion declared.', evidenceIds: [] };
723
724
  return { next, decision: { kind: 'stop', status: 'complete', reason: 'objective complete', note: goalFinalNote(next) } };
@@ -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 { paneCliCommands } from './pane_cli.js';
35
36
  import { ztcPaneCommand } from './ztc_pane.js';
36
37
  import { subsCommand } from './subs.js';
37
38
  import { diffCommand } from './diff.js';
@@ -86,7 +87,7 @@ import { effortCommand, thinkingCommand, reasoningCommand, fastCommand } from '.
86
87
  import { runtimePluginRegistry } from '../../plugin/runtime_registry.js';
87
88
  const commandList = [];
88
89
  const helpCommand = makeHelpCommand(() => commandList);
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);
90
+ 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, ...paneCliCommands, 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);
90
91
  export const commands = commandList;
91
92
  export function refreshPluginCommands() {
92
93
  const existing = new Set(commandList.map(command => command.name));
@@ -9,6 +9,7 @@
9
9
  * /manifest list — List all available manifests
10
10
  * /manifest load [name|path] — Load manifest into connected Zerg
11
11
  */
12
+ import { ToolCapability } from '../runtime/capabilities.js';
12
13
  import { createModeContext } from './mode_commands.js';
13
14
  import { manifestCreateHandler, manifestDeriveHandler, manifestValidateHandler, manifestPreviewHandler, manifestListHandler, zergLoadManifestHandler, } from '../../modes/handlers.js';
14
15
  /**
@@ -46,6 +47,9 @@ export const manifestCommand = {
46
47
  description: 'Manifest operations (create, derive, validate, preview, list, load)',
47
48
  usage: '<create|derive|validate|preview|list|load> [args]',
48
49
  agentRunnable: true,
50
+ // derive and load read files ZTC's own process opens (a template's companions, a manifest path), past every path policy;
51
+ // create reads none (it starts a draft).
52
+ agentCapabilities: args => ['derive', 'load'].includes(String(args[0] ?? '').toLowerCase()) ? [ToolCapability.SHELL_EXEC] : [],
49
53
  category: 'manifest',
50
54
  handler: async (args, ctx) => {
51
55
  const [subCmd, ...rest] = args;
@@ -51,7 +51,7 @@ function help_text(optimize) {
51
51
  'Flags:',
52
52
  ' --engine <id> Force a primary engine',
53
53
  ' --pipeline a,b,c Force a full pipeline',
54
- ' --target <ref> Explicit target (file:, mode:, emulation:, repo:, task:, workflow: supported)',
54
+ ' --target <ref> What to optimize (file:, mode:, emulation:, repo:, task:, workflow: supported), never a KernelBench target',
55
55
  ' --eval <ref> Explicit evaluator or benchmark',
56
56
  ' --objective <name> Objective such as latency, score, pass_rate, correctness',
57
57
  ' --mode <id> Runtime mode/emulation constraint',
@@ -62,7 +62,10 @@ function help_text(optimize) {
62
62
  '',
63
63
  'Notes:',
64
64
  ' - Native KernelBench execution supports concrete file/artifact targets when paired with a task selector such as --eval kernelbench:level1/22.',
65
- ' - KernelBench PTX and DIMC evaluation paths remain legacy-backed.',
65
+ ' - KernelBench PTX and the harness\'s other targets remain legacy-backed.',
66
+ ' - Name a KernelBench target with target=NAME in the request (or --eval kernelbench:target=NAME); the harness gets --target NAME.',
67
+ ' /optimize\'s own --target names what to optimize, never a KernelBench target.',
68
+ ' A target= that names no target, two targets, or a target beside a file target (the native path is CUDA only) stop the run.',
66
69
  ].join('\n');
67
70
  }
68
71
  function preview_message(spec, artifacts) {
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `/antigravity`, `/pi`, `/opencode`, `/gemini`, `/copilot` and `/cursor`: open the person's own coding-agent CLI in a
3
+ * new pane, in this pane's folder, as `/claude` and `/codex` do (panes/pane_clis.ts holds each CLI as data). Plain text
4
+ * after the command is the opening prompt; text that starts with a flag is the CLI's own arguments. The CLI signs in
5
+ * with the person's own account through its own flow; ZTC only runs it, unmodified.
6
+ *
7
+ * When the CLI isn't installed, the person is offered its vendor's own install commands for this platform, verbatim,
8
+ * to run in a new pane (panes/cli_install.ts); when the install exits 0 and the CLI is found, it opens. Only the
9
+ * person's own input starts an install. `/agents` lists every CLI, whether it is installed (where, and its version),
10
+ * and how to install it; `/agents install <cli>` offers the install.
11
+ *
12
+ * Antigravity is the person's alone: Google's Antigravity FAQ says wrapping agy inside third-party coding agents or
13
+ * applications isn't supported on consumer plans, so an agent's or relayed `/antigravity` is refused, ztc_command never
14
+ * offers it, a headless ZTC (whose input is the program's that runs it) doesn't open it, and no agent types into,
15
+ * messages or restarts its pane (panes/person_only_panes.ts).
16
+ */
17
+ import { type PaneCliId } from '../../panes/pane_clis.js';
18
+ import type { PaneCommandTransport } from '../../ui/ratatui/pane_relay.js';
19
+ import type { Command } from './types.js';
20
+ export interface PaneCliCommandDeps {
21
+ transport?: () => PaneCommandTransport | null;
22
+ /** The environment the CLI is looked for in and started with (default: this process's, as the command runs). */
23
+ env?: () => NodeJS.ProcessEnv;
24
+ platform?: NodeJS.Platform;
25
+ }
26
+ export declare function createPaneCliCommand(id: PaneCliId, deps?: PaneCliCommandDeps): Command;
27
+ export declare function createAgentsCommand(deps?: PaneCliCommandDeps): Command;
28
+ /** The commands for the CLIs the shared launcher opens, in the registry's order, and /agents. */
29
+ export declare const paneCliCommands: readonly Command[];
@@ -0,0 +1,303 @@
1
+ /**
2
+ * `/antigravity`, `/pi`, `/opencode`, `/gemini`, `/copilot` and `/cursor`: open the person's own coding-agent CLI in a
3
+ * new pane, in this pane's folder, as `/claude` and `/codex` do (panes/pane_clis.ts holds each CLI as data). Plain text
4
+ * after the command is the opening prompt; text that starts with a flag is the CLI's own arguments. The CLI signs in
5
+ * with the person's own account through its own flow; ZTC only runs it, unmodified.
6
+ *
7
+ * When the CLI isn't installed, the person is offered its vendor's own install commands for this platform, verbatim,
8
+ * to run in a new pane (panes/cli_install.ts); when the install exits 0 and the CLI is found, it opens. Only the
9
+ * person's own input starts an install. `/agents` lists every CLI, whether it is installed (where, and its version),
10
+ * and how to install it; `/agents install <cli>` offers the install.
11
+ *
12
+ * Antigravity is the person's alone: Google's Antigravity FAQ says wrapping agy inside third-party coding agents or
13
+ * applications isn't supported on consumer plans, so an agent's or relayed `/antigravity` is refused, ztc_command never
14
+ * offers it, a headless ZTC (whose input is the program's that runs it) doesn't open it, and no agent types into,
15
+ * messages or restarts its pane (panes/person_only_panes.ts).
16
+ */
17
+ import { spawn } from 'node:child_process';
18
+ import { getMuxTransport } from '../tools/pane.js';
19
+ import { ToolCapability } from '../runtime/capabilities.js';
20
+ import { installChoices, installRefusal, startInstallPane } from '../../panes/cli_install.js';
21
+ import { openPaneCli } from '../../panes/pane_cli_launch.js';
22
+ import { PANE_CLIS, PANE_CLI_IDS, TERMINAL_CLI_IDS, findPaneCli, installMethodsFor, isPaneCliId, isPersonOnlyCli, paneCliByBinary, parsePaneCliBody, } from '../../panes/pane_clis.js';
23
+ import { personOnlyHeadlessRefusal, personOnlyLaunchRefusal } from '../../panes/person_only_panes.js';
24
+ import { buildUserSubprocessEnv } from '../../utils/subprocess_env.js';
25
+ import { personProgramRefusal } from '../../config/permission_pin.js';
26
+ function say(ctx, content) {
27
+ ctx.addMessage({ role: 'system', content });
28
+ }
29
+ /** What /<cli> says where ZTC has no panes. */
30
+ function noPanes(id) {
31
+ const spec = PANE_CLIS[id];
32
+ return `/${spec.command} opens ${spec.label} in a pane, which needs ZTC's panes: start ZTC with zmux (plain \`ztc\`) or use the desktop `
33
+ + `app. You can also run \`${spec.binaries[0]}\` in another terminal.`;
34
+ }
35
+ /** The CLI's install commands, one to a line, each with the page it is from. */
36
+ function commandLines(choices) {
37
+ return choices.map(choice => ` ${choice.method.command} (${choice.method.via}, from ${choice.method.source})`).join('\n');
38
+ }
39
+ /**
40
+ * Offer to install CLI: refused for anyone but the person; shown, not offered, where ZTC can't ask (a front end whose
41
+ * choices answer themselves, or no panes to run it in); else the person picks one of its install commands, or none.
42
+ */
43
+ async function offerInstall(ctx, id, install) {
44
+ const spec = PANE_CLIS[id];
45
+ const refusal = installRefusal(ctx.commandOrigin, install.env);
46
+ if (refusal) {
47
+ say(ctx, `${spec.label} is not installed. ${refusal}`);
48
+ return;
49
+ }
50
+ const choices = installChoices(id, { env: install.env, cwd: install.cwd, platform: install.platform });
51
+ const again = install.then ? `/${spec.command}` : `/${spec.command} opens it`;
52
+ if (choices.length === 0) {
53
+ say(ctx, `${spec.label} is not installed, and ${spec.setupUrl} names no install command for this platform that ZTC runs.`);
54
+ return;
55
+ }
56
+ const canAsk = ctx.prompt?.interactive !== false && Boolean(ctx.select?.showSelect) && install.transport !== null && install.platform !== 'win32';
57
+ if (!canAsk) {
58
+ const where = install.platform === 'win32' ? ' in PowerShell' : '';
59
+ say(ctx, `${spec.label} is not installed. To install it, run one of its own commands${where}:\n${commandLines(choices)}\nthen ${again}.`);
60
+ return;
61
+ }
62
+ const available = choices.filter(choice => choice.found !== null);
63
+ const missing = choices.filter(choice => choice.found === null);
64
+ if (available.length === 0) {
65
+ say(ctx, `${spec.label} is not installed, and none of the programs its install commands start with (${[...new Set(missing.map(choice => choice.method.needs))]
66
+ .join(', ')}) is on your PATH. Install it from ${spec.setupUrl}:\n${commandLines(choices)}`);
67
+ return;
68
+ }
69
+ if (missing.length > 0) {
70
+ say(ctx, `Not offered, as ${[...new Set(missing.map(choice => choice.method.needs))].join(' and ')} isn't on your PATH: `
71
+ + missing.map(choice => `\`${choice.method.command}\``).join(', '));
72
+ }
73
+ const transport = install.transport;
74
+ ctx.select.showSelect({
75
+ title: `Install ${spec.label}?`,
76
+ question: `${spec.label} isn't installed. Pick one of its own install commands to run in a new pane, where you see what it does, `
77
+ + 'or don\'t install it.',
78
+ type: 'select',
79
+ // Not installing first: a front end that picks for itself installs nothing.
80
+ options: [
81
+ { value: 'cancel', label: 'Don\'t install', description: 'Nothing runs.' },
82
+ // The command again where the chooser wraps it, under the highlighted row, since a narrow terminal clips a row.
83
+ ...available.map((choice, index) => ({ value: `install:${index}`, label: choice.method.command,
84
+ description: `Runs ${choice.method.command} (${choice.method.via}, from ${choice.method.source})` })),
85
+ ],
86
+ silentCancel: true,
87
+ }, async (value) => {
88
+ const index = typeof value === 'string' && /^install:\d+$/.test(value) ? Number(value.slice('install:'.length)) : -1;
89
+ const choice = available[index];
90
+ if (!choice) {
91
+ say(ctx, 'Nothing was installed.');
92
+ return;
93
+ }
94
+ const started = await startInstallPane(transport, { cli: id, method: choice.method, env: install.env, platform: install.platform,
95
+ cwd: install.cwd });
96
+ if ('error' in started) {
97
+ say(ctx, started.error);
98
+ return;
99
+ }
100
+ say(ctx, `Installing ${spec.label} in a new pane: ${choice.method.command}. When it finishes, press Enter there; `
101
+ + (install.then ? `ZTC then opens ${spec.label}.` : 'ZTC then says whether it was installed.'));
102
+ void started.finished.then(async (status) => {
103
+ if (status === null) {
104
+ say(ctx, `The ${spec.label} install pane closed before the install finished, so nothing was opened. /agents install ${id} offers it again.`);
105
+ return;
106
+ }
107
+ if (status !== 0) {
108
+ say(ctx, `The ${spec.label} install exited with status ${status}, so ${spec.label} wasn't installed. /agents install ${id} offers it `
109
+ + `again; ${spec.setupUrl} has its own steps.`);
110
+ return;
111
+ }
112
+ const binary = findPaneCli(id, { env: install.env, cwd: install.cwd, platform: install.platform });
113
+ if (!binary) {
114
+ say(ctx, `The ${spec.label} install finished, but ZTC can't find ${spec.binaries[0]} on your PATH, in ~/.local/bin or the shared `
115
+ + `bin folders. Open a new terminal and run \`${spec.binaries[0]}\`, or add its folder to your PATH, then ${again}.`);
116
+ return;
117
+ }
118
+ say(ctx, `Installed ${spec.label} (${binary}).${install.then ? '' : ` /${spec.command} opens it.`}`);
119
+ await install.then?.(binary);
120
+ }).catch(error => say(ctx, `Could not finish installing ${spec.label}: ${error.message}`));
121
+ });
122
+ }
123
+ /** Open CLI for REQUEST as ORIGIN asked, and say so. */
124
+ async function openCli(ctx, id, request, opened) {
125
+ const origin = ctx.commandOrigin;
126
+ const byPerson = origin !== 'agent' && origin !== 'relayed';
127
+ const result = await openPaneCli(opened.transport, {
128
+ cli: id, request, cwd: opened.cwd, findBinary: () => opened.binary, env: opened.env,
129
+ // As for /claude and /codex: what the person types in a ZTC pane reaches it relayed, so relayed is theirs here.
130
+ openedBy: origin === 'agent' ? 'agent' : 'person',
131
+ });
132
+ if (result.error) {
133
+ say(ctx, result.error);
134
+ return;
135
+ }
136
+ // The person goes to the pane they opened; an agent or relayed input addresses panes by id.
137
+ if (byPerson && result.paneId !== undefined)
138
+ opened.transport.send({ type: 'focus_pane', pane_id: result.paneId });
139
+ say(ctx, byPerson ? `Opened ${result.title} in a new pane (${opened.cwd}): ${result.shown}`
140
+ : `Opened ${result.title} in pane ${result.paneId} (${opened.cwd}): ${result.shown}`);
141
+ if (result.notice)
142
+ say(ctx, result.notice);
143
+ }
144
+ export function createPaneCliCommand(id, deps = {}) {
145
+ const spec = PANE_CLIS[id];
146
+ const personOnly = isPersonOnlyCli(id);
147
+ return {
148
+ name: spec.command,
149
+ description: personOnly
150
+ ? `Open your own ${spec.label} (${spec.binaries[0]}) in a new pane, for you alone to drive: no agent opens it or types into it`
151
+ : `Open your own ${spec.label} in a new pane, signed in with your own account; offers to install it if it's missing (yours only)`,
152
+ usage: '[prompt | flags]',
153
+ // ztc_command never offers a person-only CLI to an agent; the handler refuses one that reaches it anyway.
154
+ agentRunnable: !personOnly,
155
+ // The CLI runs commands, so an agent's permission profile governs opening it as it governs a shell.
156
+ ...(personOnly ? {} : { agentCapabilities: [ToolCapability.SHELL_EXEC] }),
157
+ category: 'panes',
158
+ handler: async (args, ctx) => {
159
+ const origin = ctx.commandOrigin;
160
+ if (personOnly && (origin === 'agent' || origin === 'relayed')) {
161
+ say(ctx, personOnlyLaunchRefusal(id));
162
+ return;
163
+ }
164
+ // A headless ZTC's widgets answer themselves, and its input is the program's that runs it, not the person's.
165
+ if (personOnly && ctx.prompt?.interactive === false) {
166
+ say(ctx, personOnlyHeadlessRefusal(id));
167
+ return;
168
+ }
169
+ let request;
170
+ try {
171
+ request = parsePaneCliBody(args.join(' '));
172
+ }
173
+ catch (error) {
174
+ say(ctx, `/${spec.command}: ${error.message}`);
175
+ return;
176
+ }
177
+ // The environment as the command runs, kept for an install that finishes later.
178
+ const env = (deps.env ?? (() => ({ ...process.env })))();
179
+ const platform = deps.platform ?? process.platform;
180
+ const cwd = ctx.shell.getCwd();
181
+ const transport = (deps.transport ?? getMuxTransport)();
182
+ if (!transport) {
183
+ say(ctx, noPanes(id));
184
+ return;
185
+ }
186
+ const binary = findPaneCli(id, { env, cwd, platform });
187
+ if (binary) {
188
+ await openCli(ctx, id, request, { transport, env, cwd, binary });
189
+ return;
190
+ }
191
+ if (origin === 'agent' || origin === 'relayed') {
192
+ say(ctx, `${spec.label} is not installed. Only the person can install it: they can type /${spec.command} or /agents install ${id} `
193
+ + 'in Main (pane 0) and pick the install command.');
194
+ return;
195
+ }
196
+ await offerInstall(ctx, id, { transport, env, cwd, platform,
197
+ then: async (installed) => openCli(ctx, id, request, { transport, env, cwd, binary: installed }) });
198
+ },
199
+ };
200
+ }
201
+ // ── /agents ─────────────────────────────────────────────────────────────────
202
+ const VERSION_TIMEOUT_MS = 3000;
203
+ /** What BINARY --version prints first, cut short, or null: run with the person's environment, stdin closed, briefly. */
204
+ function versionOf(binary, env) {
205
+ if (personProgramRefusal('Skipped CLI version probe', `${binary} --version`, 'Run /agents without the permission pin to check versions.')) {
206
+ return Promise.resolve(null);
207
+ }
208
+ return new Promise(resolve => {
209
+ let output = '';
210
+ let done = false;
211
+ const finish = (value) => {
212
+ if (done)
213
+ return;
214
+ done = true;
215
+ clearTimeout(timer);
216
+ resolve(value);
217
+ };
218
+ let child;
219
+ try {
220
+ child = spawn(binary, ['--version'], { env: buildUserSubprocessEnv(env), stdio: ['ignore', 'pipe', 'pipe'] });
221
+ }
222
+ catch {
223
+ resolve(null);
224
+ return;
225
+ }
226
+ const timer = setTimeout(() => { child.kill('SIGKILL'); finish(null); }, VERSION_TIMEOUT_MS);
227
+ const take = (chunk) => { if (output.length < 4096)
228
+ output += chunk.toString('utf8'); };
229
+ child.stdout?.on('data', take);
230
+ child.stderr?.on('data', take);
231
+ child.on('error', () => finish(null));
232
+ child.on('close', code => {
233
+ const line = output.split(/\r?\n/).map(text => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()).find(Boolean);
234
+ finish(code === 0 && line ? line.slice(0, 80) : null);
235
+ });
236
+ });
237
+ }
238
+ /** The CLI a name the person typed means: its command, its id or its executable's name. */
239
+ function cliNamed(name) {
240
+ const lower = name.toLowerCase().replace(/^\//, '');
241
+ return isPaneCliId(lower) ? lower : PANE_CLI_IDS.find(id => PANE_CLIS[id].command === lower) ?? paneCliByBinary(lower);
242
+ }
243
+ export function createAgentsCommand(deps = {}) {
244
+ return {
245
+ name: 'agents',
246
+ description: 'List the coding-agent CLIs ZTC opens in a pane: whether each is installed and how to install it; /agents install <cli> '
247
+ + 'offers to install one (yours only)',
248
+ usage: '[install <cli>]',
249
+ // It runs each installed CLI's --version, and an install is the person's alone.
250
+ agentRunnable: false,
251
+ category: 'panes',
252
+ handler: async (args, ctx) => {
253
+ const env = (deps.env ?? (() => ({ ...process.env })))();
254
+ const platform = deps.platform ?? process.platform;
255
+ const cwd = ctx.shell.getCwd();
256
+ const [sub, name, ...rest] = args;
257
+ if (sub === 'install') {
258
+ const id = name ? cliNamed(name) : null;
259
+ if (!id || rest.length > 0) {
260
+ say(ctx, `Usage: /agents install <cli>, where <cli> is one of ${PANE_CLI_IDS.join(', ')}.`);
261
+ return;
262
+ }
263
+ const refusal = installRefusal(ctx.commandOrigin, env);
264
+ if (refusal) {
265
+ say(ctx, refusal);
266
+ return;
267
+ }
268
+ const spec = PANE_CLIS[id];
269
+ const found = findPaneCli(id, { env, cwd, platform });
270
+ if (found) {
271
+ say(ctx, `${spec.label} is already installed (${found}). /${spec.command} opens it.`);
272
+ return;
273
+ }
274
+ await offerInstall(ctx, id, { transport: (deps.transport ?? getMuxTransport)(), env, cwd, platform });
275
+ return;
276
+ }
277
+ if (sub !== undefined) {
278
+ say(ctx, `Usage: /agents lists the CLIs; /agents install <cli> offers to install one (${PANE_CLI_IDS.join(', ')}).`);
279
+ return;
280
+ }
281
+ const rows = await Promise.all(PANE_CLI_IDS.map(async (id) => {
282
+ const spec = PANE_CLIS[id];
283
+ const found = findPaneCli(id, { env, cwd, platform });
284
+ const page = `· ${spec.setupUrl}`;
285
+ if (found) {
286
+ // ZTC runs nothing of a person-only CLI's but the pane the person opens.
287
+ if (isPersonOnlyCli(id)) {
288
+ return `/${spec.command} ${spec.label}: installed at ${found}; only the person drives it, so ZTC doesn't run ${spec.binaries[0]} to `
289
+ + `ask its version ${page}`;
290
+ }
291
+ const version = await versionOf(found, env);
292
+ return `/${spec.command} ${spec.label}: installed at ${found}${version ? ` (${version})` : ''} ${page}`;
293
+ }
294
+ const commands = installMethodsFor(id, platform).map(method => `\`${method.command}\``);
295
+ const how = commands.length > 0 ? `install with ${commands.join(', or ')}, or /agents install ${id}` : `see ${spec.setupUrl}`;
296
+ return `/${spec.command} ${spec.label}: not installed; ${how}${isPersonOnlyCli(id) ? ' (only the person drives it)' : ''} ${page}`;
297
+ }));
298
+ say(ctx, `Coding-agent CLIs ZTC opens in a pane, each your own, signed in with your own account:\n${rows.join('\n')}`);
299
+ },
300
+ };
301
+ }
302
+ /** The commands for the CLIs the shared launcher opens, in the registry's order, and /agents. */
303
+ export const paneCliCommands = Object.freeze([...TERMINAL_CLI_IDS.map(id => createPaneCliCommand(id)), createAgentsCommand()]);