@zergai/ztc 0.17.0-beta.1 → 0.18.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 (52) hide show
  1. package/README.md +3 -2
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +1 -1
  7. package/dist/App.js +21 -7
  8. package/dist/agent/backends/router_gate.js +3 -2
  9. package/dist/agent/backends/router_refusal_record.d.ts +12 -2
  10. package/dist/agent/backends/router_refusal_record.js +19 -4
  11. package/dist/agent/tools/pane.d.ts +6 -1
  12. package/dist/agent/tools/pane.js +6 -4
  13. package/dist/app/mirror_startup.d.ts +7 -0
  14. package/dist/app/mirror_startup.js +10 -0
  15. package/dist/app/restart.d.ts +6 -0
  16. package/dist/app/restart.js +13 -3
  17. package/dist/app/workspace_monitor.js +17 -3
  18. package/dist/app/workspace_presets.js +8 -1
  19. package/dist/cli_main.js +5 -0
  20. package/dist/cli_ratatui.d.ts +87 -18
  21. package/dist/cli_ratatui.js +234 -129
  22. package/dist/embedded/anempa_runtime.js +3 -0
  23. package/dist/embedded/gameboy_runtime.js +4 -2
  24. package/dist/embedded/zergpod_runtime.js +4 -2
  25. package/dist/environment/store.js +4 -1
  26. package/dist/mcp/client.js +6 -2
  27. package/dist/mcp/workspace_server.d.ts +7 -3
  28. package/dist/mcp/workspace_server.js +15 -8
  29. package/dist/panes/agent_cli.d.ts +10 -3
  30. package/dist/panes/agent_cli.js +16 -4
  31. package/dist/runtime_info.js +10 -1
  32. package/dist/simulation/engines/swarm/pane_manager.d.ts +16 -3
  33. package/dist/simulation/engines/swarm/pane_manager.js +39 -17
  34. package/dist/types.d.ts +5 -2
  35. package/dist/ui/ratatui/headless_pane_manager.d.ts +13 -1
  36. package/dist/ui/ratatui/headless_pane_manager.js +37 -8
  37. package/dist/ui/ratatui/pane_credential_broker.d.ts +107 -0
  38. package/dist/ui/ratatui/pane_credential_broker.js +239 -0
  39. package/dist/ui/ratatui/pane_relay.js +4 -2
  40. package/dist/ui/ratatui/process.d.ts +13 -0
  41. package/dist/ui/ratatui/process.js +38 -3
  42. package/dist/utils/subprocess_env.js +1 -0
  43. package/dist/web/mirror_authenticator.d.ts +27 -11
  44. package/dist/web/mirror_authenticator.js +36 -12
  45. package/dist/web/mirror_client.d.ts +2 -1
  46. package/dist/web/mirror_client.js +7 -5
  47. package/dist/web/mirror_stream.d.ts +39 -8
  48. package/dist/web/mirror_stream.js +164 -29
  49. package/dist/web/pane_credentials.d.ts +131 -0
  50. package/dist/web/pane_credentials.js +302 -0
  51. package/dist/zlm-embed.mjs +2 -1
  52. package/package.json +11 -46
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'child_process';
2
2
  import { existsSync, mkdirSync, readFileSync } from 'fs';
3
3
  import { join } from 'path';
4
+ import { withoutMirrorCredentials } from '../web/pane_credentials.js';
4
5
  const DEFAULT_REFRESH_MS = 5000;
5
6
  const EVENT_LIMIT = 28;
