@zergai/ztc 0.26.2-dev.202611210149 → 0.26.4-dev.202611231953

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 (275) hide show
  1. package/README.md +590 -28
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/zmux-linux-x64 +0 -0
  4. package/bin/ztc-audio-darwin-arm64 +0 -0
  5. package/bin/ztc-capture-darwin-arm64 +0 -0
  6. package/bin/ztc-tui-darwin-arm64 +0 -0
  7. package/bin/ztc-tui-linux-x64 +0 -0
  8. package/bin/zterm-darwin-arm64 +2 -2
  9. package/dist/App.js +18 -1
  10. package/dist/agent/agent.d.ts +25 -1
  11. package/dist/agent/agent.js +26 -1
  12. package/dist/agent/attached_images.d.ts +58 -0
  13. package/dist/agent/attached_images.js +145 -0
  14. package/dist/agent/backends/anthropic.d.ts +14 -0
  15. package/dist/agent/backends/anthropic.js +49 -2
  16. package/dist/agent/backends/codex_app_server.d.ts +3 -1
  17. package/dist/agent/backends/codex_app_server.js +9 -6
  18. package/dist/agent/backends/codex_auth.js +3 -0
  19. package/dist/agent/backends/gemini.js +3 -0
  20. package/dist/agent/backends/host_effort_policy.js +14 -2
  21. package/dist/agent/backends/http_error.d.ts +17 -0
  22. package/dist/agent/backends/http_error.js +50 -1
  23. package/dist/agent/backends/index.js +2 -1
  24. package/dist/agent/backends/model_redirect.d.ts +47 -0
  25. package/dist/agent/backends/model_redirect.js +97 -0
  26. package/dist/agent/backends/openai_compatible.js +5 -0
  27. package/dist/agent/backends/openai_responses.d.ts +9 -1
  28. package/dist/agent/backends/openai_responses.js +21 -12
  29. package/dist/agent/backends/prompt_cache.d.ts +8 -0
  30. package/dist/agent/backends/prompt_cache.js +10 -0
  31. package/dist/agent/backends/provider_ids.d.ts +1 -1
  32. package/dist/agent/backends/provider_ids.js +1 -1
  33. package/dist/agent/backends/types.d.ts +8 -0
  34. package/dist/agent/backends/zerg-api.js +5 -1
  35. package/dist/agent/backends/zrouter_stream.d.ts +75 -9
  36. package/dist/agent/backends/zrouter_stream.js +250 -49
  37. package/dist/agent/commands/config.js +51 -4
  38. package/dist/agent/commands/connect.js +20 -0
  39. package/dist/agent/commands/credential_status.js +5 -3
  40. package/dist/agent/commands/debug.js +3 -0
  41. package/dist/agent/commands/diff.js +9 -5
  42. package/dist/agent/commands/emulation.js +7 -1
  43. package/dist/agent/commands/inbox.js +4 -3
  44. package/dist/agent/commands/mcp.js +3 -0
  45. package/dist/agent/commands/models.js +20 -3
  46. package/dist/agent/commands/permissions.js +16 -2
  47. package/dist/agent/commands/provider_selection.js +13 -6
  48. package/dist/agent/commands/settings.js +15 -4
  49. package/dist/agent/commands/status.js +23 -1
  50. package/dist/agent/commands/types.d.ts +34 -3
  51. package/dist/agent/commands/update.d.ts +2 -1
  52. package/dist/agent/commands/update.js +8 -3
  53. package/dist/agent/commands/zerg.d.ts +6 -0
  54. package/dist/agent/commands/zerg.js +152 -28
  55. package/dist/agent/commands/ztc_pane.js +8 -5
  56. package/dist/agent/factory.js +22 -4
  57. package/dist/agent/request_encoder.js +11 -2
  58. package/dist/agent/runtime/command_jobs.js +16 -1
  59. package/dist/agent/runtime/command_panes.js +4 -1
  60. package/dist/agent/runtime/execution_context.d.ts +8 -1
  61. package/dist/agent/runtime/execution_context.js +8 -2
  62. package/dist/agent/runtime/policy.d.ts +66 -5
  63. package/dist/agent/runtime/policy.js +161 -33
  64. package/dist/agent/runtime/remote_broker_transport.d.ts +7 -0
  65. package/dist/agent/runtime/remote_broker_transport.js +33 -3
  66. package/dist/agent/runtime/remote_resource_errors.d.ts +7 -0
  67. package/dist/agent/runtime/remote_resource_errors.js +10 -0
  68. package/dist/agent/runtime/remote_resources.d.ts +1 -1
  69. package/dist/agent/runtime/remote_resources.js +7 -3
  70. package/dist/agent/runtime/source_verification.js +15 -12
  71. package/dist/agent/runtime/tool_runtime.js +165 -58
  72. package/dist/agent/runtime/verifier_capture.d.ts +1 -1
  73. package/dist/agent/runtime/verifier_capture.js +6 -0
  74. package/dist/agent/runtime/work_base.js +46 -14
  75. package/dist/agent/tools/adaptation.js +29 -12
  76. package/dist/agent/tools/apply_patch.js +62 -5
  77. package/dist/agent/tools/background.js +2 -0
  78. package/dist/agent/tools/benchmark_cpu.js +2 -0
  79. package/dist/agent/tools/bus_message.d.ts +4 -2
  80. package/dist/agent/tools/bus_message.js +21 -3
  81. package/dist/agent/tools/delegate.js +2 -0
  82. package/dist/agent/tools/file.d.ts +12 -1
  83. package/dist/agent/tools/file.js +92 -11
  84. package/dist/agent/tools/lsp.d.ts +12 -0
  85. package/dist/agent/tools/lsp.js +61 -5
  86. package/dist/agent/tools/pane.js +20 -45
  87. package/dist/agent/tools/project_context.js +5 -2
  88. package/dist/agent/tools/routine.js +20 -4
  89. package/dist/agent/tools/screenshot.d.ts +8 -0
  90. package/dist/agent/tools/screenshot.js +39 -25
  91. package/dist/agent/tools/search.js +31 -3
  92. package/dist/agent/tools/shell.js +7 -1
  93. package/dist/agent/tools/supervision.js +6 -0
  94. package/dist/agent/tools/types.d.ts +18 -0
  95. package/dist/agent/tools/zerg.js +15 -19
  96. package/dist/agent/tools/ztc_command.d.ts +15 -4
  97. package/dist/agent/tools/ztc_command.js +48 -34
  98. package/dist/app/agent_runner.js +8 -6
  99. package/dist/app/conversation_compaction.d.ts +6 -3
  100. package/dist/app/conversation_compaction.js +6 -3
  101. package/dist/app/tool_callbacks.js +1 -0
  102. package/dist/audio/sfx.js +6 -0
  103. package/dist/batch/worktree.js +22 -10
  104. package/dist/board/client.js +2 -1
  105. package/dist/cli_main.d.ts +1 -0
  106. package/dist/cli_main.js +141 -45
  107. package/dist/cli_ratatui.d.ts +49 -4
  108. package/dist/cli_ratatui.js +355 -79
  109. package/dist/conductor_branch.js +4 -1
  110. package/dist/config/host_credentials.d.ts +157 -0
  111. package/dist/config/host_credentials.js +589 -0
  112. package/dist/config/model_pin.d.ts +111 -0
  113. package/dist/config/model_pin.js +182 -0
  114. package/dist/config/own_state_files.d.ts +35 -0
  115. package/dist/config/own_state_files.js +161 -0
  116. package/dist/config/permission_pin.d.ts +148 -0
  117. package/dist/config/permission_pin.js +203 -0
  118. package/dist/config/permissions.d.ts +9 -2
  119. package/dist/config/permissions.js +14 -3
  120. package/dist/config/platform_login.d.ts +72 -0
  121. package/dist/config/platform_login.js +111 -0
  122. package/dist/config/profile_limits.d.ts +34 -0
  123. package/dist/config/profile_limits.js +66 -0
  124. package/dist/config/provider_api_key_env.js +3 -2
  125. package/dist/config/provider_models.d.ts +6 -1
  126. package/dist/config/provider_models.js +38 -11
  127. package/dist/config/repo_config.d.ts +22 -0
  128. package/dist/config/repo_config.js +77 -3
  129. package/dist/config/router_runtime_grant.d.ts +53 -0
  130. package/dist/config/router_runtime_grant.js +131 -0
  131. package/dist/config/settings_merge.d.ts +22 -0
  132. package/dist/config/settings_merge.js +75 -0
  133. package/dist/config/types.d.ts +8 -0
  134. package/dist/config.d.ts +334 -4
  135. package/dist/config.js +1024 -41
  136. package/dist/context/project_intelligence.d.ts +11 -2
  137. package/dist/context/project_intelligence.js +38 -15
  138. package/dist/desktop/daily/desktop_wiring.js +8 -6
  139. package/dist/desktop/daily/native_pane_launcher.js +2 -1
  140. package/dist/desktop/daily/native_tool.d.ts +1 -1
  141. package/dist/desktop/daily/native_tool.js +4 -3
  142. package/dist/desktop/daily/process_identity.js +10 -2
  143. package/dist/desktop/daily/source_baseline.js +4 -3
  144. package/dist/diagnostics/native_terminal_benchmark.js +3 -2
  145. package/dist/diagnostics/session_export.js +27 -14
  146. package/dist/embedded/anempa_runtime.js +3 -3
  147. package/dist/embedded/gameboy_runtime.js +5 -4
  148. package/dist/embedded/zergpod_runtime.js +5 -4
  149. package/dist/emulation/catalog.js +6 -1
  150. package/dist/emulation/tool_adapters.js +13 -3
  151. package/dist/environment/store.js +5 -4
  152. package/dist/extension_discovery.d.ts +12 -2
  153. package/dist/extension_discovery.js +52 -7
  154. package/dist/headless.d.ts +8 -0
  155. package/dist/headless.js +52 -13
  156. package/dist/headless_cli.js +16 -1
  157. package/dist/headless_workflow_trigger.js +1 -1
  158. package/dist/hooks/dispatcher.d.ts +8 -0
  159. package/dist/hooks/dispatcher.js +22 -2
  160. package/dist/hooks/lifecycle.d.ts +6 -0
  161. package/dist/hooks/lifecycle.js +1 -0
  162. package/dist/hooks/program_files.d.ts +10 -0
  163. package/dist/hooks/program_files.js +175 -0
  164. package/dist/hooks/runner.d.ts +11 -1
  165. package/dist/hooks/runner.js +112 -11
  166. package/dist/hooks/types.d.ts +2 -0
  167. package/dist/host_credentials_startup.d.ts +6 -0
  168. package/dist/host_credentials_startup.js +17 -0
  169. package/dist/instance_registry.d.ts +6 -2
  170. package/dist/instance_registry.js +9 -15
  171. package/dist/intake/format.d.ts +6 -0
  172. package/dist/intake/format.js +9 -0
  173. package/dist/intake/notifications.js +2 -1
  174. package/dist/lsp/manager.d.ts +1 -1
  175. package/dist/lsp/manager.js +4 -5
  176. package/dist/mcp/client.d.ts +2 -0
  177. package/dist/mcp/client.js +116 -18
  178. package/dist/mcp/registry.d.ts +12 -0
  179. package/dist/mcp/registry.js +15 -1
  180. package/dist/modes/handlers.js +14 -5
  181. package/dist/panes/agent_cli.d.ts +23 -1
  182. package/dist/panes/agent_cli.js +96 -1
  183. package/dist/panes/agent_panes.d.ts +27 -4
  184. package/dist/panes/agent_panes.js +73 -11
  185. package/dist/panes/editor_program.d.ts +8 -0
  186. package/dist/panes/editor_program.js +25 -0
  187. package/dist/panes/motsi.d.ts +11 -1
  188. package/dist/panes/motsi.js +14 -1
  189. package/dist/panes/pane_registry.d.ts +28 -1
  190. package/dist/panes/pane_registry.js +25 -0
  191. package/dist/panes/worker_route.js +5 -3
  192. package/dist/panes/ztc_launch.d.ts +8 -0
  193. package/dist/panes/ztc_launch.js +26 -1
  194. package/dist/profile_baseline.js +2 -0
  195. package/dist/router_auth.d.ts +8 -3
  196. package/dist/router_auth.js +34 -2
  197. package/dist/runtime_info.js +56 -38
  198. package/dist/session.js +12 -2
  199. package/dist/shannon/runtime.js +13 -1
  200. package/dist/simulation/domains/loader.d.ts +2 -1
  201. package/dist/simulation/domains/loader.js +19 -2
  202. package/dist/simulation/living/context.d.ts +8 -8
  203. package/dist/simulation/living/types.d.ts +2 -2
  204. package/dist/simulation/memory/embedding.d.ts +2 -1
  205. package/dist/simulation/memory/embedding.js +25 -6
  206. package/dist/terminal_attach.js +2 -1
  207. package/dist/types.d.ts +21 -0
  208. package/dist/ui/ratatui/headless_pane_manager.d.ts +12 -6
  209. package/dist/ui/ratatui/headless_pane_manager.js +65 -21
  210. package/dist/ui/ratatui/ipc_path.d.ts +41 -2
  211. package/dist/ui/ratatui/ipc_path.js +164 -5
  212. package/dist/ui/ratatui/pane_credential_broker.d.ts +17 -4
  213. package/dist/ui/ratatui/pane_credential_broker.js +23 -5
  214. package/dist/ui/ratatui/pane_relay.d.ts +74 -0
  215. package/dist/ui/ratatui/pane_relay.js +188 -13
  216. package/dist/ui/ratatui/process.d.ts +15 -1
  217. package/dist/ui/ratatui/process.js +129 -163
  218. package/dist/ui/ratatui/protocol.d.ts +11 -1
  219. package/dist/ui/ratatui/protocol.js +6 -0
  220. package/dist/ui/ratatui/ztc_launch_trust.d.ts +87 -0
  221. package/dist/ui/ratatui/ztc_launch_trust.js +249 -0
  222. package/dist/utils/admitted_open.d.ts +40 -0
  223. package/dist/utils/admitted_open.js +111 -0
  224. package/dist/utils/clipboard.js +2 -1
  225. package/dist/utils/computer_native.js +12 -56
  226. package/dist/utils/dictation.js +15 -12
  227. package/dist/utils/dictation_native.js +17 -60
  228. package/dist/utils/git_probe_options.d.ts +28 -0
  229. package/dist/utils/git_probe_options.js +30 -0
  230. package/dist/utils/git_program_files.d.ts +145 -0
  231. package/dist/utils/git_program_files.js +1282 -0
  232. package/dist/utils/git_repository_programs.d.ts +13 -0
  233. package/dist/utils/git_repository_programs.js +38 -0
  234. package/dist/utils/host_shell.js +2 -1
  235. package/dist/utils/idle_compaction.js +8 -1
  236. package/dist/utils/image_fit.d.ts +4 -1
  237. package/dist/utils/image_fit.js +6 -2
  238. package/dist/utils/image_preview.js +3 -2
  239. package/dist/utils/mirror_media.d.ts +22 -4
  240. package/dist/utils/mirror_media.js +87 -86
  241. package/dist/utils/ml_native.js +11 -56
  242. package/dist/utils/native_install.d.ts +55 -0
  243. package/dist/utils/native_install.js +107 -0
  244. package/dist/utils/open_url.js +2 -0
  245. package/dist/utils/process_end.d.ts +16 -0
  246. package/dist/utils/process_end.js +73 -0
  247. package/dist/utils/router_catalog.js +9 -2
  248. package/dist/utils/sandbox.d.ts +64 -1
  249. package/dist/utils/sandbox.js +397 -89
  250. package/dist/utils/shell.js +31 -12
  251. package/dist/utils/subprocess_env.d.ts +218 -2
  252. package/dist/utils/subprocess_env.js +429 -11
  253. package/dist/utils/system_ps.d.ts +5 -0
  254. package/dist/utils/system_ps.js +30 -0
  255. package/dist/utils/tts.js +5 -0
  256. package/dist/utils/tts_native.js +13 -60
  257. package/dist/utils/zlicky_overlay.js +17 -50
  258. package/dist/utils/ztc_own_state.d.ts +58 -0
  259. package/dist/utils/ztc_own_state.js +236 -0
  260. package/dist/web/mirror_authenticator.d.ts +67 -6
  261. package/dist/web/mirror_authenticator.js +131 -22
  262. package/dist/web/mirror_stream.d.ts +54 -10
  263. package/dist/web/mirror_stream.js +379 -92
  264. package/dist/web/observer_query_redaction.js +53 -13
  265. package/dist/web/observer_secret_redaction.d.ts +59 -0
  266. package/dist/web/observer_secret_redaction.js +714 -0
  267. package/dist/web/pane_credentials.d.ts +20 -2
  268. package/dist/web/pane_credentials.js +58 -5
  269. package/dist/worker/executor.js +3 -1
  270. package/dist/workspace_collision.js +19 -15
  271. package/dist/zerg/local_zerg_launches.d.ts +27 -0
  272. package/dist/zerg/local_zerg_launches.js +198 -0
  273. package/dist/zlm-embed.mjs +6257 -2791
  274. package/npm-shrinkwrap.json +1 -1
  275. package/package.json +42 -15
