@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
@@ -20,6 +20,8 @@ import { delimiter, dirname, isAbsolute, join, resolve } from 'path';
20
20
  import { createRequire } from 'module';
21
21
  import { isMuxPaneRestorable, resolveMuxPersistenceOptions, sanitizeMuxSessionState, validateWorkspaceState } from './mux_persistence.js';
22
22
  import { buildUserSubprocessEnv, removeUserSubprocessCredentials, restoreModelRouteCredentials } from '../../utils/subprocess_env.js';
23
+ import { withoutMirrorCredentials } from '../../web/pane_credentials.js';
24
+ import { PaneCredentialBroker } from './pane_credential_broker.js';
23
25
  import { handleWorkspaceLayout } from '../../workspace_layout.js';
24
26
  let _ptyMod;
25
27
  function loadPty() {
@@ -99,7 +101,11 @@ export function encodeZtcPaneInput(input) {
99
101
  /**
100
102
  * Compute the env a managed pane child is spawned with.
101
103
  *
102
- * colony_ztc panes are framework children and inherit the full parent env.
104
+ * colony_ztc panes are framework children and inherit the full parent env,
105
+ * except the parent's mirror credentials (withoutMirrorCredentials): each pane
106
+ * is given a credential of its own by PaneCredentialBroker: a ZTC pane or a
107
+ * workspace monitor in a one-time file its arguments name, any other pane in
108
+ * `commandEnv`.
103
109
  * Every other pane type runs as a user subprocess: ZTC infra vars
104
110
  * (ZTC_MIRROR_PORT, ZTC_PANE_RELAY, ...) are stripped via
105
111
  * buildUserSubprocessEnv so nested user processes don't inherit the parent's
@@ -112,7 +118,7 @@ export function encodeZtcPaneInput(input) {
112
118
  */
113
119
  export function computePaneSpawnEnv(paneType, paneId, options = {}, source = process.env) {
114
120
  const env = {
115
- ...(paneType === 'colony_ztc' ? source : buildUserSubprocessEnv(source)),
121
+ ...(paneType === 'colony_ztc' ? withoutMirrorCredentials(source) : buildUserSubprocessEnv(source)),
116
122
  ...(paneType === 'colony_ztc' ? {} : { ZTC_HEADLESS_MUX: '1' }),
117
123
  ZTC_PANE_ID: String(paneId),
118
124
  ...(options.persona ? { ZTC_SIM_PERSONA: options.persona } : {}),
@@ -201,6 +207,8 @@ export class HeadlessPaneManager {
201
207
  geometry: { cols: 120, rows: 40 },
202
208
  };
203
209
  hostLabels = {};
210
+ /** Each pane's own mirror credential, bound to the id this manager assigns before it spawns. */
211
+ paneCredentials = new PaneCredentialBroker();
204
212
  exitSubscribed = false;
205
213
  exitHandler = () => {
206
214
  for (const pane of this.panes.values()) {
@@ -231,6 +239,14 @@ export class HeadlessPaneManager {
231
239
  setHostTitle(title) {
232
240
  this.hostTitle = title;
233
241
  }
242
+ /**
243
+ * PORT is the mirror this manager's owner runs now, or undefined once it stops: a pane a pane opens through the relay
244
+ * is pointed at it and gets its credential there, whatever mirror this process's environment names by then (a /sim
245
+ * run names its own while it runs). See PaneCredentialBroker.setOwnerMirrorPort.
246
+ */
247
+ setOwnerMirrorPort(port) {
248
+ this.paneCredentials.setOwnerMirrorPort(port);
249
+ }
234
250
  get isMuxMode() {
235
251
  return true;
236
252
  }
@@ -248,6 +264,8 @@ export class HeadlessPaneManager {
248
264
  };
249
265
  }
250
266
  emit(event) {
267
+ if (event.type === 'pane_closed')
268
+ this.paneCredentials.closed(event.pane_id);
251
269
  for (const h of this.handlers) {
252
270
  try {
253
271
  h(event);
@@ -367,6 +385,7 @@ export class HeadlessPaneManager {
367
385
  }
368
386
  this.panes.clear();
369
387
  this.closedPanes.clear();
388
+ this.paneCredentials.revokeAll();
370
389
  this.unsubscribeFromExit();
371
390
  }
372
391
  kill() {
@@ -382,6 +401,7 @@ export class HeadlessPaneManager {
382
401
  }
383
402
  this.panes.clear();
384
403
  this.closedPanes.clear();
404
+ this.paneCredentials.revokeAll();
385
405
  this.unsubscribeFromExit();
386
406
  }
387
407
  // --------------------------------------------------------------------------
@@ -435,10 +455,16 @@ export class HeadlessPaneManager {
435
455
  const groupId = cmd.env?.ZTC_MIRROR_GROUP || '';
436
456
  // Reuse the shared env builder (dev's computePaneSpawnEnv) — behaviourally
437
457
  // identical to the old inline childEnv. The actual spawn (PTY-aware) lives
438
- // below and consumes childEnv for both the PTY and child_process paths.
458
+ // below and consumes childEnv for both the PTY and child_process paths. The
459
+ // pane's mirror credential is its own, bound to the id assigned above: in
460
+ // its environment, or for a ZTC pane or a workspace monitor in a one-time
461
+ // file the arguments it is spawned with name (never in pane.launch, which
462
+ // a relaunch or a saved workspace reuses).
463
+ const prepared = this.paneCredentials.prepare(cmd, id, paneType);
464
+ const spawnArgs = prepared.args ?? args;
439
465
  const childEnv = computePaneSpawnEnv(paneType, id, {
440
466
  persona: cmd.persona,
441
- commandEnv: cmd.env,
467
+ commandEnv: prepared.env,
442
468
  });
443
469
  const pane = {
444
470
  id,
@@ -511,7 +537,7 @@ export class HeadlessPaneManager {
511
537
  if (ptyMod) {
512
538
  let ptyProc;
513
539
  try {
514
- ptyProc = ptyMod.spawn(cmd.command, args, {
540
+ ptyProc = ptyMod.spawn(cmd.command, spawnArgs, {
515
541
  name: 'xterm-256color',
516
542
  cols: 80,
517
543
  rows: 24,
@@ -533,7 +559,7 @@ export class HeadlessPaneManager {
533
559
  else {
534
560
  let child;
535
561
  try {
536
- child = spawn(cmd.command, args, {
562
+ child = spawn(cmd.command, spawnArgs, {
537
563
  cwd,
538
564
  stdio: ['pipe', 'pipe', 'pipe'],
539
565
  env: childEnv,
@@ -643,10 +669,13 @@ export class HeadlessPaneManager {
643
669
  const cwd = cmd.cwd || process.cwd();
644
670
  const title = cmd.title || pane.title;
645
671
  const paneType = cmd.pane_type || pane.paneType;
646
- const child = spawn(cmd.command, args, {
672
+ // A relaunched ZTC pane's credential is a fresh one, in a one-time file its arguments name; the program it replaced
673
+ // never had it.
674
+ const relaunch = this.paneCredentials.prepareRelaunch(cmd, paneType, cmd.pane_id);
675
+ const child = spawn(cmd.command, relaunch.args, {
647
676
  cwd,
648
677
  stdio: ['pipe', 'pipe', 'pipe'],
649
- env: computePaneSpawnEnv(paneType, cmd.pane_id),
678
+ env: computePaneSpawnEnv(paneType, cmd.pane_id, { commandEnv: relaunch.env }),
650
679
  shell: !isZtcPaneType(paneType),
651
680
  });
652
681
  const nextPane = {
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Gives each pane a pane transport creates its own mirror credential (see web/pane_credentials.ts).
3
+ *
4
+ * Every create_pane a transport sends to its renderer, its owner's own or one a child forwarded through the pane relay,
5
+ * passes through prepare(). The mirror's process-wide token and shared secret are cleared in the pane's environment
6
+ * (the renderer was spawned without them as well), and so is any credential the launcher copied. A ZTC pane, or a pane
7
+ * whose launcher asked for one, then gets a fresh credential from the mirror it will talk to: the one its owner's
8
+ * command names or, when it names none, the one it inherits (see the constructor). A pane a pane opens through the
9
+ * relay always talks to the mirror its transport's owner runs now (setOwnerMirrorPort), or the one it inherits while
10
+ * its owner names none, whatever its command names. A ZTC pane and a workspace monitor are handed theirs in a one-time
11
+ * owner-only file their command line names (PANE_CREDENTIAL_FILE_FLAG), since any program running as this user can read
12
+ * the environment a pane's program starts with; a pane whose launcher asked for a plain one (a Claude Code or Codex
13
+ * pane, whose CLI starts the workspace tools with its environment) gets it in its environment. The file is removed with
14
+ * the credential if its program never took it. A renderer that assigns pane ids before it spawns (the headless pane
15
+ * manager) binds the credential at once. Otherwise the command goes to the renderer under a request id the broker
16
+ * chose, never its sender's: a pane chooses the ids of what it sends through the relay, and could give a pane it opens
17
+ * the id of a pane it replaces. The credential is bound when pane_created reports the pane under that id, and the
18
+ * transport reports the pane under its sender's own (created). A ZTC pane its owner has the renderer start again in
19
+ * place (replace_pane, through prepareReplace) gets a fresh credential the same way, in a one-time file, since
20
+ * replace_pane carries no environment either. A closed pane's credential is revoked, and so is the credential of a pane
21
+ * the renderer relaunches in place without one: zmux's restart_pane, which starts the program with the renderer's
22
+ * environment alone, or a replace a pane asked for through the relay. (The desktop app's restart keeps the pane's own
23
+ * environment and command line and reports no new pane, so a pane's credential stays bound; a program that took its
24
+ * credential from a file, which it deleted, starts again without it.)
25
+ */
26
+ import type { RustCommand } from './protocol.js';
27
+ type CreatePane = Extract<RustCommand, {
28
+ type: 'create_pane';
29
+ }>;
30
+ type ReplacePane = Extract<RustCommand, {
31
+ type: 'replace_pane';
32
+ }>;
33
+ /**
34
+ * Mark a command that a pane sent through the pane relay. The mark is a hidden property, so it never reaches the
35
+ * renderer or changes the command's shape; it tells the transport the command is a pane's, which may ask for a plain
36
+ * credential for a pane it opens, never a workspace monitor's, and only from the mirror its transport's owner runs, and
37
+ * gets none for a pane it relaunches in place.
38
+ */
39
+ export declare function markRelayed<T extends object>(command: T): T;
40
+ export declare class PaneCredentialBroker {
41
+ private readonly inheritedMirrorPort;
42
+ /** Credentials waiting for pane_created, by the request id the broker sent their create_pane or replace_pane under. */
43
+ private readonly pending;
44
+ /** The credential each pane holds, by pane id. */
45
+ private readonly bound;
46
+ /** The mirror the transport's owner runs now, if it named one (setOwnerMirrorPort). */
47
+ private ownerMirrorPort;
48
+ /**
49
+ * INHERITED_MIRROR_PORT gives the ZTC_MIRROR_PORT a pane inherits when its command names none. A renderer process
50
+ * starts each pane with its own environment, fixed when it was spawned, and the pane's merged over it: its transport
51
+ * gives the port it spawned the renderer with, which this process's environment may no longer name (a /sim run in
52
+ * this process names its own mirror while it runs). A transport that builds each pane's whole environment itself (the
53
+ * headless pane manager) gives this process's own, as it is when the pane starts.
54
+ */
55
+ constructor(inheritedMirrorPort?: () => string | undefined);
56
+ /**
57
+ * PORT is the mirror the transport's owner runs now (a ZTC's own, from its start and each /mirror start, or a /sim
58
+ * run's), or undefined once it stops. A pane a pane opens through the relay is pointed at that mirror and gets its
59
+ * credential there, whatever its command names: the mirror the renderer was spawned with can be gone by then, after
60
+ * /mirror stop and a /mirror start on another port. With no mirror named, it gets the inherited one.
61
+ */
62
+ setOwnerMirrorPort(port: number | undefined): void;
63
+ /**
64
+ * The create_pane to send for CMD: its environment rewritten as above, the handoff its credential is in named among
65
+ * its arguments' options when it is a ZTC pane or a workspace monitor (withHandoff), and, when it carries an unbound
66
+ * credential, the broker's own request id to bind it by. PANE_ID is the pane's id when the transport assigns it before
67
+ * spawning, and PANE_TYPE the type it settled on when the command named none.
68
+ */
69
+ prepare(cmd: CreatePane, paneId?: number, paneType?: string | undefined): CreatePane;
70
+ /** prepare(), and the credential the command carries, if any. */
71
+ private issue;
72
+ /**
73
+ * The replace_pane to send for CMD. A ZTC pane its owner has the renderer start again in place (a resumed agent
74
+ * session) gets a fresh credential from the mirror it inherits, bound when pane_created reports it, as a new pane's
75
+ * is. replace_pane carries no environment, so the credential goes in a one-time owner-only file whose path is
76
+ * added to the command line (PANE_CREDENTIAL_FILE_FLAG); the ZTC deletes it as it starts, and the file is removed if
77
+ * the pane never appears or closes first. A pane that asks the relay to replace a pane gets none for it.
78
+ */
79
+ prepareReplace(cmd: ReplacePane): ReplacePane;
80
+ /**
81
+ * The environment and arguments for a pane a transport relaunches in place under PANE_ID with CMD (the headless pane
82
+ * manager's replace_pane): a fresh credential for a ZTC pane its owner relaunches, in a one-time file its arguments
83
+ * name, and none for one a pane relaunches, whose old credential is revoked.
84
+ */
85
+ prepareRelaunch(cmd: ReplacePane, paneType: string, paneId: number): {
86
+ env: Record<string, string>;
87
+ args: string[];
88
+ };
89
+ /**
90
+ * The renderer reports a pane under REQUEST_ID: bind the credential its create_pane or replace_pane carried, and
91
+ * return the request id the transport reports the pane under, its sender's own. Any other pane_created for a pane that
92
+ * holds a credential means its program was relaunched in place without one (restart_pane, or a replace a pane asked
93
+ * for): revoke it.
94
+ */
95
+ created(paneId: number, requestId?: string): string | undefined;
96
+ /** The pane closed: its credential stops working, and a handoff its program never took is removed. */
97
+ closed(paneId: number): void;
98
+ /** The renderer is gone: every credential it was given stops working. */
99
+ revokeAll(): void;
100
+ /**
101
+ * Keep WAITING until pane_created reports its pane, or give it up after PENDING_BIND_MS. Returns the request id to send
102
+ * its command under: a fresh one of the broker's, which no sender chose and so no other command carries.
103
+ */
104
+ private await;
105
+ private hold;
106
+ }
107
+ export {};
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Gives each pane a pane transport creates its own mirror credential (see web/pane_credentials.ts).
3
+ *
4
+ * Every create_pane a transport sends to its renderer, its owner's own or one a child forwarded through the pane relay,
5
+ * passes through prepare(). The mirror's process-wide token and shared secret are cleared in the pane's environment
6
+ * (the renderer was spawned without them as well), and so is any credential the launcher copied. A ZTC pane, or a pane
7
+ * whose launcher asked for one, then gets a fresh credential from the mirror it will talk to: the one its owner's
8
+ * command names or, when it names none, the one it inherits (see the constructor). A pane a pane opens through the
9
+ * relay always talks to the mirror its transport's owner runs now (setOwnerMirrorPort), or the one it inherits while
10
+ * its owner names none, whatever its command names. A ZTC pane and a workspace monitor are handed theirs in a one-time
11
+ * owner-only file their command line names (PANE_CREDENTIAL_FILE_FLAG), since any program running as this user can read
12
+ * the environment a pane's program starts with; a pane whose launcher asked for a plain one (a Claude Code or Codex
13
+ * pane, whose CLI starts the workspace tools with its environment) gets it in its environment. The file is removed with
14
+ * the credential if its program never took it. A renderer that assigns pane ids before it spawns (the headless pane
15
+ * manager) binds the credential at once. Otherwise the command goes to the renderer under a request id the broker
16
+ * chose, never its sender's: a pane chooses the ids of what it sends through the relay, and could give a pane it opens
17
+ * the id of a pane it replaces. The credential is bound when pane_created reports the pane under that id, and the
18
+ * transport reports the pane under its sender's own (created). A ZTC pane its owner has the renderer start again in
19
+ * place (replace_pane, through prepareReplace) gets a fresh credential the same way, in a one-time file, since
20
+ * replace_pane carries no environment either. A closed pane's credential is revoked, and so is the credential of a pane
21
+ * the renderer relaunches in place without one: zmux's restart_pane, which starts the program with the renderer's
22
+ * environment alone, or a replace a pane asked for through the relay. (The desktop app's restart keeps the pane's own
23
+ * environment and command line and reports no new pane, so a pane's credential stays bound; a program that took its
24
+ * credential from a file, which it deleted, starts again without it.)
25
+ */
26
+ import { randomUUID } from 'node:crypto';
27
+ import { OWNER_MIRROR_CREDENTIAL_ENV, PANE_CREDENTIAL_ENV, PANE_CREDENTIAL_FILE_FLAG, WORKSPACE_MONITOR_CREDENTIAL_REQUEST, paneCredentialStoreForPort, removePaneCredentialHandoff, writePaneCredentialHandoff, } from '../../web/pane_credentials.js';
28
+ /** How long an unbound credential waits for its pane_created (the store drops it then too). */
29
+ const PENDING_BIND_MS = 30_000;
30
+ const RELAYED = Symbol('ztc.paneRelayed');
31
+ /**
32
+ * Mark a command that a pane sent through the pane relay. The mark is a hidden property, so it never reaches the
33
+ * renderer or changes the command's shape; it tells the transport the command is a pane's, which may ask for a plain
34
+ * credential for a pane it opens, never a workspace monitor's, and only from the mirror its transport's owner runs, and
35
+ * gets none for a pane it relaunches in place.
36
+ */
37
+ export function markRelayed(command) {
38
+ Object.defineProperty(command, RELAYED, { value: true });
39
+ return command;
40
+ }
41
+ function isRelayed(command) {
42
+ return command[RELAYED] === true;
43
+ }
44
+ function isZtcPane(paneType) {
45
+ return paneType === 'ztc' || paneType === 'colony_ztc';
46
+ }
47
+ /**
48
+ * ARGS with the flag naming HANDOFF among the pane program's options. A ZTC pane opened with a task (New pane or New
49
+ * session, an isolated ZTC, the workspace tools' ZTC pane) ends its command line with its end of options ('--') and the
50
+ * task, which is literal text whatever it says, so the flag goes before the two. Otherwise it goes at the end, which is
51
+ * still the program's own arguments when Motsi runs the program after an end of options of its own.
52
+ */
53
+ function withHandoff(args, handoff) {
54
+ const flag = [PANE_CREDENTIAL_FILE_FLAG, handoff];
55
+ return args.at(-2) === '--' ? [...args.slice(0, -2), ...flag, ...args.slice(-2)] : [...args, ...flag];
56
+ }
57
+ export class PaneCredentialBroker {
58
+ inheritedMirrorPort;
59
+ /** Credentials waiting for pane_created, by the request id the broker sent their create_pane or replace_pane under. */
60
+ pending = new Map();
61
+ /** The credential each pane holds, by pane id. */
62
+ bound = new Map();
63
+ /** The mirror the transport's owner runs now, if it named one (setOwnerMirrorPort). */
64
+ ownerMirrorPort;
65
+ /**
66
+ * INHERITED_MIRROR_PORT gives the ZTC_MIRROR_PORT a pane inherits when its command names none. A renderer process
67
+ * starts each pane with its own environment, fixed when it was spawned, and the pane's merged over it: its transport
68
+ * gives the port it spawned the renderer with, which this process's environment may no longer name (a /sim run in
69
+ * this process names its own mirror while it runs). A transport that builds each pane's whole environment itself (the
70
+ * headless pane manager) gives this process's own, as it is when the pane starts.
71
+ */
72
+ constructor(inheritedMirrorPort = () => process.env.ZTC_MIRROR_PORT) {
73
+ this.inheritedMirrorPort = inheritedMirrorPort;
74
+ }
75
+ /**
76
+ * PORT is the mirror the transport's owner runs now (a ZTC's own, from its start and each /mirror start, or a /sim
77
+ * run's), or undefined once it stops. A pane a pane opens through the relay is pointed at that mirror and gets its
78
+ * credential there, whatever its command names: the mirror the renderer was spawned with can be gone by then, after
79
+ * /mirror stop and a /mirror start on another port. With no mirror named, it gets the inherited one.
80
+ */
81
+ setOwnerMirrorPort(port) {
82
+ this.ownerMirrorPort = port;
83
+ }
84
+ /**
85
+ * The create_pane to send for CMD: its environment rewritten as above, the handoff its credential is in named among
86
+ * its arguments' options when it is a ZTC pane or a workspace monitor (withHandoff), and, when it carries an unbound
87
+ * credential, the broker's own request id to bind it by. PANE_ID is the pane's id when the transport assigns it before
88
+ * spawning, and PANE_TYPE the type it settled on when the command named none.
89
+ */
90
+ prepare(cmd, paneId, paneType = cmd.pane_type) {
91
+ return this.issue(cmd, paneId, paneType).command;
92
+ }
93
+ /** prepare(), and the credential the command carries, if any. */
94
+ issue(cmd, paneId, paneType) {
95
+ const env = { ...(cmd.env ?? {}) };
96
+ const requested = env[PANE_CREDENTIAL_ENV];
97
+ const scope = requested === WORKSPACE_MONITOR_CREDENTIAL_REQUEST && !isRelayed(cmd)
98
+ ? 'workspace-monitor'
99
+ : requested || isZtcPane(paneType) ? 'pane' : null;
100
+ // A renderer merges a pane's environment over its own, so the names are cleared there. A transport that assigns
101
+ // ids builds each pane's whole environment itself, without them (computePaneSpawnEnv), so they are left out.
102
+ for (const name of OWNER_MIRROR_CREDENTIAL_ENV) {
103
+ if (paneId === undefined)
104
+ env[name] = '';
105
+ else
106
+ delete env[name];
107
+ }
108
+ if (!scope)
109
+ return { command: { ...cmd, env } };
110
+ // A pane a pane opens through the relay talks to the mirror its transport's owner runs, whatever mirror its command
111
+ // names: a mirror numbers its panes by its own renderer's ids, which another renderer (a /sim run's) reuses for its
112
+ // panes.
113
+ const port = isRelayed(cmd) ? this.ownerMirrorPort ?? Number(this.inheritedMirrorPort())
114
+ : Number(env.ZTC_MIRROR_PORT || this.inheritedMirrorPort());
115
+ const store = paneCredentialStoreForPort(port);
116
+ if (!store)
117
+ return { command: { ...cmd, env } };
118
+ const credential = store.issue(scope, paneId);
119
+ let handoff;
120
+ if (scope === 'workspace-monitor' || isZtcPane(paneType)) {
121
+ // Never in its environment, which any program running as this user can read: in a file only it is told of.
122
+ try {
123
+ handoff = writePaneCredentialHandoff(credential.token);
124
+ }
125
+ catch {
126
+ credential.revoke();
127
+ return { command: { ...cmd, env } };
128
+ }
129
+ }
130
+ else {
131
+ env[PANE_CREDENTIAL_ENV] = credential.token;
132
+ }
133
+ // The pane talks to the mirror that issued its credential.
134
+ env.ZTC_MIRROR_PORT = String(port);
135
+ const held = { credential, handoff };
136
+ const args = handoff ? withHandoff(cmd.args ?? [], handoff) : cmd.args;
137
+ const command = { ...cmd, env, ...(args ? { args } : {}) };
138
+ if (paneId !== undefined) {
139
+ this.hold(paneId, held);
140
+ return { command, held };
141
+ }
142
+ return { command: { ...command, request_id: this.await({ held, requestId: cmd.request_id }) }, held };
143
+ }
144
+ /**
145
+ * The replace_pane to send for CMD. A ZTC pane its owner has the renderer start again in place (a resumed agent
146
+ * session) gets a fresh credential from the mirror it inherits, bound when pane_created reports it, as a new pane's
147
+ * is. replace_pane carries no environment, so the credential goes in a one-time owner-only file whose path is
148
+ * added to the command line (PANE_CREDENTIAL_FILE_FLAG); the ZTC deletes it as it starts, and the file is removed if
149
+ * the pane never appears or closes first. A pane that asks the relay to replace a pane gets none for it.
150
+ */
151
+ prepareReplace(cmd) {
152
+ if (!isZtcPane(cmd.pane_type) || isRelayed(cmd))
153
+ return cmd;
154
+ // replace_pane carries no environment: the program talks to the mirror the renderer's own environment names.
155
+ const store = paneCredentialStoreForPort(Number(this.inheritedMirrorPort()));
156
+ if (!store)
157
+ return cmd;
158
+ const credential = store.issue('pane');
159
+ let handoff;
160
+ try {
161
+ handoff = writePaneCredentialHandoff(credential.token);
162
+ }
163
+ catch {
164
+ credential.revoke();
165
+ return cmd;
166
+ }
167
+ const requestId = this.await({ held: { credential, handoff }, requestId: cmd.request_id });
168
+ return { ...cmd, request_id: requestId, args: withHandoff(cmd.args ?? [], handoff) };
169
+ }
170
+ /**
171
+ * The environment and arguments for a pane a transport relaunches in place under PANE_ID with CMD (the headless pane
172
+ * manager's replace_pane): a fresh credential for a ZTC pane its owner relaunches, in a one-time file its arguments
173
+ * name, and none for one a pane relaunches, whose old credential is revoked.
174
+ */
175
+ prepareRelaunch(cmd, paneType, paneId) {
176
+ const relaunch = { type: 'create_pane', command: cmd.command ?? '', args: cmd.args ?? [] };
177
+ const { command, held } = this.issue(relaunch, paneId, isRelayed(cmd) ? undefined : paneType);
178
+ if (!held)
179
+ this.closed(paneId);
180
+ return { env: command.env ?? {}, args: command.args ?? [] };
181
+ }
182
+ /**
183
+ * The renderer reports a pane under REQUEST_ID: bind the credential its create_pane or replace_pane carried, and
184
+ * return the request id the transport reports the pane under, its sender's own. Any other pane_created for a pane that
185
+ * holds a credential means its program was relaunched in place without one (restart_pane, or a replace a pane asked
186
+ * for): revoke it.
187
+ */
188
+ created(paneId, requestId) {
189
+ const waiting = requestId === undefined ? undefined : this.pending.get(requestId);
190
+ if (!waiting) {
191
+ this.closed(paneId);
192
+ return requestId;
193
+ }
194
+ this.pending.delete(requestId);
195
+ this.hold(paneId, waiting.held);
196
+ return waiting.requestId;
197
+ }
198
+ /** The pane closed: its credential stops working, and a handoff its program never took is removed. */
199
+ closed(paneId) {
200
+ const held = this.bound.get(paneId);
201
+ this.bound.delete(paneId);
202
+ if (held)
203
+ release(held);
204
+ }
205
+ /** The renderer is gone: every credential it was given stops working. */
206
+ revokeAll() {
207
+ for (const held of [...[...this.pending.values()].map(waiting => waiting.held), ...this.bound.values()])
208
+ release(held);
209
+ this.pending.clear();
210
+ this.bound.clear();
211
+ }
212
+ /**
213
+ * Keep WAITING until pane_created reports its pane, or give it up after PENDING_BIND_MS. Returns the request id to send
214
+ * its command under: a fresh one of the broker's, which no sender chose and so no other command carries.
215
+ */
216
+ await(waiting) {
217
+ const requestId = `pane-credential-${randomUUID()}`;
218
+ this.pending.set(requestId, waiting);
219
+ setTimeout(() => {
220
+ if (this.pending.get(requestId) !== waiting)
221
+ return;
222
+ this.pending.delete(requestId);
223
+ release(waiting.held);
224
+ }, PENDING_BIND_MS).unref();
225
+ return requestId;
226
+ }
227
+ hold(paneId, held) {
228
+ const previous = this.bound.get(paneId);
229
+ if (previous && previous.credential !== held.credential)
230
+ release(previous);
231
+ held.credential.bind(paneId);
232
+ this.bound.set(paneId, held);
233
+ }
234
+ }
235
+ function release(held) {
236
+ held.credential.revoke();
237
+ if (held.handoff)
238
+ removePaneCredentialHandoff(held.handoff);
239
+ }
@@ -14,6 +14,7 @@ import { createInterface } from 'readline';
14
14
  import { serializeCommand, parseEvent, CAPABILITY_PANE_DELIVERY_ACK, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_SYNCHRONIZED_OUTPUT, CAPABILITY_ATTENTION_BADGES } from './protocol.js';
15
15
  import { runtimeDiag } from '../../utils/debug_log.js';
16
16
  import { generateIpcPath, removeOwnedIpcPath } from './ipc_path.js';
17
+ import { markRelayed } from './pane_credential_broker.js';
17
18
  // ============================================================================
18
19
  // PaneRelayServer — runs in parent ZTC (--mux mode)
19
20
  // ============================================================================
@@ -68,8 +69,9 @@ export class PaneRelayServer {
68
69
  if (!parsed)
69
70
  return;
70
71
  // Treat incoming lines as commands (same JSON shape as RustCommand)
71
- // Forward to parent's TuiProcess
72
- this.transport.send(parsed);
72
+ // Forward to parent's TuiProcess, marked as a pane's: a pane it opens gets a plain credential of its own,
73
+ // never a workspace monitor's, and a pane it relaunches in place gets none (PaneCredentialBroker).
74
+ this.transport.send(markRelayed(parsed));
73
75
  });
74
76
  client.on('error', () => {
75
77
  this.clients.delete(client);
@@ -124,6 +124,13 @@ export declare class TuiProcess {
124
124
  */
125
125
  private _zmuxMirrorSocketListeners;
126
126
  private _capabilities;
127
+ /** ZTC_MIRROR_PORT as the renderer was spawned with it, which every pane it starts inherits. */
128
+ private rendererMirrorPort;
129
+ /**
130
+ * Each pane's own mirror credential, from the mirror the pane talks to, bound when the renderer reports the pane
131
+ * (see PaneCredentialBroker).
132
+ */
133
+ private readonly paneCredentials;
127
134
  /**
128
135
  * In-flight `read_clipboard_image` requests, keyed by request id. The
129
136
  * renderer answers asynchronously (it reads and PNG-encodes the clipboard
@@ -143,6 +150,12 @@ export declare class TuiProcess {
143
150
  * when the path arrives.
144
151
  */
145
152
  onZmuxMirrorSocketReady(cb: (path: string) => void): () => void;
153
+ /**
154
+ * PORT is the mirror this transport's owner runs now, or undefined once it stops: a pane a pane opens through the
155
+ * relay is pointed at it and gets its credential there (PaneCredentialBroker.setOwnerMirrorPort). It can differ from
156
+ * the one the renderer was spawned with, after /mirror stop and a /mirror start on another port.
157
+ */
158
+ setOwnerMirrorPort(port: number | undefined): void;
146
159
  /**
147
160
  * Subscribe to events from the Rust process
148
161
  */
@@ -20,6 +20,8 @@ import { generateIpcPath, removeOwnedIpcPath } from './ipc_path.js';
20
20
  import { loadDesktopRuntime, validateDesktopRendererReady } from '../../desktop/runtime.js';
21
21
  import { debugFileLog as debugLog, describeInputForLog } from '../../utils/debug_log.js';
22
22
  import { rendererOpensInBackground } from '../../utils/session_interactivity.js';
23
+ import { withoutMirrorCredentials } from '../../web/pane_credentials.js';
24
+ import { PaneCredentialBroker } from './pane_credential_broker.js';
23
25
  /** Renderer events that carry no user text, logged whole. */
24
26
  const PLAIN_RENDERER_EVENTS = new Set(['ready', 'resize', 'resize_ack', 'quit_requested']);
25
27
  /**
@@ -249,7 +251,8 @@ export async function launchZtermDesktop(options) {
249
251
  const child = spawn(binaryPath, spawnArgs, {
250
252
  stdio: 'inherit',
251
253
  cwd: options?.cwd ?? process.cwd(),
252
- env: { ...process.env },
254
+ // The desktop app and the panes it opens never inherit a mirror credential of this process's.
255
+ env: withoutMirrorCredentials(process.env),
253
256
  });
254
257
  return await new Promise((resolve, reject) => {
255
258
  child.on('error', reject);
@@ -366,6 +369,13 @@ export class TuiProcess {
366
369
  */
367
370
  _zmuxMirrorSocketListeners = [];
368
371
  _capabilities = new Set();
372
+ /** ZTC_MIRROR_PORT as the renderer was spawned with it, which every pane it starts inherits. */
373
+ rendererMirrorPort;
374
+ /**
375
+ * Each pane's own mirror credential, from the mirror the pane talks to, bound when the renderer reports the pane
376
+ * (see PaneCredentialBroker).
377
+ */
378
+ paneCredentials = new PaneCredentialBroker(() => this.rendererMirrorPort);
369
379
  /**
370
380
  * In-flight `read_clipboard_image` requests, keyed by request id. The
371
381
  * renderer answers asynchronously (it reads and PNG-encodes the clipboard
@@ -399,6 +409,14 @@ export class TuiProcess {
399
409
  this._zmuxMirrorSocketListeners.splice(idx, 1);
400
410
  };
401
411
  }
412
+ /**
413
+ * PORT is the mirror this transport's owner runs now, or undefined once it stops: a pane a pane opens through the
414
+ * relay is pointed at it and gets its credential there (PaneCredentialBroker.setOwnerMirrorPort). It can differ from
415
+ * the one the renderer was spawned with, after /mirror stop and a /mirror start on another port.
416
+ */
417
+ setOwnerMirrorPort(port) {
418
+ this.paneCredentials.setOwnerMirrorPort(port);
419
+ }
402
420
  /**
403
421
  * Subscribe to events from the Rust process
404
422
  */
@@ -412,6 +430,15 @@ export class TuiProcess {
412
430
  * Emit an event to all handlers
413
431
  */
414
432
  emit(event) {
433
+ if (event.type === 'pane_created') {
434
+ // The renderer reports a pane that carries a credential under the broker's own request id: its listeners hear of
435
+ // it under the one its sender chose (see PaneCredentialBroker).
436
+ const requestId = this.paneCredentials.created(event.pane_id, event.request_id);
437
+ if (requestId !== event.request_id)
438
+ event = { ...event, request_id: requestId };
439
+ }
440
+ else if (event.type === 'pane_closed')
441
+ this.paneCredentials.closed(event.pane_id);
415
442
  for (const handler of this.eventHandlers) {
416
443
  try {
417
444
  handler(event);
@@ -546,8 +573,12 @@ export class TuiProcess {
546
573
  const spawnArgs = ['--socket', this.socketPath];
547
574
  if (isHeadless && !this._desktopMode)
548
575
  spawnArgs.push('--headless');
549
- const childEnv = { ...process.env };
576
+ // The renderer starts every pane it opens with its own environment plus the pane's: it is spawned without this
577
+ // process's mirror credentials, so no pane can inherit them (each pane gets its own; see PaneCredentialBroker).
578
+ const childEnv = withoutMirrorCredentials(process.env);
550
579
  Object.assign(childEnv, options?.env ?? {});
580
+ // The renderer hands this port to every pane it starts, whatever this process's environment names later.
581
+ this.rendererMirrorPort = childEnv.ZTC_MIRROR_PORT || undefined;
551
582
  if (this._desktopMode && options?.desktopUpdateRelaunch) {
552
583
  childEnv.ZTERM_UPDATE_RELAUNCH = options.desktopUpdateRelaunch;
553
584
  }
@@ -826,7 +857,9 @@ export class TuiProcess {
826
857
  return false;
827
858
  }
828
859
  try {
829
- const json = serializeCommand(cmd);
860
+ // A pane the renderer opens, or starts again in place, gets its own mirror credential (PaneCredentialBroker).
861
+ const json = serializeCommand(cmd.type === 'create_pane' ? this.paneCredentials.prepare(cmd)
862
+ : cmd.type === 'replace_pane' ? this.paneCredentials.prepareReplace(cmd) : cmd);
830
863
  this.socket.write(json + '\n');
831
864
  return true;
832
865
  }
@@ -845,6 +878,8 @@ export class TuiProcess {
845
878
  */
846
879
  cleanup() {
847
880
  this.ready = false;
881
+ // The renderer is gone, and with it every pane it opened.
882
+ this.paneCredentials.revokeAll();
848
883
  // A torn-down socket can never deliver answers; release waiters.
849
884
  for (const pending of this.clipboardRequests.values()) {
850
885
  clearTimeout(pending.timer);
@@ -11,6 +11,7 @@ const USER_SUBPROCESS_STRIPPED_ZTC_ENV = [
11
11
  'ZTC_COLONY_WORKTREE_ID',
12
12
  'ZTC_MIRROR_PORT',
13
13
  'ZTC_MIRROR_INTERNAL_TOKEN',
14
+ 'ZTC_MIRROR_PANE_TOKEN',
14
15
  'ZTC_MIRROR_REQUIRE_AUTH',
15
16
  'ZTC_MIRROR_SHARED_SECRET',
16
17
  'ZTC_NAVIGATOR_GROUP',