6
7
  function runtime_refresh_ms(system) {
@@ -195,6 +196,8 @@ export class AnempaRuntimeSession {
195
196
  const child = spawn(join(this.context.system.projectDir, 'scripts', 'run_simulator.sh'), [], {
196
197
  cwd: this.context.system.projectDir,
197
198
  stdio: ['ignore', 'ignore', 'pipe'],
199
+ // Without the mirror credentials this process holds, which any program running as this user could read there.
200
+ env: withoutMirrorCredentials(process.env),
198
201
  });
199
202
  this.activeChild = child;
200
203
  let stderr = '';
@@ -2,6 +2,7 @@ import { spawn } from 'child_process';
2
2
  import { existsSync, mkdirSync, writeFileSync } from 'fs';
3
3
  import { join } from 'path';
4
4
  import { createInterface } from 'readline';
5
+ import { withoutMirrorCredentials } from '../web/pane_credentials.js';
5
6
  const DEFAULT_TICK_MS = 33;
6
7
  const DEFAULT_FRAME_BUDGET = 12000;
7
8
  const DEFAULT_WARMUP_FRAME_BUDGET = 96000;
@@ -187,7 +188,8 @@ async function run_script(projectDir, scriptPath) {
187
188
  const child = spawn('zsh', ['-lc', `cd "${projectDir}" && "${scriptPath}"`], {
188
189
  cwd: projectDir,
189
190
  stdio: ['ignore', 'ignore', 'pipe'],
190
- env: process.env,
191
+ // Without the mirror credentials this process holds, which any program running as this user could read there.
192
+ env: withoutMirrorCredentials(process.env),
191
193
  });
192
194
  let stderr = '';
193
195
  child.stderr.on('data', (chunk) => {
@@ -262,7 +264,7 @@ export class GameboyRuntimeSession {
262
264
  cwd: this.system.projectDir,
263
265
  stdio: ['pipe', 'pipe', 'pipe'],
264
266
  env: {
265
- ...process.env,
267
+ ...withoutMirrorCredentials(process.env),
266
268
  PYTHONDONTWRITEBYTECODE: '1',
267
269
  },
268
270
  });
@@ -2,6 +2,7 @@ import { spawn } from 'child_process';
2
2
  import { existsSync, mkdirSync, readFileSync } from 'fs';
3
3
  import { join } from 'path';
4
4
  import { createInterface } from 'readline';
5
+ import { withoutMirrorCredentials } from '../web/pane_credentials.js';
5
6
  const DEFAULT_TICK_MS = 180;
6
7
  const DEFAULT_FRAME_BUDGET = 64;
7
8
  const ARTIFACT_REFRESH_MS = 1000;
@@ -348,7 +349,8 @@ async function run_script(projectDir, scriptPath) {
348
349
  const child = spawn('zsh', ['-lc', `cd "${projectDir}" && "${scriptPath}"`], {
349
350
  cwd: projectDir,
350
351
  stdio: ['ignore', 'ignore', 'pipe'],
351
- env: process.env,
352
+ // Without the mirror credentials this process holds, which any program running as this user could read there.
353
+ env: withoutMirrorCredentials(process.env),
352
354
  });
353
355
  let stderr = '';
354
356
  child.stderr.on('data', (chunk) => {
@@ -417,7 +419,7 @@ export class ZergpodRuntimeSession {
417
419
  cwd: this.system.projectDir,
418
420
  stdio: ['pipe', 'pipe', 'pipe'],
419
421
  env: {
420
- ...process.env,
422
+ ...withoutMirrorCredentials(process.env),
421
423
  PYTHONDONTWRITEBYTECODE: '1',
422
424
  ...(this.hardwareProfileId ? { ZERGPOD_HARDWARE_PROFILE: this.hardwareProfileId } : {}),
423
425
  },
@@ -7,6 +7,7 @@ import { spawn } from 'node:child_process';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { activeProfile, validateProfileName } from '../config/profiles.js';
9
9
  import { writeFileAtomic } from '../utils/atomic_write.js';
10
+ import { withoutMirrorCredentials } from '../web/pane_credentials.js';
10
11
  const root = () => join(process.env.ZTC_CONFIG_DIR || join(homedir(), '.ztc'), 'environments');
11
12
  const namePattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
12
13
  const valid = (name) => {
@@ -301,7 +302,9 @@ export async function startEnvironmentService(name, sessionId, serviceName, comm
301
302
  await save(record);
302
303
  const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
303
304
  const runner = fileURLToPath(new URL(`./service_runner.${extension}`, import.meta.url));
304
- const child = spawn(process.execPath, [...(extension === 'ts' ? ['--import', import.meta.resolve('tsx')] : []), runner, serviceDir], { cwd: serviceCwd, detached: true, stdio: 'ignore', env: process.env });
305
+ // The runner starts without the mirror's credentials this process holds: any program running as this user can read
306
+ // the environment a process starts with.
307
+ const child = spawn(process.execPath, [...(extension === 'ts' ? ['--import', import.meta.resolve('tsx')] : []), runner, serviceDir], { cwd: serviceCwd, detached: true, stdio: 'ignore', env: withoutMirrorCredentials(process.env) });
305
308
  child.unref();
306
309
  try {
307
310
  await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
@@ -1,6 +1,7 @@
1
1
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
2
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
3
3
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
4
+ import { withoutMirrorCredentials } from '../web/pane_credentials.js';
4
5
  export const MAX_MCP_IMAGE_BYTES = 4 * 1024 * 1024;
5
6
  const CLIENT_INFO = { name: 'ztc', version: '0.1.0' };
6
7
  // Connection-independent state and accessors live in registry.ts (so light
@@ -20,10 +21,13 @@ function withTimeout(promise, ms, label) {
20
21
  });
21
22
  return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
22
23
  }
23
- /** Env for an stdio MCP child: the parent env plus the entry's own overrides. */
24
+ /**
25
+ * Env for an stdio MCP child: the parent env, less this process's mirror credentials (an MCP server is someone
26
+ * else's program, and they speak for every pane), plus the entry's own overrides.
27
+ */
24
28
  function buildStdioEnv(extra) {
25
29
  const env = {};
26
- for (const [k, v] of Object.entries(process.env)) {
30
+ for (const [k, v] of Object.entries(withoutMirrorCredentials(process.env))) {
27
31
  if (typeof v === 'string')
28
32
  env[k] = v;
29
33
  }
@@ -6,8 +6,9 @@
6
6
  * $ZTC_PANE_ID, and gives the agent the workspace: list panes; open a ZTC
7
7
  * agent, Claude Code, Codex or a shell; read a pane; type into one; message
8
8
  * another agent; close a pane. Messages travel over ZTC's bus when the mirror
9
- * is reachable, so ZTC panes receive them as messages from this pane;
10
- * otherwise they are typed in with the sender's name.
9
+ * is reachable, with this pane's own mirror credential ($ZTC_MIRROR_PANE_TOKEN),
10
+ * so ZTC panes receive them as messages from this pane and the mirror takes
11
+ * them as nothing else; otherwise they are typed in with the sender's name.
11
12
  *
12
13
  * It runs in a process of its own, so it reads ZTC's saved settings before
13
14
  * each pane it opens, and the pane follows them as they are then: Claude Code
@@ -50,7 +51,10 @@ export interface WorkspaceMcpOptions {
50
51
  }
51
52
  /** The MCP server, connected to a workspace through `transport`. */
52
53
  export declare function createWorkspaceMcpServer(options: WorkspaceMcpOptions): Server;
53
- /** Posts bus messages to the overseer's mirror, as MirrorClient does, without joining the bus. */
54
+ /**
55
+ * Posts bus messages to the overseer's mirror, as MirrorClient does, without joining the bus. It presents the pane's
56
+ * own mirror credential, so the mirror takes its messages as this pane's, and only as this pane's.
57
+ */
54
58
  export declare function mirrorBusSender(env?: NodeJS.ProcessEnv): WorkspaceBusSender | null;
55
59
  /** Entry point for `ztc workspace-mcp`: serve on stdio until the CLI closes it. */
56
60
  export declare function runWorkspaceMcpServer(env?: NodeJS.ProcessEnv): Promise<void>;
@@ -6,8 +6,9 @@
6
6
  * $ZTC_PANE_ID, and gives the agent the workspace: list panes; open a ZTC
7
7
  * agent, Claude Code, Codex or a shell; read a pane; type into one; message
8
8
  * another agent; close a pane. Messages travel over ZTC's bus when the mirror
9
- * is reachable, so ZTC panes receive them as messages from this pane;
10
- * otherwise they are typed in with the sender's name.
9
+ * is reachable, with this pane's own mirror credential ($ZTC_MIRROR_PANE_TOKEN),
10
+ * so ZTC panes receive them as messages from this pane and the mirror takes
11
+ * them as nothing else; otherwise they are typed in with the sender's name.
11
12
  *
12
13
  * It runs in a process of its own, so it reads ZTC's saved settings before
13
14
  * each pane it opens, and the pane follows them as they are then: Claude Code
@@ -28,6 +29,7 @@ import { buildZtcPaneLaunchCommand, createZtcLaunchSpec } from '../panes/ztc_lau
28
29
  import { PaneRelayClient } from '../ui/ratatui/pane_relay.js';
29
30
  import { buildUserSubprocessEnvOverrides } from '../utils/subprocess_env.js';
30
31
  import { getVersion } from '../utils/version.js';
32
+ import { paneMirrorCredentialHeaders } from '../web/pane_credentials.js';
31
33
  const PANE_REF = {
32
34
  description: 'The pane: its id, or its name as list_panes shows it.',
33
35
  anyOf: [{ type: 'integer', minimum: 0 }, { type: 'string', minLength: 1 }],
@@ -320,15 +322,17 @@ export function createWorkspaceMcpServer(options) {
320
322
  const text = String(args.text ?? '').trim();
321
323
  if (!text)
322
324
  throw new ToolError('text is required.');
323
- const from = { id: ownPaneId ?? -1, name: await ownName() };
324
325
  const broadcast = typeof args.to === 'string' && args.to.trim().toLowerCase() === 'all';
325
326
  const target = broadcast ? null : await findPane(args.to);
326
- if (options.bus) {
327
+ // On the bus this pane speaks as itself, which its credential stands for; a server with no pane id has no bus.
328
+ if (options.bus && ownPaneId !== null) {
329
+ const from = { id: ownPaneId, name: await ownName() };
327
330
  await options.bus.send({ from, to: target ? target.id : 'all', type: 'ztc_message', text });
328
331
  return target ? `Message sent to ${paneName(target)} (pane ${target.id}).` : 'Message sent to every ZTC agent.';
329
332
  }
330
333
  if (!target)
331
334
  throw new ToolError('Sending to "all" needs ZTC\'s message bus, which this pane cannot reach; send to one pane at a time.');
335
+ const from = { id: ownPaneId ?? -1, name: await ownName() };
332
336
  await typeInto(target, formatAgentPaneMessage({ from, text }), true);
333
337
  return `Message typed into ${paneName(target)} (pane ${target.id}).`;
334
338
  },
@@ -356,11 +360,14 @@ export function createWorkspaceMcpServer(options) {
356
360
  });
357
361
  return server;
358
362
  }
359
- /** Posts bus messages to the overseer's mirror, as MirrorClient does, without joining the bus. */
363
+ /**
364
+ * Posts bus messages to the overseer's mirror, as MirrorClient does, without joining the bus. It presents the pane's
365
+ * own mirror credential, so the mirror takes its messages as this pane's, and only as this pane's.
366
+ */
360
367
  export function mirrorBusSender(env = process.env) {
361
368
  const port = Number(env.ZTC_MIRROR_PORT);
362
- const token = env.ZTC_MIRROR_INTERNAL_TOKEN;
363
- if (!Number.isInteger(port) || port <= 0 || !token)
369
+ const credential = paneMirrorCredentialHeaders(env);
370
+ if (!Number.isInteger(port) || port <= 0 || Object.keys(credential).length === 0)
364
371
  return null;
365
372
  const group = env.ZTC_MIRROR_GROUP?.trim();
366
373
  return {
@@ -374,7 +381,7 @@ export function mirrorBusSender(env = process.env) {
374
381
  headers: {
375
382
  'Content-Type': 'application/json',
376
383
  'Content-Length': Buffer.byteLength(body),
377
- 'x-ztc-internal-token': token,
384
+ ...credential,
378
385
  },
379
386
  }, res => {
380
387
  let text = '';
@@ -73,8 +73,13 @@ export declare const WORKSPACE_MCP_SERVER_NAME = "ztc";
73
73
  * Variables the workspace server reads, where ZTC's settings are among them
74
74
  * (the profile and ZTC_CONFIG_DIR). Codex starts MCP servers with a short
75
75
  * allowlist of variables, so these are named for it to forward; Claude Code
76
- * passes its whole environment. They reach the pane through its environment,
77
- * never its command line.
76
+ * passes its whole environment, to its Bash tool and hooks too. They reach the
77
+ * pane through its environment, never its command line. The mirror credential
78
+ * among them is the pane's own, which acts only as that pane; the mirror's
79
+ * process-wide token is never one of them. Any program running as this user can
80
+ * read a process's environment, and act as this pane with the credential; a
81
+ * ZTC pane or a workspace monitor, whose own programs start nothing that needs
82
+ * it, takes its credential from a one-time file instead.
78
83
  */
79
84
  export declare const WORKSPACE_MCP_ENV: readonly string[];
80
85
  /** The CLI's own arguments that attach the workspace server, or nothing without one. */
@@ -101,7 +106,9 @@ export declare function nextPaneTitle(label: string, existing: readonly string[]
101
106
  * The pane's environment overrides: ZTC's control variables are cleared as for
102
107
  * any user program, except what the workspace server needs to reach this
103
108
  * workspace. Everything else is the user's own environment, untouched, so the
104
- * CLI offers every sign-in method it normally would.
109
+ * CLI offers every sign-in method it normally would. The pane's mirror
110
+ * credential is asked of the pane transport, which mints one for this pane
111
+ * alone (PaneCredentialBroker); no credential of the opener's is copied.
105
112
  */
106
113
  export declare function agentPaneEnv(source?: NodeJS.ProcessEnv): Record<string, string>;
107
114
  /**
@@ -21,6 +21,7 @@ import { basename, dirname, join } from 'node:path';
21
21
  import { resolveOwnedCliLaunch } from '../desktop/cli_launch.js';
22
22
  import { isProfileName } from './agent_profiles.js';
23
23
  import { buildUserSubprocessEnvOverrides } from '../utils/subprocess_env.js';
24
+ import { PANE_CREDENTIAL_ENV, PANE_CREDENTIAL_REQUEST } from '../web/pane_credentials.js';
24
25
  export const AGENT_CLIS = Object.freeze({
25
26
  claude: {
26
27
  id: 'claude',
@@ -193,14 +194,19 @@ export const WORKSPACE_MCP_SERVER_NAME = 'ztc';
193
194
  * Variables the workspace server reads, where ZTC's settings are among them
194
195
  * (the profile and ZTC_CONFIG_DIR). Codex starts MCP servers with a short
195
196
  * allowlist of variables, so these are named for it to forward; Claude Code
196
- * passes its whole environment. They reach the pane through its environment,
197
- * never its command line.
197
+ * passes its whole environment, to its Bash tool and hooks too. They reach the
198
+ * pane through its environment, never its command line. The mirror credential
199
+ * among them is the pane's own, which acts only as that pane; the mirror's
200
+ * process-wide token is never one of them. Any program running as this user can
201
+ * read a process's environment, and act as this pane with the credential; a
202
+ * ZTC pane or a workspace monitor, whose own programs start nothing that needs
203
+ * it, takes its credential from a one-time file instead.
198
204
  */
199
205
  export const WORKSPACE_MCP_ENV = Object.freeze([
200
206
  'ZTC_PANE_ID',
201
207
  'ZTC_PANE_RELAY',
202
208
  'ZTC_MIRROR_PORT',
203
- 'ZTC_MIRROR_INTERNAL_TOKEN',
209
+ PANE_CREDENTIAL_ENV,
204
210
  'ZTC_MIRROR_GROUP',
205
211
  'ZTC_NAVIGATOR_GROUP',
206
212
  'ZTC_PROFILE',
@@ -279,13 +285,19 @@ export function nextPaneTitle(label, existing) {
279
285
  * The pane's environment overrides: ZTC's control variables are cleared as for
280
286
  * any user program, except what the workspace server needs to reach this
281
287
  * workspace. Everything else is the user's own environment, untouched, so the
282
- * CLI offers every sign-in method it normally would.
288
+ * CLI offers every sign-in method it normally would. The pane's mirror
289
+ * credential is asked of the pane transport, which mints one for this pane
290
+ * alone (PaneCredentialBroker); no credential of the opener's is copied.
283
291
  */
284
292
  export function agentPaneEnv(source = process.env) {
285
293
  const env = buildUserSubprocessEnvOverrides();
286
294
  for (const key of WORKSPACE_MCP_ENV) {
287
295
  if (key === 'ZTC_PANE_ID')
288
296
  continue; // the renderer sets each pane's own
297
+ if (key === PANE_CREDENTIAL_ENV) {
298
+ env[key] = PANE_CREDENTIAL_REQUEST;
299
+ continue;
300
+ }
289
301
  const value = source[key];
290
302
  if (value)
291
303
  env[key] = value;
@@ -2,6 +2,7 @@ import { execFile, execFileSync } from 'child_process';
2
2
  import { createHash } from 'crypto';
3
3
  import { existsSync, realpathSync } from 'fs';
4
4
  import { getVersion } from './utils/version.js';
5
+ import { withoutMirrorCredentials } from './web/pane_credentials.js';
5
6
  const STARTED_AT = new Date();
6
7
  const GIT_TIMEOUT_MS = 2_000;
7
8
  const DIFF_HASH_TIMEOUT_MS = 5_000;
@@ -17,12 +18,20 @@ function gitErrorText(error) {
17
18
  const stderrText = Buffer.isBuffer(stderr) ? stderr.toString('utf8') : String(stderr ?? '');
18
19
  return `${stderrText}\n${String(message ?? '')}`;
19
20
  }
21
+ /**
22
+ * The environment a git probe starts with: this process's, without the mirror credentials it holds, since any program
23
+ * running as this user can read the environment a process starts with (git's hooks and helpers start with it too).
24
+ */
25
+ function gitEnvironment() {
26
+ return withoutMirrorCredentials(process.env);
27
+ }
20
28
  function runGit(cwd, args, timeout = GIT_TIMEOUT_MS) {
21
29
  try {
22
30
  const output = execFileSync('git', args, {
23
31
  cwd,
24
32
  encoding: 'utf8',
25
33
  timeout,
34
+ env: gitEnvironment(),
26
35
  stdio: ['ignore', 'pipe', 'pipe'],
27
36
  // Leading spaces carry meaning: porcelain's " M file" is unstaged, and a full trim once turned it into a staged
28
37
  // "M nventory/..." for the model (2026-10-27).
@@ -168,7 +177,7 @@ function gatherGitOutputsSync(cwd, includeDirtyHash) {
168
177
  */
169
178
  function runGitAsync(cwd, args, timeout = GIT_TIMEOUT_MS) {
170
179
  return new Promise((resolve) => {
171
- execFile('git', args, { cwd, encoding: 'utf8', timeout }, (error, stdout) => {
180
+ execFile('git', args, { cwd, encoding: 'utf8', timeout, env: gitEnvironment() }, (error, stdout) => {
172
181
  if (error) {
173
182
  const failure = /not a git repository/i.test(gitErrorText(error)) ? 'not_repository' : 'unknown';
174
183
  resolve({ ok: false, failure });
@@ -18,8 +18,16 @@ export declare class PaneInfrastructure {
18
18
  tuiProcess: PaneHost | null;
19
19
  relayServer: PaneRelayServer | null;
20
20
  mirrorServer: MirrorStreamServer | null;
21
- /** Env vars set during setup — tracked so teardown cleans up exactly what was set. */
22
- envVarsSet: string[];
21
+ /**
22
+ * Env vars setup replaced: what each held before the run (undefined when unset) and the value the run put there.
23
+ * Teardown puts each back while it still holds the run's value, so the ZTC that ran the sim keeps its own mirror
24
+ * port and pane relay, and leaves one that something else changed meanwhile.
25
+ */
26
+ envVarsSet: Array<{
27
+ name: string;
28
+ before: string | undefined;
29
+ value: string | undefined;
30
+ }>;
23
31
  humanPanes: Array<{
24
32
  paneId: number;
25
33
  transport: PaneCommandTransport;
@@ -38,6 +46,8 @@ export interface PaneHost extends PaneCommandTransport {
38
46
  rows: number;
39
47
  }>;
40
48
  stop(): Promise<void>;
49
+ /** The mirror the run runs: a pane a pane opens through the run's relay is pointed at it and gets its credential there. */
50
+ setOwnerMirrorPort(port: number | undefined): void;
41
51
  }
42
52
  /**
43
53
  * The notification log arrays that the bus observer fills and the
@@ -78,7 +88,10 @@ export declare function observeSwarmBusMessage(msg: BusMessage, logs: PaneObserv
78
88
  * buildUserSubprocessEnv() strips it from generic user subprocesses.
79
89
  * Passed explicitly as create_pane `env` so the pane manager merges it back
80
90
  * after stripping — without it, children boot but never attach to the message
81
- * bus and periods complete with zero agent activity.
91
+ * bus and periods complete with zero agent activity. Each ZTC pane's mirror
92
+ * credential is its own, which the pane transport hands it as it creates the
93
+ * pane, in a one-time file its command line names (PaneCredentialBroker); the
94
+ * process-wide token is never passed on.
82
95
  */
83
96
  export declare function simPaneBusEnv(source?: NodeJS.ProcessEnv): Record<string, string>;
84
97
  export type PaneStartupPolicy = 'fail_fast' | 'degraded';
@@ -41,7 +41,11 @@ export class PaneInfrastructure {
41
41
  tuiProcess = null;
42
42
  relayServer = null;
43
43
  mirrorServer = null;
44
- /** Env vars set during setup — tracked so teardown cleans up exactly what was set. */
44
+ /**
45
+ * Env vars setup replaced: what each held before the run (undefined when unset) and the value the run put there.
46
+ * Teardown puts each back while it still holds the run's value, so the ZTC that ran the sim keeps its own mirror
47
+ * port and pane relay, and leaves one that something else changed meanwhile.
48
+ */
45
49
  envVarsSet = [];
46
50
  humanPanes = [];
47
51
  /** Bus subscription handles — captured at registration so teardown can detach
@@ -126,14 +130,15 @@ function findZtcEntrypoint() {
126
130
  * buildUserSubprocessEnv() strips it from generic user subprocesses.
127
131
  * Passed explicitly as create_pane `env` so the pane manager merges it back
128
132
  * after stripping — without it, children boot but never attach to the message
129
- * bus and periods complete with zero agent activity.
133
+ * bus and periods complete with zero agent activity. Each ZTC pane's mirror
134
+ * credential is its own, which the pane transport hands it as it creates the
135
+ * pane, in a one-time file its command line names (PaneCredentialBroker); the
136
+ * process-wide token is never passed on.
130
137
  */
131
138
  export function simPaneBusEnv(source = process.env) {
132
139
  const env = {};
133
140
  if (source.ZTC_MIRROR_PORT)
134
141
  env.ZTC_MIRROR_PORT = source.ZTC_MIRROR_PORT;
135
- if (source.ZTC_MIRROR_INTERNAL_TOKEN)
136
- env.ZTC_MIRROR_INTERNAL_TOKEN = source.ZTC_MIRROR_INTERNAL_TOKEN;
137
142
  if (source.ZTC_PANE_RELAY)
138
143
  env.ZTC_PANE_RELAY = source.ZTC_PANE_RELAY;
139
144
  return env;
@@ -359,8 +364,9 @@ export async function setupRealPanes(state, logs, infra, onProgress, agentsOverr
359
364
  // 2. Set env vars BEFORE zmux starts (inherited by children via PTY).
360
365
  // Must be on process.env because zmux PTY children inherit the parent environment.
361
366
  // Protected from concurrent sim corruption by _starting lock in GameSessionManager.
362
- // Clean up all sim env vars before setting new ones — derived from simEnv keys
363
- // plus ZTC_MIRROR_PORT which is set conditionally later.
367
+ // Clear all sim env vars before setting new ones — derived from simEnv keys
368
+ // plus ZTC_MIRROR_PORT which is set conditionally later — keeping what each
369
+ // held for teardown to put back.
364
370
  const simEnv = {
365
371
  ZTC_PANE_RELAY: generateRelaySocketPath(),
366
372
  ZTC_SIM_FREE_MODE: '1',
@@ -368,13 +374,14 @@ export async function setupRealPanes(state, logs, infra, onProgress, agentsOverr
368
374
  ZTC_SIM_OUTPUT_DIR: state.config.outputDir,
369
375
  ZTC_SIM_DOMAIN: state.preset.name,
370
376
  };
371
- for (const key of [...Object.keys(simEnv), 'ZTC_MIRROR_PORT']) {
372
- delete process.env[key];
377
+ infra.envVarsSet = [...Object.keys(simEnv), 'ZTC_MIRROR_PORT']
378
+ .map(name => ({ name, before: process.env[name], value: undefined }));
379
+ for (const { name } of infra.envVarsSet) {
380
+ delete process.env[name];
373
381
  }
374
382
  for (const [key, val] of Object.entries(simEnv)) {
375
- process.env[key] = val;
383
+ setRunEnv(infra, key, val);
376
384
  }
377
- infra.envVarsSet = Object.keys(simEnv);
378
385
  // Render dynamic system prompt from j2 template — includes domain tool descriptions.
379
386
  // Done in the parent so the rendered string can be passed via env if needed; child panes
380
387
  // already inherit ZTC_SIM_DOMAIN and rebuild the allowlist themselves in factory.ts.
@@ -408,8 +415,7 @@ export async function setupRealPanes(state, logs, infra, onProgress, agentsOverr
408
415
  observeSwarmBusMessage(msg, observerLogs, onProgress);
409
416
  }));
410
417
  await infra.mirrorServer.start();
411
- process.env.ZTC_MIRROR_PORT = String(infra.mirrorServer.getPort());
412
- infra.envVarsSet.push('ZTC_MIRROR_PORT');
418
+ setRunEnv(infra, 'ZTC_MIRROR_PORT', String(infra.mirrorServer.getPort()));
413
419
  onProgress(`[panes] Message bus started on port ${infra.mirrorServer.getPort()}`);
414
420
  // 4. Start native zmux in headless mode for autonomous simulation panes.
415
421
  // This keeps real PTY semantics while running without an interactive UI.
@@ -426,7 +432,9 @@ export async function setupRealPanes(state, logs, infra, onProgress, agentsOverr
426
432
  setPaneToolsTuiProcess(infra.tuiProcess);
427
433
  onProgress(`[panes] Native zmux (headless) started (${cols}x${rows})`);
428
434
  }
429
- // 5. Start PaneRelayServer so children can manage sub-panes
435
+ // 5. Start PaneRelayServer so children can manage sub-panes. A pane a pane opens through it talks to the run's
436
+ // mirror, whatever mirror this process names meanwhile.
437
+ infra.tuiProcess.setOwnerMirrorPort(infra.mirrorServer.getPort());
430
438
  infra.relayServer = new PaneRelayServer(infra.tuiProcess, simEnv.ZTC_PANE_RELAY);
431
439
  await infra.relayServer.start();
432
440
  // 6. Wire bus transport (same pattern as cli_ratatui.ts:419-431)
@@ -652,6 +660,13 @@ export async function waitForBusResponses(log, paneIds, timeoutMs, stopSignal, s
652
660
  }
653
661
  return responses;
654
662
  }
663
+ /** Set NAME for the run in process.env, noting the value so teardown can tell whether it is still the run's. */
664
+ function setRunEnv(infra, name, value) {
665
+ process.env[name] = value;
666
+ const replaced = infra.envVarsSet.find(entry => entry.name === name);
667
+ if (replaced)
668
+ replaced.value = value;
669
+ }
655
670
  /** Clean up zmux, relay, and mirror server for a given run's infrastructure. */
656
671
  export async function teardownPanes(infra) {
657
672
  // Detach bus observers BEFORE stopping the mirror server. If a reused server
@@ -697,10 +712,17 @@ export async function teardownPanes(infra) {
697
712
  // Release the concurrency guard first — even if subsequent cleanup throws,
698
713
  // the flag must not stay true and prevent future runs.
699
714
  _freeSimRunning = false; // R1: release concurrency guard
700
- // Clean up process.env vars set during setupRealPanes to prevent leaking
701
- // sim state into normal ZTC operation after a run completes.
702
- for (const key of infra.envVarsSet) {
703
- delete process.env[key];
715
+ // Put back the process.env vars setupRealPanes replaced, so no sim state
716
+ // leaks into normal ZTC operation after a run completes and the ZTC that ran
717
+ // it keeps reaching its own mirror and pane relay. A var something else
718
+ // changed during the run (a mirror this ZTC started or stopped) stays.
719
+ for (const { name, before, value } of infra.envVarsSet) {
720
+ if (process.env[name] !== value)
721
+ continue;
722
+ if (before === undefined)
723
+ delete process.env[name];
724
+ else
725
+ process.env[name] = before;
704
726
  }
705
727
  infra.envVarsSet = [];
706
728
  clearBusTransport();
package/dist/types.d.ts CHANGED
@@ -44,8 +44,11 @@ export interface QueueEntry {
44
44
  * The person entered this entry themselves (typed, dictated, or sent from
45
45
  * the browser mirror), so it runs as theirs when it is sent: with the
46
46
  * choices only they make, such as where dictation transcribes, and one real
47
- * attempt past a Zerg Router refusal. Absent: input relayed to this ZTC (a
48
- * /loop tick, another pane's message), which stays relayed when queued.
47
+ * attempt past a Zerg Router refusal, unless where they entered it is
48
+ * relayed (a ZTC pane's or a colony cell's terminal, which the overseer's
49
+ * write_terminal_pane types into too; see the TUI's handleSubmit). Absent:
50
+ * input relayed to this ZTC (a /loop tick, another pane's message), which
51
+ * stays relayed when queued.
49
52
  */
50
53
  person?: boolean;
51
54
  /**
@@ -5,7 +5,11 @@ export declare function encodeZtcPaneInput(input: string): string;
5
5
  /**
6
6
  * Compute the env a managed pane child is spawned with.
7
7
  *
8
- * colony_ztc panes are framework children and inherit the full parent env.
8
+ * colony_ztc panes are framework children and inherit the full parent env,
9
+ * except the parent's mirror credentials (withoutMirrorCredentials): each pane
10
+ * is given a credential of its own by PaneCredentialBroker: a ZTC pane or a
11
+ * workspace monitor in a one-time file its arguments name, any other pane in
12
+ * `commandEnv`.
9
13
  * Every other pane type runs as a user subprocess: ZTC infra vars
10
14
  * (ZTC_MIRROR_PORT, ZTC_PANE_RELAY, ...) are stripped via
11
15
  * buildUserSubprocessEnv so nested user processes don't inherit the parent's
@@ -39,6 +43,8 @@ export declare class HeadlessPaneManager implements PaneCommandTransport {
39
43
  private layout;
40
44
  private workspaceMetadata;
41
45
  private hostLabels;
46
+ /** Each pane's own mirror credential, bound to the id this manager assigns before it spawns. */
47
+ private readonly paneCredentials;
42
48
  private exitSubscribed;
43
49
  private readonly exitHandler;
44
50
  constructor(options?: {
@@ -48,6 +54,12 @@ export declare class HeadlessPaneManager implements PaneCommandTransport {
48
54
  private unsubscribeFromExit;
49
55
  /** Set the display title for pane 0 (the host ZTC process). */
50
56
  setHostTitle(title: string): void;
57
+ /**
58
+ * PORT is the mirror this manager's owner runs now, or undefined once it stops: a pane a pane opens through the relay
59
+ * is pointed at it and gets its credential there, whatever mirror this process's environment names by then (a /sim
60
+ * run names its own while it runs). See PaneCredentialBroker.setOwnerMirrorPort.
61
+ */
62
+ setOwnerMirrorPort(port: number | undefined): void;
51
63
  get isMuxMode(): boolean;
52
64
  get zmuxMirrorSocketPath(): string | null;
53
65
  /** HeadlessPaneManager never spawns zmux; callback never fires. */