@@ -3,6 +3,7 @@ import { spawn } from 'child_process';
3
3
  import { dirname, join } from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { loadDesktopRuntime } from '../../desktop/runtime.js';
6
+ import { buildUserSubprocessEnv } from '../../utils/subprocess_env.js';
6
7
  /**
7
8
  * The folder npm installed ZTC in. The npm launcher names it in ZERGAI_CLI_ROOT, because it runs ZTC from a copy of
8
9
  * the launched version (scripts/npm/cli-snapshot.cjs) that no install touches; otherwise it is where this code runs.
@@ -21,9 +22,13 @@ function getCurrentInstallPath() {
21
22
  }
22
23
  }
23
24
  const DESKTOP_UPDATE_MESSAGE = 'This ZTC desktop app updates itself: it downloads and verifies new releases in the background and installs them when you quit ZTC. Open Updates in the title bar to check now or change this.';
25
+ /**
26
+ * Run the launcher with a user subprocess's environment: it runs npm and the install scripts npm runs, so they get the
27
+ * person's environment (their npm settings among it) and none of ZTC's credentials.
28
+ */
24
29
  function runProcess(command, args) {
25
30
  return new Promise((resolve) => {
26
- const proc = spawn(command, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env } });
31
+ const proc = spawn(command, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: buildUserSubprocessEnv() });
27
32
  let stdout = '';
