@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
@@ -41,6 +41,7 @@ import { PaneRegistry } from './pane_registry.js';
41
41
  import { buildWorkspaceRuntimeSnapshot } from '../workspace_runtime.js';
42
42
  import { ChildPublicationLedger } from './child_publication.js';
43
43
  import { createMirrorAuthenticatorFromEnv, } from './mirror_authenticator.js';
44
+ import { PANE_CREDENTIAL_HEADER, adoptPaneCredentialStore } from './pane_credentials.js';
44
45
  import { areMirrorCorsRequestHeadersAllowed, getMirrorOriginPolicy, MIRROR_CORS_ALLOW_HEADERS, rejectReasonForUnsafeMirrorWrite, } from './mirror_origin_policy.js';
45
46
  import { getAccountsPayload, getAccountsPayloadWithCodexStatus, applyAccountOp, getActiveAccountsSummary } from './accounts_mirror.js';
46
47
  import { onAccountsChanged } from '../agent/backends/account_events.js';
@@ -61,7 +62,9 @@ const MAX_INTERNAL_TOOL_IMAGES = 4;
61
62
  const MIRROR_MEDIA_TTL_MS = 24 * 60 * 60 * 1000;
62
63
  /** The bus member a person in the browser mirror speaks as ("User"); panes and the coordinator are 0 and up. */
63
64
  export const BROWSER_BUS_MEMBER_ID = -1;
64
- const MIN_PANE_BUS_MEMBER_ID = 0;
65
+ /** The bus member of the ZTC that runs the mirror ("Overseer", or a sim's coordinator): the parent of every pane on it. */
66
+ export const OVERSEER_BUS_MEMBER_ID = 0;
67
+ const MIN_PANE_BUS_MEMBER_ID = OVERSEER_BUS_MEMBER_ID;
65
68
  const MAX_BUS_MEMBER_ID = 100_000;
66
69
  const MAX_BUS_QUEUE_TARGETS = 256;
67
70
  const MAX_BUS_QUEUE_MESSAGES_PER_TARGET = 100;
@@ -87,6 +90,17 @@ const OBSERVER_EVENT_TYPES = new Set([
87
90
  'queue_state', 'command_jobs', 'command_pane', 'hook_approval_request', 'widget_prompt', 'widget_select',
88
91
  'widget_questionnaire', 'widget_dismiss', 'context_progress_bar_config',
89
92
  ]);
93
+ /**
94
+ * The routes a pane's own credential reaches: its bus membership and its publications (each checked against the pane
95
+ * it stands for), and input, which arrives as relayed (see MirrorInputVia). A colony cell asks its overseer for its own
96
+ * restart (app/restart.ts). Everything else, the person's controls included, refuses a pane credential.
97
+ */
98
+ const PANE_CREDENTIAL_PATHS = ['/bus/connect', '/bus/send', '/pane-publication', '/pane-events'];
99
+ const PANE_CREDENTIAL_EXACT_PATHS = new Set(['/pane-store-event', '/input', '/submit', '/pane-input', '/colony/agents/restart']);
100
+ /** What a workspace monitor's credential also reaches: the runtime it shows and the decisions it answers. */
101
+ const WORKSPACE_MONITOR_PATHS = new Set(['/workspace/runtime', '/ask-user-answer']);
102
+ /** How long a request presenting a pane credential waits for its owner to hear the pane was created. */
103
+ const PANE_CREDENTIAL_SETTLE_MS = 10_000;
90
104
  const OBSERVER_GET_PATHS = new Set([
91
105
  '/', '/events', '/debug/config', '/mirror/pane-registry', '/mirror/layout',
92
106
  '/status', '/stats', '/output', '/health', '/favicon.svg', '/favicon.ico', '/mirror-favicon.svg',
@@ -130,6 +144,14 @@ const MIRROR_FALLBACK_STUB = '<!doctype html><html><head><title>ZTC Mirror</titl
130
144
  '<body><h1>ZTC Mirror runtime is running</h1>' +
131
145
  '<p>Install and build the browser client plugin to enable the full mirror UI.</p>' +
132
146
  '</body></html>';
147
+ /**
148
+ * End a long-lived response (an event stream), then the connection it came on, once the end is sent: the client makes
149
+ * its next request on a new connection, to whatever listens on the port by then, not on this one to a stopped mirror.
150
+ */
151
+ function endStream(res) {
152
+ const socket = res.socket;
153
+ res.end(() => { socket?.end(); });
154
+ }
133
155
  export class MirrorStreamServer {
134
156
  port;
135
157
  host;
@@ -307,7 +329,8 @@ export class MirrorStreamServer {
307
329
  this.browserBasePath = normalizeMirrorBasePath(process.env.ZTC_MIRROR_BASE_PATH);
308
330
  // The MirrorAuthenticator (Seam C) owns the enable policy, the HMAC token scheme,
309
331
  // the session store, and the secret/internal-token self-mint (writing process.env
310
- // so child panes inherit them).
332
+ // so the rest of this process shares them; no pane inherits them, see
333
+ // createMirrorAuthenticatorFromEnv).
311
334
  this.auth = createMirrorAuthenticatorFromEnv();
312
335
  this.auth.onShareRevoked(id => {
313
336
  for (const [clientId, client] of this.clients) {
@@ -744,17 +767,22 @@ export class MirrorStreamServer {
744
767
  }
745
768
  // Headless ZTC pane children read input from their own stdin — they have no
746
769
  // bus callback or SSE connection.
747
- // A ztc_message is an internal control command ({"__ztc_cmd":...}), NOT user
748
- // text: deliver it BARE via the control channel so the child classifies it as
749
- // a control command instead of replaying it to the LLM as a prompt.
750
- if (typeof targetId === 'number' && targetId !== 0 && msg.type === 'ztc_message' && this.paneControlCallback) {
770
+ // A ztc_message from the overseer (bus member 0, the ZTC that opened the pane)
771
+ // is an internal control command ({"__ztc_cmd":...}), NOT user text: deliver
772
+ // it BARE via the control channel so the child classifies it as a control
773
+ // command instead of replaying it to the LLM as a prompt. From any other member
774
+ // it is no control command, as a pane on the bus ignores one (cli_ratatui
775
+ // handleBusMessage): it falls through to the input channel below, as ordinary
776
+ // input, so it can't change the pane's model or answer its question.
777
+ if (typeof targetId === 'number' && targetId !== 0 && msg.type === 'ztc_message'
778
+ && msg.from.id === OVERSEER_BUS_MEMBER_ID && this.paneControlCallback) {
751
779
  if (process.env.ZTC_DEBUG)
752
780
  process.stderr.write(`${tag} delivered via pane-control callback (stdin, bare)\n`);
753
781
  this.paneControlCallback(targetId, msg.text);
754
782
  return;
755
783
  }
756
- // Everything else is user input — route to the pane-input callback, which
757
- // writes it to the child's stdin as a prompt envelope.
784
+ // Everything else is user input, or another member's message — route to the
785
+ // pane-input callback, which writes it to the child's stdin as a prompt envelope.
758
786
  if (typeof targetId === 'number' && targetId !== 0 && this.paneInputCallback) {
759
787
  if (process.env.ZTC_DEBUG)
760
788
  process.stderr.write(`${tag} delivered via pane-input callback (stdin)\n`);
@@ -950,6 +978,8 @@ export class MirrorStreamServer {
950
978
  this.port = addr.port;
951
979
  }
952
980
  }
981
+ // The credentials of the panes that talk to this port, the ones an earlier mirror on it gave out included.
982
+ this.auth.paneCredentials = adoptPaneCredentialStore(this.port);
953
983
  resolve();
954
984
  });
955
985
  };
@@ -960,6 +990,21 @@ export class MirrorStreamServer {
960
990
  // Detach the module-global accounts listener so it doesn't outlive the server.
961
991
  this.accountsUnsub?.();
962
992
  this.accountsUnsub = null;
993
+ // End each pane's bus stream and each browser's event stream, and the connection each came on, so every client
994
+ // connects again to whatever listens on the port next: a pane's mirror client rejoins the bus of the mirror ZTC
995
+ // starts again there (/mirror stop, then /mirror start), and a browser reconnects. Left open, they stayed with this
996
+ // stopped mirror, and what ZTC sends through the mirror it runs now never reached them.
997
+ for (const [memberId, res] of this.busConnections) {
998
+ this.busConnections.delete(memberId);
999
+ this.busMembers.delete(memberId);
1000
+ endStream(res);
1001
+ }
1002
+ for (const [id, client] of this.clients) {
1003
+ this.clients.delete(id);
1004
+ endStream(client.res);
1005
+ }
1006
+ // The pane credentials stay with the port, for the next mirror started on it (/mirror stop, then /mirror start):
1007
+ // each stops working when its pane closes or its renderer exits (see pane_credentials.ts).
963
1008
  await new Promise((resolve) => {
964
1009
  // Open SSE clients can hold close() open; give up after two seconds, and clear the timer
965
1010
  // when close() finishes first so it cannot hold the process open.
@@ -2409,7 +2454,7 @@ export class MirrorStreamServer {
2409
2454
  res.writeHead(401, { 'Content-Type': 'application/json' });
2410
2455
  res.end(JSON.stringify({ error: 'Mirror authentication required' }));
2411
2456
  }
2412
- return { ok: decision.ok, session: decision.session, source: decision.source };
2457
+ return { ok: decision.ok, session: decision.session, source: decision.source, ...(decision.pane ? { pane: decision.pane } : {}) };
2413
2458
  }
2414
2459
  requireInternalAuth(auth, res) {
2415
2460
  if (auth.source === 'internal')
@@ -2418,18 +2463,83 @@ export class MirrorStreamServer {
2418
2463
  res.end(JSON.stringify({ error: 'Internal mirror token required' }));
2419
2464
  return false;
2420
2465
  }
2421
- isInternalAuth(auth) {
2422
- return auth.source === 'internal';
2466
+ /**
2467
+ * May this caller act as pane PANE_ID: join the bus as it, publish as it? The process-wide token is ZTC's own and may
2468
+ * act for any pane; a pane's credential only for its own pane; nothing else for any.
2469
+ */
2470
+ requirePaneIdentity(auth, paneId, res) {
2471
+ if (auth.source === 'internal' || (auth.source === 'pane' && auth.pane?.paneId === paneId))
2472
+ return true;
2473
+ res.writeHead(403, { 'Content-Type': 'application/json' });
2474
+ res.end(JSON.stringify({ error: auth.source === 'pane'
2475
+ ? 'A pane credential acts only as its own pane.' : 'Internal mirror token required' }));
2476
+ return false;
2477
+ }
2478
+ /** The process-wide token, or a workspace monitor's own credential (the runtime and decisions it shows). */
2479
+ requireWorkspaceMonitor(auth, res) {
2480
+ if (auth.source === 'pane' && auth.pane?.scope === 'workspace-monitor')
2481
+ return true;
2482
+ return this.requireInternalAuth(auth, res);
2483
+ }
2484
+ /**
2485
+ * Is this caller the person? A browser session is, and in open mode so is a request with no credential. The
2486
+ * process-wide token is ZTC's own, never the person's, except in a hosted runtime: there the host's same-origin proxy
2487
+ * (zapps/zergrouter server/lib/ztc-mirror-proxy.ts) forwards the signed-in owner's own browser requests with it, the
2488
+ * only mirror credential it lets through, and no pane runs to hold it.
2489
+ */
2490
+ speaksForPerson(auth) {
2491
+ return auth.source === 'browser' || auth.source === 'open' || (auth.source === 'internal' && this.hostedMode);
2492
+ }
2493
+ /**
2494
+ * Who a caller is on the bus, from how it authenticated, never from what it writes: the person (speaksForPerson) is
2495
+ * the browser member; a pane's credential is that pane; the process-wide token is ZTC's own and may speak as any pane
2496
+ * or the overseer, and as the person only in a hosted runtime.
2497
+ */
2498
+ mayClaimBusMember(auth, memberId) {
2499
+ switch (auth.source) {
2500
+ case 'browser':
2501
+ case 'open':
2502
+ return memberId === BROWSER_BUS_MEMBER_ID;
2503
+ case 'pane':
2504
+ return memberId === auth.pane?.paneId;
2505
+ case 'internal':
2506
+ return memberId !== BROWSER_BUS_MEMBER_ID || this.speaksForPerson(auth);
2507
+ case null:
2508
+ return false;
2509
+ }
2510
+ }
2511
+ /** Where input this caller posts to /input, /submit or /pane-input came from (see MirrorInputVia). */
2512
+ inputVia(auth) {
2513
+ return this.speaksForPerson(auth) ? 'browser' : 'relayed';
2514
+ }
2515
+ /** The bus member that input this caller posts for another pane speaks as: the person only for the person. */
2516
+ inputSender(auth) {
2517
+ if (auth.source === 'pane' && auth.pane) {
2518
+ const id = auth.pane.paneId;
2519
+ return { id, name: this.busMembers.get(id) ?? this.panes.get(id)?.title ?? `ZTC ${id}` };
2520
+ }
2521
+ if (!this.speaksForPerson(auth))
2522
+ return { id: OVERSEER_BUS_MEMBER_ID, name: 'Overseer' };
2523
+ return { id: BROWSER_BUS_MEMBER_ID, name: 'User' };
2524
+ }
2525
+ /** May a pane's own credential use this route? (See PANE_CREDENTIAL_PATHS.) */
2526
+ paneCredentialReaches(pane, pathname) {
2527
+ if (PANE_CREDENTIAL_EXACT_PATHS.has(pathname))
2528
+ return true;
2529
+ if (PANE_CREDENTIAL_PATHS.some(path => pathname === path || pathname.startsWith(`${path}/`)))
2530
+ return true;
2531
+ return pane.scope === 'workspace-monitor' && WORKSPACE_MONITOR_PATHS.has(pathname);
2423
2532
  }
2424
2533
  /**
2425
2534
  * May this principal mutate the account pool (POST /mirror/account)? Those ops
2426
2535
  * have real host side effects — `login` spawns an OAuth flow on the ztc host;
2427
2536
  * use/add/remove rewrite the pool — so they are operator-only, on the
2428
2537
  * same bar as /debug/prompts. Open mode = the trusted local operator on their
2429
- * own loopback mirror; internal = a process-internal caller (child pane). A
2538
+ * own loopback mirror; internal = ZTC's own process-internal caller. A
2430
2539
  * browser session is the operator only when it carries the superuser scope
2431
- * (canInspectPrompts); a shared, non-superuser viewer is refused. Reached only
2432
- * past the !auth.ok guard, so `null` is unreachable — enumerated for clarity.
2540
+ * (canInspectPrompts); a shared, non-superuser viewer is refused, and so is a
2541
+ * pane's credential (which never reaches this route). Reached only past the
2542
+ * !auth.ok guard, so `null` is unreachable — enumerated for clarity.
2433
2543
  */
2434
2544
  canMutateAccounts(auth) {
2435
2545
  if (this.hostedMode)
@@ -2440,6 +2550,7 @@ export class MirrorStreamServer {
2440
2550
  return true;
2441
2551
  case 'browser':
2442
2552
  return auth.session?.canInspectPrompts === true;
2553
+ case 'pane':
2443
2554
  case null:
2444
2555
  return false;
2445
2556
  }
@@ -2850,9 +2961,20 @@ export class MirrorStreamServer {
2850
2961
  await this.handleCvSnapshot(req, res);
2851
2962
  return;
2852
2963
  }
2964
+ // A pane's program can start before its owner hears the renderer created the pane: wait (briefly) for the
2965
+ // credential it presents to be bound to that pane, rather than refuse its first request.
2966
+ const presentedPaneCredential = req.headers[PANE_CREDENTIAL_HEADER];
2967
+ if (typeof presentedPaneCredential === 'string' && presentedPaneCredential) {
2968
+ await this.auth.paneCredentials.settled(presentedPaneCredential.trim(), PANE_CREDENTIAL_SETTLE_MS);
2969
+ }
2853
2970
  const auth = this.authenticateRequest(req, url, res);
2854
2971
  if (!auth.ok)
2855
2972
  return;
2973
+ if (auth.source === 'pane' && !this.paneCredentialReaches(auth.pane, url.pathname)) {
2974
+ res.writeHead(403, { 'Content-Type': 'application/json' });
2975
+ res.end(JSON.stringify({ error: 'A pane credential cannot use this endpoint.' }));
2976
+ return;
2977
+ }
2856
2978
  const readOnly = auth.session?.canControl === false;
2857
2979
  if (readOnly && (req.method !== 'GET' || !(OBSERVER_GET_PATHS.has(url.pathname) || url.pathname.startsWith('/js/') || url.pathname.startsWith('/media/')))) {
2858
2980
  res.writeHead(403, { 'Content-Type': 'application/json' });
@@ -2947,7 +3069,7 @@ export class MirrorStreamServer {
2947
3069
  return;
2948
3070
  }
2949
3071
  if (url.pathname === '/workspace/runtime') {
2950
- if (!this.requireInternalAuth(auth, res))
3072
+ if (!this.requireWorkspaceMonitor(auth, res))
2951
3073
  return;
2952
3074
  if (req.headers['x-ztc-workspace-owner'] !== this.workspaceOwnerId) {
2953
3075
  res.writeHead(409, { 'Content-Type': 'application/json' });
@@ -3419,13 +3541,14 @@ export class MirrorStreamServer {
3419
3541
  res.end(JSON.stringify({ callbacks, connections, members, queued }));
3420
3542
  return;
3421
3543
  }
3422
- // Handle input from browser (single-pane or parent pane)
3544
+ // Handle input for the overseer (single-pane or parent pane): the browser's, or relayed by a ZTC process or pane
3423
3545
  if ((url.pathname === '/input' || url.pathname === '/submit') && req.method === 'POST') {
3424
3546
  try {
3425
3547
  const input = await this.readMessageInput(req);
3426
3548
  if ((isMeaningfulUserInput(input.text) || input.attachments.length > 0) && this.inputCallback) {
3427
3549
  await this.maybeCreateColonyCheckpoint(input.text, 0);
3428
- this.inputCallback(input, 'browser');
3550
+ // The person's only from the browser; from a ZTC process or a pane, relayed (see MirrorInputVia).
3551
+ this.inputCallback(input, this.inputVia(auth));
3429
3552
  }
3430
3553
  res.writeHead(200, { 'Content-Type': 'application/json' });
3431
3554
  res.end(JSON.stringify({ ok: true, attachments: input.attachments }));
@@ -3836,7 +3959,7 @@ export class MirrorStreamServer {
3836
3959
  // browser callers retain their pane/question identity contract.
3837
3960
  const workspaceOwner = req.headers['x-ztc-workspace-owner'];
3838
3961
  if (workspaceOwner !== undefined) {
3839
- if (!this.requireInternalAuth(auth, res))
3962
+ if (!this.requireWorkspaceMonitor(auth, res))
3840
3963
  return;
3841
3964
  if (workspaceOwner !== this.workspaceOwnerId) {
3842
3965
  res.writeHead(409, { 'Content-Type': 'application/json' });
@@ -3933,7 +4056,7 @@ export class MirrorStreamServer {
3933
4056
  // Open a fresh parent-issued publication identity. Reopening supersedes old packets;
3934
4057
  // clients never retry uncertain effects and do not carry an identity across reconnects.
3935
4058
  if (url.pathname.startsWith('/pane-publication') && req.method === 'POST') {
3936
- if (!this.requireInternalAuth(auth, res))
4059
+ if (auth.source !== 'pane' && !this.requireInternalAuth(auth, res))
3937
4060
  return;
3938
4061
  try {
3939
4062
  const parsed = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
@@ -3944,6 +4067,8 @@ export class MirrorStreamServer {
3944
4067
  res.end(JSON.stringify({ error: 'invalid_publication_pane' }));
3945
4068
  return;
3946
4069
  }
4070
+ if (!this.requirePaneIdentity(auth, paneId, res))
4071
+ return;
3947
4072
  const publicationId = this.childPublications.open(paneId, scope);
3948
4073
  res.writeHead(publicationId ? 200 : 503, { 'Content-Type': 'application/json' });
3949
4074
  res.end(JSON.stringify(publicationId ? { ok: true, publication_id: publicationId }
@@ -3956,10 +4081,12 @@ export class MirrorStreamServer {
3956
4081
  }
3957
4082
  // Handle events from child panes (multi-pane mode)
3958
4083
  if (url.pathname.startsWith('/pane-events') && req.method === 'POST') {
3959
- if (!this.requireInternalAuth(auth, res))
4084
+ if (auth.source !== 'pane' && !this.requireInternalAuth(auth, res))
3960
4085
  return;
3961
4086
  try {
3962
4087
  const parsed = await this.readJsonBody(req, req.headers['x-ztc-tool-image'] === '1' ? MAX_TOOL_IMAGE_BODY_BYTES : MAX_MIRROR_EVENT_BODY_BYTES);
4088
+ if (auth.source === 'pane' && !this.requirePaneIdentity(auth, Number(parsed?.pane_id), res))
4089
+ return;
3963
4090
  if (!this.admitChildPublication(parsed, res, url.pathname.slice('/pane-events'.length)))
3964
4091
  return;
3965
4092
  // Inject pane_id into event data and broadcast to SSE clients
@@ -4034,10 +4161,12 @@ export class MirrorStreamServer {
4034
4161
  }
4035
4162
  // Store-only endpoint for child panes (finalized messages for history replay)
4036
4163
  if (url.pathname === '/pane-store-event' && req.method === 'POST') {
4037
- if (!this.requireInternalAuth(auth, res))
4164
+ if (auth.source !== 'pane' && !this.requireInternalAuth(auth, res))
4038
4165
  return;
4039
4166
  try {
4040
4167
  const parsed = await this.readJsonBody(req, MAX_MIRROR_EVENT_BODY_BYTES);
4168
+ if (auth.source === 'pane' && !this.requirePaneIdentity(auth, Number(parsed?.pane_id), res))
4169
+ return;
4041
4170
  if (!this.admitChildPublication(parsed, res, ''))
4042
4171
  return;
4043
4172
  const event = parsed.event;
@@ -4055,9 +4184,9 @@ export class MirrorStreamServer {
4055
4184
  return;
4056
4185
  }
4057
4186
  // --- Bus endpoints ---
4058
- // SSE connection for child ZTC bus members
4187
+ // SSE connection for child ZTC bus members: a pane joins only as itself (see requirePaneIdentity)
4059
4188
  if (url.pathname.startsWith('/bus/connect') && req.method === 'GET') {
4060
- if (!this.requireInternalAuth(auth, res))
4189
+ if (auth.source !== 'pane' && !this.requireInternalAuth(auth, res))
4061
4190
  return;
4062
4191
  const memberId = this.parseBusId(url.searchParams.get('id'));
4063
4192
  if (memberId === null || !this.isSafeBusId(memberId, false)) {
@@ -4065,6 +4194,8 @@ export class MirrorStreamServer {
4065
4194
  res.end(JSON.stringify({ error: 'Invalid bus member' }));
4066
4195
  return;
4067
4196
  }
4197
+ if (!this.requirePaneIdentity(auth, memberId, res))
4198
+ return;
4068
4199
  const memberName = url.searchParams.get('name') || `ZTC ${memberId}`;
4069
4200
  res.writeHead(200, {
4070
4201
  'Content-Type': 'text/event-stream',
@@ -4107,9 +4238,11 @@ export class MirrorStreamServer {
4107
4238
  res.end(JSON.stringify({ error: 'Invalid bus message' }));
4108
4239
  return;
4109
4240
  }
4110
- if (from.id !== BROWSER_BUS_MEMBER_ID && !this.isInternalAuth(auth)) {
4241
+ // The sender is who the caller authenticated as, not who the body says: refused, nothing is delivered.
4242
+ if (!this.mayClaimBusMember(auth, from.id)) {
4111
4243
  res.writeHead(403, { 'Content-Type': 'application/json' });
4112
- res.end(JSON.stringify({ error: 'Internal mirror token required' }));
4244
+ res.end(JSON.stringify({ error: auth.source === 'browser' || auth.source === 'open'
4245
+ ? 'Internal mirror token required' : 'This credential cannot send as that bus member.' }));
4113
4246
  return;
4114
4247
  }
4115
4248
  const msg = {
@@ -4128,7 +4261,8 @@ export class MirrorStreamServer {
4128
4261
  }
4129
4262
  return;
4130
4263
  }
4131
- // Handle pane-specific input from browser (multi-pane mode)
4264
+ // Handle pane-specific input from browser (multi-pane mode), or relayed by a ZTC process or pane, which reaches the
4265
+ // overseer as relayed and another pane as a message from the caller's own bus member (see inputVia, inputSender).
4132
4266
  // Legacy endpoint — now routes through the bus for child panes
4133
4267
  if (url.pathname === '/pane-input' && req.method === 'POST') {
4134
4268
  try {
@@ -4137,11 +4271,12 @@ export class MirrorStreamServer {
4137
4271
  const cleanText = input.text.replace(/\n$/, '');
4138
4272
  const bodyPaneId = Number(input.pane_id);
4139
4273
  const hasContent = isMeaningfulUserInput(cleanText) || input.attachments.length > 0;
4274
+ const sender = this.inputSender(auth);
4140
4275
  if (bodyPaneId === 0) {
4141
4276
  // Route to parent's input callback (Overseer / pane 0)
4142
4277
  if (hasContent && this.inputCallback) {
4143
4278
  await this.maybeCreateColonyCheckpoint(cleanText, 0);
4144
- this.inputCallback({ text: cleanText, attachments: input.attachments }, 'browser');
4279
+ this.inputCallback({ text: cleanText, attachments: input.attachments }, this.inputVia(auth));
4145
4280
  res.writeHead(200, { 'Content-Type': 'application/json' });
4146
4281
  res.end(JSON.stringify({ ok: true, routed: 'parent', attachments: input.attachments }));
4147
4282
  }
@@ -4160,7 +4295,7 @@ export class MirrorStreamServer {
4160
4295
  await this.maybeCreateColonyCheckpoint(cleanText, targetId);
4161
4296
  const msg = {
4162
4297
  id: randomUUID(),
4163
- from: { id: -1, name: 'User' },
4298
+ from: sender,
4164
4299
  to: targetId,
4165
4300
  type: 'user_input',
4166
4301
  text: cleanText,
@@ -4181,7 +4316,7 @@ export class MirrorStreamServer {
4181
4316
  await this.maybeCreateColonyCheckpoint(cleanText, targetId);
4182
4317
  const msg = {
4183
4318
  id: randomUUID(),
4184
- from: { id: -1, name: 'User' },
4319
+ from: sender,
4185
4320
  to: targetId,
4186
4321
  type: 'user_input',
4187
4322
  text: cleanText,
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Per-pane mirror credentials.
3
+ *
4
+ * The mirror's process-wide internal token speaks for every pane at once, and for ZTC itself, so ZTC never gives it to
5
+ * a pane: a pane's programs (Claude Code's and Codex's tools among them) can read their own environment. Each pane
6
+ * ZTC launches that talks to the mirror gets a credential of its own instead: a random token minted when the pane is
7
+ * requested, which authenticates as nothing until it is bound to the pane id the renderer assigns, then only as that
8
+ * pane, and stops working once the pane closes. It comes back in a header (PANE_CREDENTIAL_HEADER), never on a command
9
+ * line or in a log.
10
+ *
11
+ * Any program running as this user can read the environment another of this user's processes started with (`ps -E`,
12
+ * /proc/PID/environ), so a ZTC pane and a workspace monitor, whose credential also answers the questions waiting in any
13
+ * pane, are handed theirs in a one-time owner-only file that only the file's path on their command line names
14
+ * (PANE_CREDENTIAL_FILE_FLAG). The program takes it and deletes the file as it starts, and keeps it in memory, never in
15
+ * its environment, which every program it starts would inherit (consumePaneCredentialHandoff). Only a program that
16
+ * reads the file before the pane's program has taken it could take the credential as well. A Claude Code or Codex pane
17
+ * gets its credential in its environment (PANE_CREDENTIAL_ENV), since its CLI starts the pane's workspace tools with
18
+ * that environment; another program running as this user can read it there and act as that pane.
19
+ *
20
+ * A store belongs to a port, not to one mirror server: the first mirror in this process to listen on a port makes its
21
+ * store, and every later mirror on that port takes the same one (adoptPaneCredentialStore). So the panes' credentials
22
+ * outlive a restart of their mirror (/mirror stop, then /mirror start), as the process-wide token does, and each stops
23
+ * working when its pane closes or its renderer exits. The pane transport that creates a pane mints from the store of
24
+ * the port the pane will talk to (paneCredentialStoreForPort), and binds the credential when the pane appears.
25
+ *
26
+ * Self-contained (node builtins only), so the mirror, the pane transports and the CLI entry can all depend on it.
27
+ */
28
+ /** The pane's own mirror credential, in the environment of a pane whose launcher asked for it there (see above). */
29
+ export declare const PANE_CREDENTIAL_ENV = "ZTC_MIRROR_PANE_TOKEN";
30
+ /** The header a pane's programs present it in. */
31
+ export declare const PANE_CREDENTIAL_HEADER = "x-ztc-pane-token";
32
+ /**
33
+ * The mirror credentials a ZTC process may hold that nothing it spawns inherits: its mirror's process-wide token and
34
+ * shared secret, and its own pane credential when it is itself a pane. A renderer is spawned without them, and a pane
35
+ * transport clears them in every pane it creates before giving the pane a credential of its own.
36
+ */
37
+ export declare const OWNER_MIRROR_CREDENTIAL_ENV: readonly string[];
38
+ /** ENV without the owner's mirror credentials (see OWNER_MIRROR_CREDENTIAL_ENV). */
39
+ export declare function withoutMirrorCredentials(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
40
+ /**
41
+ * What a credential lets its pane do besides act as itself: 'workspace-monitor' also reads the workspace runtime and
42
+ * answers its decisions, for the monitors a layout opens.
43
+ */
44
+ export type PaneCredentialScope = 'pane' | 'workspace-monitor';
45
+ /**
46
+ * The values a launcher puts under PANE_CREDENTIAL_ENV in a create_pane env to ask for a credential. The pane
47
+ * transport always replaces the value: with a plain credential, or with '' when it hands a workspace monitor's in a
48
+ * one-time file (PANE_CREDENTIAL_FILE_FLAG) or no mirror in this process has listened on the pane's port. A ZTC pane is
49
+ * given a credential in such a file without asking.
50
+ */
51
+ export declare const PANE_CREDENTIAL_REQUEST = "request";
52
+ export declare const WORKSPACE_MONITOR_CREDENTIAL_REQUEST = "request:workspace-monitor";
53
+ /** Who a bound credential authenticates as. */
54
+ export interface PanePrincipal {
55
+ readonly paneId: number;
56
+ readonly scope: PaneCredentialScope;
57
+ }
58
+ export interface PaneCredential {
59
+ readonly token: string;
60
+ readonly scope: PaneCredentialScope;
61
+ /** Bind to the pane the renderer created; from then on the credential authenticates as that pane. */
62
+ bind(paneId: number): void;
63
+ /** The pane closed, was relaunched, or never opened: the credential stops working. */
64
+ revoke(): void;
65
+ }
66
+ /** The pane credentials of one port's mirror. Kept by digest, so no lookup compares the token itself. */
67
+ export declare class PaneCredentialStore {
68
+ private readonly entries;
69
+ /**
70
+ * Mint a credential for a pane about to be created. It authenticates as nothing until bound, and is dropped if it
71
+ * isn't bound within PENDING_TTL_MS. With `paneId`, a renderer that assigns ids before it spawns binds it at once.
72
+ */
73
+ issue(scope?: PaneCredentialScope, paneId?: number): PaneCredential;
74
+ /** The pane a presented credential stands for; 'pending' while it waits for its pane; null for anything else. */
75
+ resolve(token: string): PanePrincipal | 'pending' | null;
76
+ /**
77
+ * Resolves once a presented credential no longer waits for its pane (bound, revoked or expired), or after
78
+ * `timeoutMs`. A pane's program can start before its owner hears the renderer created the pane; its first request
79
+ * waits here instead of being refused.
80
+ */
81
+ settled(token: string, timeoutMs: number): Promise<void>;
82
+ private drop;
83
+ private wake;
84
+ private sweep;
85
+ }
86
+ /**
87
+ * The store a mirror that starts listening on PORT honours: the one an earlier mirror on the port left, so the panes
88
+ * that talked to it rejoin this one, or a new one.
89
+ */
90
+ export declare function adoptPaneCredentialStore(port: number): PaneCredentialStore;
91
+ /**
92
+ * The store for `port`, once a mirror in this process has listened on it: a pane created to talk to that port gets its
93
+ * credential there, also between a /mirror stop and a /mirror start, which a mirror listening on the port again takes.
94
+ * Null for a port no mirror here has listened on.
95
+ */
96
+ export declare function paneCredentialStoreForPort(port: number): PaneCredentialStore | null;
97
+ /**
98
+ * The flag on a pane program's command line that names its pane credential handoff: for a ZTC pane and a workspace
99
+ * monitor, opened or started again in place of a pane (replace_pane: /layout resume, the Resume button on a saved agent
100
+ * pane), and for the ZTC a ZTC pane execs in its own place (paneCredentialRelaunchArgs). The handoff is a fresh
101
+ * owner-only directory in the temp directory holding the credential alone; the program takes the credential and
102
+ * deletes the directory as it starts (consumePaneCredentialHandoff).
103
+ */
104
+ export declare const PANE_CREDENTIAL_FILE_FLAG = "--pane-credential-file";
105
+ /** Write TOKEN to a one-time handoff for a pane to take (see PANE_CREDENTIAL_FILE_FLAG); returns the file's path. */
106
+ export declare function writePaneCredentialHandoff(token: string): string;
107
+ /** Remove a handoff no pane took: its pane never started, or closed first. */
108
+ export declare function removePaneCredentialHandoff(path: string): void;
109
+ /**
110
+ * Take the pane credential a handoff on ARGV names (PANE_CREDENTIAL_FILE_FLAG): drop the flag and its path from ARGV,
111
+ * so nothing that relaunches this process or launches a pane from its arguments passes them on; keep the credential as
112
+ * this process's own, which it presents to its mirror (paneMirrorCredentialHeaders); and delete the handoff. The
113
+ * credential is never put in this process's environment, which every program it starts would inherit and any program
114
+ * running as this user can read. A handoff that is gone, or that this user alone could not have written, gives no
115
+ * credential. Only ARGV's options name a handoff: what follows an end of options ('--') is a ZTC pane's task, literal
116
+ * text whatever it says, and stays as it is. Returns whether a credential was taken.
117
+ */
118
+ export declare function consumePaneCredentialHandoff(argv?: string[]): boolean;
119
+ /**
120
+ * The header a pane's program presents to its mirror: the pane's own credential, the one this process took from its
121
+ * handoff or else the one ENV holds (a Claude Code or Codex pane's workspace tools), or, under a ZTC from before
122
+ * per-pane credentials, the process-wide token that ZTC handed its panes. Empty when there is none of them.
123
+ */
124
+ export declare function paneMirrorCredentialHeaders(env?: NodeJS.ProcessEnv): Record<string, string>;
125
+ /**
126
+ * The arguments that hand this process's pane credential to the ZTC it execs in its own place (a hot restart, or a
127
+ * session resumed from the panel), which is the same pane: a fresh one-time handoff, since the credential is not in
128
+ * the environment the replacement starts with. Empty when this process took none, or the handoff can't be written
129
+ * (the replacement then starts without one, as a pane restarted in place does).
130
+ */
131
+ export declare function paneCredentialRelaunchArgs(): string[];