28
33
  let stderr = '';
29
34
  proc.stdout?.on('data', (d) => { stdout += d.toString(); });
@@ -39,6 +44,7 @@ function runProcess(command, args) {
39
44
  * checkout updates with git.
40
45
  */
41
46
  export function createUpdateCommand(deps) {
47
+ const run = deps.run ?? runProcess;
42
48
  return {
43
49
  name: 'update',
44
50
  description: 'Check for updates and install the latest version',
@@ -58,7 +64,7 @@ export function createUpdateCommand(deps) {
58
64
  }
59
65
  const check = args.includes('--check') || args.includes('check');
60
66
  ctx.addMessage({ role: 'system', content: check ? 'Checking for updates…' : 'Checking for updates and installing any newer release…' });
61
- const result = await deps.run(deps.nodePath, [launcher, 'update', ...(check ? ['--check'] : [])]);
67
+ const result = await run(deps.nodePath, [launcher, 'update', ...(check ? ['--check'] : [])]);
62
68
  const output = [result.stderr, result.stdout].map(text => text.trim()).filter(Boolean).join('\n');
63
69
  if (result.exitCode === 0) {
64
70
  const installed = /^Updated /m.test(output);
@@ -79,6 +85,5 @@ export const updateCommand = createUpdateCommand({
79
85
  desktopBundle: () => Boolean(loadDesktopRuntime()),
80
86
  packageRoot: getCurrentInstallPath,
81
87
  exists: existsSync,
82
- run: runProcess,
83
88
  nodePath: process.execPath,
84
89
  });
@@ -13,6 +13,12 @@ export declare function resolveLocalZergProjectDir(startDir?: string): string |
13
13
  export declare function findDefaultLaunchPort(start?: number, limit?: number): Promise<number>;
14
14
  export declare function assertPortAvailable(port: number): Promise<void>;
15
15
  export declare function waitForZergHealth(endpoint: string, timeoutMs?: number, fetchImpl?: typeof fetch): Promise<void>;
16
+ /**
17
+ * The arguments of /zerg that launch a local Zerg: Poetry then runs the working directory's zerg/ project, its
18
+ * in-project virtualenv included, outside any sandbox, so the agent's launch is a shell command of the profile's
19
+ * (Command.agentCapabilities) and one it starts outside the OS sandbox.
20
+ */
21
+ export declare function launchesLocalZerg(args: readonly string[]): boolean;
16
22
  export declare function zergLaunchLocal(args: string[], ctx: CommandContext): Promise<void>;
17
23
  export declare function formatManagedZergStartResult(input: {
18
24
  result: 'started_background' | 'already_starting' | 'connected' | 'wait_timeout' | 'failed';
@@ -1,16 +1,21 @@
1
- import { execSync, spawn, spawnSync } from 'child_process';
1
+ import { spawn, spawnSync } from 'child_process';
2
2
  import { randomBytes } from 'crypto';
3
3
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from 'fs';
4
4
  import { createServer } from 'net';
5
5
  import { homedir } from 'os';
6
6
  import { dirname, join, resolve } from 'path';
7
7
  import { configStore } from '../../config.js';
8
+ import { commandPolicyFor } from '../../config/permissions.js';
9
+ import { ToolCapability } from '../runtime/capabilities.js';
10
+ import { commandsRequireOsSandbox } from '../../utils/sandbox.js';
11
+ import { buildModelClientSubprocessEnv, buildUserSubprocessEnv } from '../../utils/subprocess_env.js';
8
12
  import { getZergSocketClient } from '../../zerg/socket_client.js';
9
13
  import { getActiveManifest } from '../../zerg/manifest_state.js';
10
14
  import { createMiniZdeController, getActiveMiniZdeController, listZergRuns, resumeMiniZdeController, } from '../../zerg/mini_zde_controller.js';
11
15
  import { attachMiniZdePane } from '../../zerg/mini_zde_render.js';
12
16
  import { normalizeMiniZdeStatus, summarizeManifestYaml, } from '../../zerg/mini_zde_state.js';
13
17
  import { activateConnectedZerg, deactivateConnectedZerg } from '../../zerg/active_zerg.js';
18
+ import { LOCAL_ZERG_LAUNCH_ID_ENV, forgetLocalZergLaunch, newLocalZergLaunchId, recordLocalZergLaunch, stopRecordedLocalZerg, } from '../../zerg/local_zerg_launches.js';
14
19
  import { applyZergUpdate } from '../../zerg/zerg_update_interpreter.js';
15
20
  import { ZERG_SOCKET_EVENTS } from '../../zerg/socket_events.js';
16
21
  const LOCAL_ZERG_DEFAULT_PORT = 3333;
@@ -49,7 +54,11 @@ function applyPhaseUpdate(controller, data) {
49
54
  schema_version: typeof payload.schema_version === 'number' ? payload.schema_version : undefined,
50
55
  });
51
56
  }
52
- export function createLocalZergRuntimePaths(port, baseDir = join(homedir(), '.ztc', 'zerg-runs'), timestamp = Date.now(), nonce = randomBytes(4).toString('hex')) {
57
+ /** Where /zerg launch keeps each launch's runtime folder, and in it the launch's record (local_zerg_launches.ts). */
58
+ function localZergRunsDir() {
59
+ return join(homedir(), '.ztc', 'zerg-runs');
60
+ }
61
+ export function createLocalZergRuntimePaths(port, baseDir = localZergRunsDir(), timestamp = Date.now(), nonce = randomBytes(4).toString('hex')) {
53
62
  const runDir = join(baseDir, `local-zerg-${port}-${timestamp}-${nonce}`);
54
63
  const dataRoot = join(runDir, 'data');
55
64
  const workspaceRoot = join(runDir, 'workspace-root');
@@ -151,23 +160,69 @@ export async function waitForZergHealth(endpoint, timeoutMs = 30_000, fetchImpl
151
160
  }
152
161
  throw new Error(lastError || `Timed out waiting for ${endpoint}/health`);
153
162
  }
154
- function killProcessOnPort(port) {
163
+ /**
164
+ * The local Zergs this ZTC started with /zerg launch, by the origin each answers on, with each one's runtime folder:
165
+ * this ZTC stops them from memory. Each launch is recorded on disk too, for a ZTC started after this one (/restart, a
166
+ * hot restart after an update, a relaunch), which stops one only once it has confirmed the process is that launch
167
+ * (local_zerg_launches.ts). /zerg stop ends nothing else.
168
+ */
169
+ const launchedLocalZergs = new Map();
170
+ function endpointPort(endpoint) {
155
171
  try {
156
- // Use -sTCP:LISTEN to only find the server process, not client connections
157
- const pids = execSync(`lsof -ti:${port} -sTCP:LISTEN`, { encoding: 'utf-8' }).trim();
158
- if (!pids)
159
- return false;
160
- for (const pid of pids.split(/\s+/)) {
161
- try {
162
- process.kill(Number(pid), 'SIGTERM');
163
- }
164
- catch { /* already dead */ }
165
- }
166
- return true;
172
+ const url = new URL(endpoint);
173
+ return url.port || (url.protocol === 'https:' ? '443' : '80');
167
174
  }
168
175
  catch {
169
- return false;
176
+ return 'unknown';
177
+ }
178
+ }
179
+ function endpointOrigin(endpoint) {
180
+ try {
181
+ return new URL(endpoint).origin;
182
+ }
183
+ catch {
184
+ return null;
185
+ }
186
+ }
187
+ /**
188
+ * Stop the Zerg this ZTC launched at ENDPOINT: its launch (Poetry) and everything it started. The launch is detached,
189
+ * so it leads its own process group, and while it runs (until ZTC reaps it) the group is that launch's and no one
190
+ * else's. 'not-launched' for any Zerg ZTC did not start here, which keeps running.
191
+ */
192
+ function stopLaunchedLocalZerg(endpoint) {
193
+ const origin = endpointOrigin(endpoint);
194
+ const launched = origin === null ? undefined : launchedLocalZergs.get(origin);
195
+ if (!launched)
196
+ return 'not-launched';
197
+ launchedLocalZergs.delete(origin);
198
+ forgetLocalZergLaunch(launched.runDir);
199
+ const { child: launch } = launched;
200
+ const pid = launch.pid;
201
+ if (pid === undefined || launch.exitCode !== null || launch.signalCode !== null)
202
+ return 'exited';
203
+ try {
204
+ process.kill(process.platform === 'win32' ? pid : -pid, 'SIGTERM');
170
205
  }
206
+ catch {
207
+ try {
208
+ launch.kill('SIGTERM');
209
+ }
210
+ catch {
211
+ return 'exited';
212
+ }
213
+ }
214
+ return 'stopped';
215
+ }
216
+ /**
217
+ * Stop the Zerg launched at ENDPOINT: from memory if this ZTC launched it, else by the record an earlier ZTC left
218
+ * ('unconfirmed' when the process that record names could not be confirmed to be that launch, which keeps running).
219
+ */
220
+ async function stopLocalZerg(endpoint) {
221
+ const outcome = stopLaunchedLocalZerg(endpoint);
222
+ if (outcome !== 'not-launched')
223
+ return outcome;
224
+ const recorded = await stopRecordedLocalZerg(endpoint, localZergRunsDir());
225
+ return recorded === 'not-recorded' ? 'not-launched' : recorded;
171
226
  }
172
227
  function readLogTail(logPath, maxLines = 20) {
173
228
  try {
@@ -179,6 +234,28 @@ function readLogTail(logPath, maxLines = 20) {
179
234
  return '';
180
235
  }
181
236
  }
237
+ /**
238
+ * The arguments of /zerg that launch a local Zerg: Poetry then runs the working directory's zerg/ project, its
239
+ * in-project virtualenv included, outside any sandbox, so the agent's launch is a shell command of the profile's
240
+ * (Command.agentCapabilities) and one it starts outside the OS sandbox.
241
+ */
242
+ export function launchesLocalZerg(args) {
243
+ return args[0] === 'launch' || args[0] === 'serve';
244
+ }
245
+ /**
246
+ * Whether the permission profile this process runs under holds the agent's commands to the OS sandbox, so relayed
247
+ * input, which another pane's agent can send and nobody approves, launches no local Zerg. One that can't be read does.
248
+ */
249
+ function launchRefusedForRelayedInput(ctx) {
250
+ if (ctx.commandOrigin !== 'relayed')
251
+ return false;
252
+ try {
253
+ return commandsRequireOsSandbox(commandPolicyFor(configStore.get()));
254
+ }
255
+ catch {
256
+ return true;
257
+ }
258
+ }
182
259
  export async function zergLaunchLocal(args, ctx) {
183
260
  const explicitPort = args[0] ? Number.parseInt(args[0], 10) : null;
184
261
  if (args[0] && (explicitPort === null || !Number.isInteger(explicitPort) || explicitPort <= 0)) {
@@ -188,6 +265,17 @@ export async function zergLaunchLocal(args, ctx) {
188
265
  });
189
266
  return;
190
267
  }
268
+ // Poetry runs the zerg/ project's own code outside the OS sandbox this profile holds the agent's commands to. The
269
+ // agent's ztc_command is refused before this (launchesLocalZerg) unless the person approved it; relayed input here.
270
+ if (launchRefusedForRelayedInput(ctx)) {
271
+ ctx.addMessage({
272
+ role: 'system',
273
+ content: 'No local Zerg was launched: Poetry would run the zerg/ project\'s code outside the OS sandbox this permission '
274
+ + 'profile holds the agent\'s commands to, and input relayed from another pane can\'t ask for that. Run /zerg launch '
275
+ + 'in Main yourself, or /zerg connect <url> to a Zerg that is already running.',
276
+ });
277
+ return;
278
+ }
191
279
  const zergDir = resolveLocalZergProjectDir(ctx.shell.getCwd());
192
280
  if (zergDir === null) {
193
281
  ctx.addMessage({
@@ -199,6 +287,8 @@ export async function zergLaunchLocal(args, ctx) {
199
287
  const poetryCheck = spawnSync('poetry', ['--version'], {
200
288
  cwd: zergDir,
201
289
  encoding: 'utf-8',
290
+ // Poetry, and the plugins it loads, start with a user subprocess's environment: none of ZTC's credentials.
291
+ env: buildUserSubprocessEnv(process.env),
202
292
  });
203
293
  if (poetryCheck.error || poetryCheck.status !== 0) {
204
294
  const detail = poetryCheck.error?.message || poetryCheck.stderr || 'poetry is unavailable';
@@ -233,12 +323,17 @@ export async function zergLaunchLocal(args, ctx) {
233
323
  const stderrFd = openSync(logPath, 'a');
234
324
  const runtimePaths = createLocalZergRuntimePaths(port);
235
325
  const commandArgs = buildLocalZergLaunchArgs(port, runtimePaths.workspaceRoot);
326
+ // The Zerg service is a model client of its own: the person's environment and provider keys, and none of ZTC's
327
+ // credentials (its mirror's secret and token, the Router grant it infers with, a runtime session secret).
328
+ const launchId = newLocalZergLaunchId();
236
329
  const childEnv = {
237
- ...process.env,
330
+ ...buildModelClientSubprocessEnv(process.env),
238
331
  ZERG_DATA_ROOT: runtimePaths.dataRoot,
239
332
  ZERG_WORKSPACE_ROOT: runtimePaths.workspaceRoot,
240
333
  ZERG_WORKSPACE_BASE: runtimePaths.workspaceBase,
241
334
  ZERG_SNAPSHOT_PATH: runtimePaths.snapshotPath,
335
+ // What a ZTC started after this one confirms before it stops this launch (local_zerg_launches.ts).
336
+ [LOCAL_ZERG_LAUNCH_ID_ENV]: launchId,
242
337
  };
243
338
  const portNote = explicitPort !== null
244
339
  ? `Using requested port ${port}.`
@@ -256,6 +351,17 @@ export async function zergLaunchLocal(args, ctx) {
256
351
  closeSync(stdoutFd);
257
352
  closeSync(stderrFd);
258
353
  child.unref();
354
+ // The Zerg this ZTC started at ENDPOINT, for /zerg stop to end (a failed or slow start included), here and in a ZTC
355
+ // started after this one.
356
+ launchedLocalZergs.set(endpointOrigin(endpoint), { child, runDir: runtimePaths.runDir });
357
+ if (child.pid !== undefined) {
358
+ try {
359
+ recordLocalZergLaunch(runtimePaths.runDir, { pid: child.pid, launchId, endpoint });
360
+ }
361
+ catch {
362
+ // Without its record only this ZTC can stop it; a later one says how to.
363
+ }
364
+ }
259
365
  try {
260
366
  await Promise.race([
261
367
  waitForZergHealth(endpoint),
@@ -574,7 +680,8 @@ export function formatRunSnapshot(state) {
574
680
  if (state.activity.length > 0) {
575
681
  const last = state.activity[state.activity.length - 1];
576
682
  if (last) {
577
- const detail = last.detail ? ` — ${last.detail.slice(0, 80)}` : '';
683
+ // A detail cut short says so: the mirror withholds from an observer what may start a credential at the mark.
684
+ const detail = last.detail ? ` — ${last.detail.length > 80 ? `${last.detail.slice(0, 80)}…` : last.detail}` : '';
578
685
  lines.push(` Last activity: (${last.level}) ${last.title}${detail}`);
579
686
  }
580
687
  }
@@ -585,6 +692,8 @@ export const zergCommand = {
585
692
  description: 'Manage Zerg agents. For managed starts, reuse the same ID and poll /zerg info while STARTING/BUILDING; do not create replacement Zergs automatically.',
586
693
  usage: '<connect|launch|disconnect|status|list|info|create|start|stop|delete> [args]',
587
694
  agentRunnable: true,
695
+ // /zerg launch and /zerg serve run Poetry in the working directory's zerg/ project, outside any sandbox.
696
+ agentCapabilities: args => launchesLocalZerg(args) ? [ToolCapability.SHELL_EXEC] : [],
588
697
  category: 'zerg',
589
698
  handler: async (args, ctx) => {
590
699
  const [subCmd, ...rest] = args;
@@ -668,28 +777,39 @@ export const zergCommand = {
668
777
  });
669
778
  return;
670
779
  }
671
- let port = null;
672
- try {
673
- port = new URL(localEndpoint).port ? Number(new URL(localEndpoint).port) : null;
674
- }
675
- catch { /* invalid URL */ }
780
+ // The client may still be trying to reach the endpoint (a connect that failed retries): leave it either way.
676
781
  const client = getZergSocketClient();
677
- if (client.connected) {
782
+ if (client.connected || client.endpoint === localEndpoint) {
678
783
  clearZergStartHandlers();
679
784
  client.disconnect();
680
785
  }
681
- const killed = port !== null && killProcessOnPort(port);
682
- deactivateConnectedZerg(`Stopped local Zerg at ${localEndpoint}`);
683
- if (killed) {
786
+ // Only a Zerg ZTC launched is stopped (by this ZTC or one before it), never whatever else listens on the port.
787
+ const outcome = await stopLocalZerg(localEndpoint);
788
+ deactivateConnectedZerg(outcome === 'stopped' ? `Stopped local Zerg at ${localEndpoint}` : `Disconnected from ${localEndpoint}`);
789
+ const port = endpointPort(localEndpoint);
790
+ const listener = `the process listening on port ${port} (lsof -nP -iTCP:${port} -sTCP:LISTEN)`;
791
+ if (outcome === 'stopped') {
684
792
  ctx.addMessage({
685
793
  role: 'system',
686
794
  content: `Stopped local Zerg at ${localEndpoint} (port ${port}).`,
687
795
  });
688
796
  }
797
+ else if (outcome === 'exited') {
798
+ ctx.addMessage({
799
+ role: 'system',
800
+ content: `Disconnected from ${localEndpoint}. The Zerg ZTC launched there has already exited, so nothing was stopped; anything answering there now was not started by ZTC.`,
801
+ });
802
+ }
803
+ else if (outcome === 'unconfirmed') {
804
+ ctx.addMessage({
805
+ role: 'system',
806
+ content: `Disconnected from ${localEndpoint}. ZTC launched a Zerg there before, but could not confirm that the process its record names is that Zerg, so it stopped nothing. To stop the Zerg, end ${listener}.`,
807
+ });
808
+ }
689
809
  else {
690
810
  ctx.addMessage({
691
811
  role: 'system',
692
- content: `Disconnected from ${localEndpoint}. The process may have already exited — check with \`lsof -i:${port || '3333'}\` if needed.`,
812
+ content: `Disconnected from ${localEndpoint}. ZTC did not start the Zerg there, so it is still running. To stop it, stop it where it was started (Ctrl+C in the terminal running it), or end ${listener}. For a cloud Zerg, use /zerg stop <id>.`,
693
813
  });
694
814
  }
695
815
  return;
@@ -737,9 +857,13 @@ export const zergCommand = {
737
857
  // Fall through to cloud status below
738
858
  }
739
859
  if (!configStore.isAuthenticated() && !configStore.get().zergEndpoint && subCmd !== 'status') {
860
+ // A login ZTC holds but sends to no platform API (a Zerg Router credential, the host's grant, or a ZTC_AUTH_TOKEN no
861
+ // platform API is named for) says why.
862
+ const why = configStore.getPlatformLoginRefusal();
740
863
  ctx.addMessage({
741
864
  role: 'system',
742
- content: 'Not logged in. Use /auth login first, or /zerg connect <url> for a local Zerg.',
865
+ content: why ? `Not logged in to a ZergAI platform API: ${why} Or use /zerg connect <url> for a local Zerg.`
866
+ : 'Not logged in. Use /auth login first, or /zerg connect <url> for a local Zerg.',
743
867
  });
744
868
  return;
745
869
  }
@@ -103,14 +103,14 @@ function describeRoute(route) {
103
103
  return `${routeWord(provider, routed)} · ${label} · ${route.modelOverride}${effort}`;
104
104
  }
105
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
106
+ * Why a ZTC pane an agent opens now in CWD would run under more than the agent's own pane does, or undefined when it
107
107
  * wouldn't: it runs under the profile's saved permission settings, and this pane may run under narrower ones for this
108
- * session.
108
+ * session. Its relative roots are CWD's, as this pane's are where a host's pin holds them at the folder it started in.
109
109
  */
110
- function widerThanThisPane() {
110
+ function widerThanThisPane(cwd) {
111
111
  const saved = savedPermissionSettings(configStore.getConfigPath());
112
112
  const current = configStore.get();
113
- const beyond = permissionsBeyond(saved, current);
113
+ const beyond = permissionsBeyond(saved, current, cwd);
114
114
  if (beyond.length === 0)
115
115
  return undefined;
116
116
  return `a new ZTC pane runs under the saved permissions (${saved.permissionProfile}), which allow more than this pane's `
@@ -129,6 +129,9 @@ export const ztcPaneCommand = {
129
129
  // A ZTC pane runs an agent that runs commands: the profile governs opening one as it governs a shell, as
130
130
  // create_ztc_pane's shell_exec does for a ZTC agent's own panes and as for /claude and /codex.
131
131
  agentCapabilities: [ToolCapability.SHELL_EXEC],
132
+ // Its agent runs under permissions no wider than this pane's (widerThanThisPane), so its commands are held where
133
+ // this pane's are: a profile whose commands run only in an OS sandbox still lets the agent open one.
134
+ agentConfined: true,
132
135
  category: 'panes',
133
136
  handler: async (args, ctx) => {
134
137
  const say = (content) => ctx.addMessage({ role: 'system', content });
@@ -159,7 +162,7 @@ export const ztcPaneCommand = {
159
162
  if (!byPerson) {
160
163
  let wider;
161
164
  try {
162
- wider = widerThanThisPane();
165
+ wider = widerThanThisPane(ctx.shell.getCwd());
163
166
  }
164
167
  catch (error) {
165
168
  // A saved permission profile ZTC can't resolve: a pane started on it would not run.
@@ -17,12 +17,14 @@ import { loadIntentsContext } from '../context/intents_loader.js';
17
17
  import { getDefaultModelForProvider, inferDefaultProvider, resolveCodexEffort } from '../config/defaults.js';
18
18
  import { resolveRepoModelOverride } from '../config/repo_config.js';
19
19
  import { runtimeDiag, runtimeDiagOnce } from '../utils/debug_log.js';
20
- import { CapabilityPolicy, shellOutsideSandbox } from './runtime/policy.js';
20
+ import { CapabilityPolicy, commandsSandboxOnly, shellOutsideSandbox, startsProgramsOutsideSandbox } from './runtime/policy.js';
21
21
  import { HookDispatcher } from '../hooks/dispatcher.js';
22
22
  import { getModeRegistry } from '../modes/index.js';
23
23
  import { defaultTools, paneTools, supervisionTools, busTools, worldMutationTools, computerTools, zlickyTools, zlickyWebTools, mlTools, evolutionTools, simTools, proposeMeetingTool, acceptMeetingTool, declineMeetingTool, vetoMeetingTool } from './tools/index.js';
24
24
  import { getToolBundle } from './tools/bundle_registry.js';
25
+ import { stopLanguageServersUnlessAdmitted } from './tools/lsp.js';
25
26
  import { memoryTools } from './tools/memory_tools.js';
27
+ import { SCREEN_TOOLS, screenCaptureAvailable } from './tools/screenshot.js';
26
28
  import { parseToolGroupsConfig } from './tools/tool_groups.js';
27
29
  import { buildAgentToolsFromDomain } from './tools/sim_domain_tools.js';
28
30
  import { getMcpTools, noteShadowedMcpTool } from '../mcp/registry.js';
@@ -377,6 +379,11 @@ export function createAgentFromConfig(options) {
377
379
  const cwd = options.cwd ? resolvePath(options.cwd) : process.cwd();
378
380
  const permissionProfile = resolvePermissionProfile(options.config);
379
381
  const permissionPolicy = projectPermissionPolicy(options.config);
382
+ const policy = new CapabilityPolicy(options.config.toolPermissions, permissionProfile, cwd, { sandbox: options.config.sandbox });
383
+ // The agent is built again after a change of the permissions: the language servers the LSP tools started under earlier
384
+ // ones stop where these don't admit those tools without asking (agent/tools/lsp.ts).
385
+ stopLanguageServersUnlessAdmitted(policy, JSON.stringify({ profile: permissionProfile, toolPermissions: options.config.toolPermissions ?? null,
386
+ sandbox: options.config.sandbox ?? null }));
380
387
  const sessionId = options.sessionId ?? randomUUID();
381
388
  const remoteResourceSession = guardedRemoteSession(sessionId, options.config.remoteResources);
382
389
  if (remoteResourceSession && options.mode && options.mode !== 'normal') {
@@ -436,6 +443,11 @@ export function createAgentFromConfig(options) {
436
443
  if (!workflowsEnabled(options.config)) {
437
444
  allTools = allTools.filter((tool) => tool.definition.name !== 'workflow');
438
445
  }
446
+ // screenshot, list_windows and run_and_capture need a screen: a Linux machine with no display (a server, ZergCloud's
447
+ // resident) is not offered them.
448
+ if (!screenCaptureAvailable()) {
449
+ allTools = allTools.filter((tool) => !SCREEN_TOOLS.includes(tool));
450
+ }
439
451
  // External-plugin tool bundles keyed by mode name (cybersim, …).
440
452
  // Plugins call registerToolBundle() at module load via .ztc/plugin.yaml.
441
453
  if (options.mode) {
@@ -630,11 +642,15 @@ export function createAgentFromConfig(options) {
630
642
  filteredTools = filteredTools.filter(tool => hostToolAllowlist.has(tool.definition.name));
631
643
  }
632
644
  // A tool the permission profile forbids is not offered: CapabilityPolicy would refuse every call to it. Plan mode
633
- // keeps its own fixed tool list.
645
+ // keeps its own fixed tool list. Nor is one that would start a program of the agent's outside the OS sandbox a
646
+ // profile holds its commands to, unless the profile asks the person before each command (commandsSandboxOnly);
647
+ // ztc_command stays, and each of its calls is judged by what its command starts.
634
648
  if (mode !== 'plan') {
635
649
  const allowed = permissionPolicy.capabilities;
650
+ const sandboxOnly = commandsSandboxOnly(permissionProfile, options.config.sandbox, permissionPolicy.approvalRequiredCapabilities);
636
651
  filteredTools = filteredTools.filter(tool => (tool.capabilities ?? []).every(capability => allowed[capability] !== false)
637
- && !shellOutsideSandbox(allowed.file_write !== false, tool.capabilities ?? [], tool.sandboxedCommands));
652
+ && !shellOutsideSandbox(allowed.file_write !== false, tool.capabilities ?? [], tool.sandboxedCommands)
653
+ && !(sandboxOnly && startsProgramsOutsideSandbox(tool.capabilities ?? [], tool)));
638
654
  }
639
655
  if (toolGroups && hostToolAllowlist && !hostToolAllowlist.has(toolGroups.loaderName) && !isCodexAppServerProvider(provider)) {
640
656
  throw new Error('Tool group loader is unavailable under the host tool allowlist.');
@@ -711,6 +727,8 @@ export function createAgentFromConfig(options) {
711
727
  isSubagent: false,
712
728
  }, {
713
729
  approvalRequester: options.hookApprovalRequester,
730
+ // Hooks run under the agent's own command policy: inside the OS sandbox it requires, or not at all.
731
+ commandPolicy: () => ({ profileId: permissionPolicy.id, profile: permissionProfile, sandbox: options.config.sandbox }),
714
732
  });
715
733
  if (remoteResourceSession) {
716
734
  filteredTools = [createRemoteResourceTool(remoteResourceSession), askUserTool, recallToolResponseTool, sessionEvidenceTool];
@@ -782,7 +800,7 @@ export function createAgentFromConfig(options) {
782
800
  ]),
783
801
  ...(teamLead ? { leadTurnNote: leadTurnNote(workersFree), leadStaffingNote: LEAD_STAFFING_NOTE,
784
802
  workerCheckIntervalMs: (options.config.workers?.checkIntervalSec ?? 600) * 1000 } : {}),
785
- policy: new CapabilityPolicy(options.config.toolPermissions, permissionProfile, cwd),
803
+ policy,
786
804
  autoContinue: options.autoContinue ?? options.config.autoContinue ?? true,
787
805
  completionCheck: options.completionCheck,
788
806
  runCheck: options.runCheck,
@@ -22,6 +22,7 @@ import { imageResultCaption, parseImageToolResult, toolResultText, withToolResul
22
22
  import { assistantClaimReplayContent } from './claim_observation.js';
23
23
  import { presentToolResult, toolCallNames } from './tool_result_presentation.js';
24
24
  import { COPY_ADVICE, resultCopyNote } from '../utils/tool_output_copies.js';
25
+ import { withheldImagesIn } from './attached_images.js';
25
26
  const OLD_RESULT_CAP = 2000;
26
27
  // Rewriting a near-cap result saves little but changes the cacheable history.
27
28
  // Keep small results stable; large historical results still use the 2K cap.
@@ -82,7 +83,11 @@ export class RequestEncoder {
82
83
  this.freezeContent(m, assistantContent);
83
84
  return { role: m.role, content: assistantContent };
84
85
  }
85
- return { role: m.role, content: structuredClone(m.nativeContent), ...(responseItems ? { responseItems } : {}) };
86
+ // The images a person attached that Zerg Router refused under a spending limit go as their note, replayed too.
87
+ const native = structuredClone(m.nativeContent);
88
+ const withheld = m.role === 'user' && typeof m.metadata?.withheldImages === 'string' ? m.metadata.withheldImages : undefined;
89
+ return { role: m.role, content: withheld === undefined ? native : withheldImagesIn(native, withheld, m.metadata?.keptImageTypes),
90
+ ...(responseItems ? { responseItems } : {}) };
86
91
  }
87
92
  if (m.role === 'user') {
88
93
  // Summaries and host observations quote source text. Preserve those
@@ -95,7 +100,11 @@ export class RequestEncoder {
95
100
  if (m.metadata?.compactionSummary) {
96
101
  return { role: m.role, content: m.content };
97
102
  }
98
- const content = this.buildUserContentBlocks(m.content, m.attachments || []);
103
+ // Each image the person attached that Zerg Router refused under a spending limit goes as its note
104
+ // (agent/attached_images.ts), in this request and every later one.
105
+ const built = this.buildUserContentBlocks(m.content, m.attachments || []);
106
+ const content = typeof m.metadata?.withheldImages === 'string'
107
+ ? withheldImagesIn(built, m.metadata.withheldImages, m.metadata.keptImageTypes) : built;
99
108
  this.freezeContent(m, content);
100
109
  return {
101
110
  role: m.role,
@@ -197,6 +197,18 @@ function createJob(options) {
197
197
  publish(sessionId);
198
198
  return job;
199
199
  }
200
+ /** How much of a failed command's stderr its receipt keeps as its error: the end, where a failure is told. */
201
+ const ERROR_TAIL = 4096;
202
+ /**
203
+ * What a failed job's receipt keeps of STDERR as its error: all of it up to ERROR_TAIL characters, else an ellipsis and
204
+ * its last ERROR_TAIL - 1. The ellipsis says where it was cut: a cut can fall inside a credential, and a read-only
205
+ * observer of the mirror is withheld what may be the rest of one after the mark. Undefined when STDERR is empty.
206
+ */
207
+ function stderrTail(stderr) {
208
+ if (stderr.length <= ERROR_TAIL)
209
+ return stderr || undefined;
210
+ return `…${stderr.slice(-(ERROR_TAIL - 1))}`;
211
+ }
200
212
  /** Records the process's end on the receipt, persists it and wakes readers. */
201
213
  function settleJob(sessionId, job, running, cleanup, onSettled) {
202
214
  const registry = sessions.get(sessionId);
@@ -212,6 +224,9 @@ function settleJob(sessionId, job, running, cleanup, onSettled) {
212
224
  if (result.outputHeldOpen)
213
225
  job.receipt.warning = [job.receipt.warning, 'Processes the command started were still running '
214
226
  + 'after the command exited and held its output open; their later output is not recorded.'].filter(Boolean).join(' ');
227
+ // What the sandbox's step after the command undid (utils/sandbox.ts afterCommand).
228
+ if (result.sandboxNotes)
229
+ job.receipt.warning = [job.receipt.warning, ...result.sandboxNotes].filter(Boolean).join(' ');
215
230
  if (result.checked)
216
231
  job.receipt.checked = structuredClone(result.checked);
217
232
  if (job.receipt.status !== 'interrupted')
@@ -220,7 +235,7 @@ function settleJob(sessionId, job, running, cleanup, onSettled) {
220
235
  : result.checked.status === 'cancelled' ? 'cancelled' : 'failed'
221
236
  : result.timedOut === true ? 'timed_out' : result.exitCode === 0 ? 'completed' : 'failed';
222
237
  if (result.exitCode !== 0)
223
- job.receipt.error = result.stderr.slice(-4096) || `Command exited with code ${result.exitCode}`;
238
+ job.receipt.error = stderrTail(result.stderr) ?? `Command exited with code ${result.exitCode}`;
224
239
  job.receipt.ended_at = new Date().toISOString();
225
240
  }, error => {
226
241
  if (job.receipt.status !== 'interrupted')
@@ -234,7 +234,10 @@ export class CommandPaneManager {
234
234
  let start = 0;
235
235
  while (start < bytesRead && (buffer[start] & 0xc0) === 0x80)
236
236
  start++;
237
- return (size > length ? '[earlier output omitted from pane; attach evidence for retained log]\n' : '') + buffer.subarray(start, bytesRead).toString('utf8');
237
+ const text = buffer.subarray(start, bytesRead).toString('utf8');
238
+ // A cut log is shown whole after a mark where it was cut: the cut may fall inside a credential, and a read-only
239
+ // observer of the mirror is withheld what may be the rest of one after the mark (observer_secret_redaction.ts).
240
+ return size > length ? `[earlier output omitted from pane; attach evidence for retained log]\n…${text}` : text;
238
241
  }
239
242
  finally {
240
243
  await file.close();
@@ -19,5 +19,12 @@ export interface ExecutionContext {
19
19
  settings: Required<ExecutionSettings>;
20
20
  jobs: CommandReceipt[];
21
21
  }
22
- export declare function describeExecutionContext(context: ExecutionContext): string;
22
+ /**
23
+ * The agent's execution facts, as its prompt holds them each request, its permission policy among them (the profile's
24
+ * capabilities and file roots). SHOWN.permissions false leaves that out, as /status --verbose does: /permissions is where
25
+ * a person reads what the profile allows, and a host that lets a controller read /status may not let it read that.
26
+ */
27
+ export declare function describeExecutionContext(context: ExecutionContext, shown?: {
28
+ permissions?: boolean;
29
+ }): string;
23
30
  export { resolveExecutionSettings };
@@ -29,7 +29,12 @@ function managedCommandSummary(jobs) {
29
29
  }
30
30
  return `[${rows.join(',')}]${jobs.length > rows.length ? `; ${jobs.length - rows.length} additional or oversized command summaries omitted` : ''}`;
31
31
  }
32
- export function describeExecutionContext(context) {
32
+ /**
33
+ * The agent's execution facts, as its prompt holds them each request, its permission policy among them (the profile's
34
+ * capabilities and file roots). SHOWN.permissions false leaves that out, as /status --verbose does: /permissions is where
35
+ * a person reads what the profile allows, and a host that lets a controller read /status may not let it read that.
36
+ */
37
+ export function describeExecutionContext(context, shown = {}) {
33
38
  const names = new Set(context.tools);
34
39
  const shell = ['run_command', 'Bash', 'exec_command', 'shell_command'].filter(name => names.has(name));
35
40
  const panes = ['create_terminal_pane', 'read_terminal_pane', 'write_terminal_pane'].filter(name => names.has(name));
@@ -40,7 +45,8 @@ export function describeExecutionContext(context) {
40
45
  `Tool-call budget: at most ${context.settings.maxCallsPerResponse} total calls (reads + effects) per response, of which at most ${context.settings.maxEffectsPerResponse} effects (writes, commands, unknown tools); reads count only toward the total. Read concurrency: ${context.settings.readConcurrency}; this bounds overlapping reads independently of the total-call budget. Oversized batches execute no tools.`,
41
46
  'Send calls that do not depend on each other\'s results together in one response. Plan exploration in bounded rounds. Inspect prerequisite results before dependent effects, and inspect failed or running commands before continuing dependent work.',
42
47
  `Mode: ${context.mode}. Cwd: ${cwd}. Config write scope: ${context.configScope}.`,
43
- context.permissions ? describePermissionPolicy(context.permissions) : 'Permission policy not reported by this host; OS isolation is not established.',
48
+ ...(shown.permissions === false ? []
49
+ : [context.permissions ? describePermissionPolicy(context.permissions) : 'Permission policy not reported by this host; OS isolation is not established.']),
44
50
  `Output cap: ${context.maxTokens ?? 'provider default'} (source: ${context.outputLimitSource}). Use /config max-tokens <number|default> to change it.`,
45
51
  `Shell: ${shell.length ? shell.join(', ') : 'unavailable in the current tool surface'}.`,
46
52
  `Mux: ${context.mux ? 'connected' : 'unavailable'}. Pane tools: ${panes.join(', ') || 'unavailable in this mode'}.`,