@zergai/ztc 0.17.1-dev.202611092212 → 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 (55) 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-computer-darwin-arm64 +0 -0
  6. package/bin/ztc-llm-darwin-arm64 +0 -0
  7. package/bin/ztc-tts-darwin-arm64 +0 -0
  8. package/bin/ztc-tui-darwin-arm64 +0 -0
  9. package/bin/zterm-darwin-arm64 +1 -1
  10. package/dist/App.js +21 -7
  11. package/dist/agent/backends/router_gate.js +3 -2
  12. package/dist/agent/backends/router_refusal_record.d.ts +12 -2
  13. package/dist/agent/backends/router_refusal_record.js +19 -4
  14. package/dist/agent/tools/pane.d.ts +6 -1
  15. package/dist/agent/tools/pane.js +6 -4
  16. package/dist/app/mirror_startup.d.ts +7 -0
  17. package/dist/app/mirror_startup.js +10 -0
  18. package/dist/app/restart.d.ts +6 -0
  19. package/dist/app/restart.js +13 -3
  20. package/dist/app/workspace_monitor.js +17 -3
  21. package/dist/app/workspace_presets.js +8 -1
  22. package/dist/cli_main.js +5 -0
  23. package/dist/cli_ratatui.d.ts +87 -18
  24. package/dist/cli_ratatui.js +234 -129
  25. package/dist/embedded/anempa_runtime.js +3 -0
  26. package/dist/embedded/gameboy_runtime.js +4 -2
  27. package/dist/embedded/zergpod_runtime.js +4 -2
  28. package/dist/environment/store.js +4 -1
  29. package/dist/mcp/client.js +6 -2
  30. package/dist/mcp/workspace_server.d.ts +7 -3
  31. package/dist/mcp/workspace_server.js +15 -8
  32. package/dist/panes/agent_cli.d.ts +10 -3
  33. package/dist/panes/agent_cli.js +16 -4
  34. package/dist/runtime_info.js +10 -1
  35. package/dist/simulation/engines/swarm/pane_manager.d.ts +16 -3
  36. package/dist/simulation/engines/swarm/pane_manager.js +39 -17
  37. package/dist/types.d.ts +5 -2
  38. package/dist/ui/ratatui/headless_pane_manager.d.ts +13 -1
  39. package/dist/ui/ratatui/headless_pane_manager.js +37 -8
  40. package/dist/ui/ratatui/pane_credential_broker.d.ts +107 -0
  41. package/dist/ui/ratatui/pane_credential_broker.js +239 -0
  42. package/dist/ui/ratatui/pane_relay.js +4 -2
  43. package/dist/ui/ratatui/process.d.ts +13 -0
  44. package/dist/ui/ratatui/process.js +38 -3
  45. package/dist/utils/subprocess_env.js +1 -0
  46. package/dist/web/mirror_authenticator.d.ts +27 -11
  47. package/dist/web/mirror_authenticator.js +36 -12
  48. package/dist/web/mirror_client.d.ts +2 -1
  49. package/dist/web/mirror_client.js +7 -5
  50. package/dist/web/mirror_stream.d.ts +39 -8
  51. package/dist/web/mirror_stream.js +164 -29
  52. package/dist/web/pane_credentials.d.ts +131 -0
  53. package/dist/web/pane_credentials.js +302 -0
  54. package/dist/zlm-embed.mjs +2 -1
  55. package/package.json +16 -7
package/README.md CHANGED
@@ -110,7 +110,8 @@ the whole ZTC process, so subagents, workers, heartbeats, `/loop` routines, goal
110
110
  messages from other panes get the same message without contacting Router. One real request
111
111
  every five minutes still goes through, so a raised limit works within minutes, and a
112
112
  successful answer for that model lifts the hold. A message you send yourself (typed,
113
- dictated, from the browser mirror, or given on the command line) gets one real attempt.
113
+ dictated, from the browser mirror, or given on the command line) gets one real attempt,
114
+ unless you type it into a ZTC pane or a colony cell, which the overseer can type into too.
114
115
  A full concurrency limit is retried a few times, and a provider cooldown is waited out;
115
116
  one longer than a minute ends the turn with the time it clears, and nothing, not even
116
117
  your own message, is sent to that model before then.
@@ -123,7 +124,7 @@ on such a refusal, with Router's words on stderr; 2 is a usage error and 3 an
123
124
  request, so a shell or cron loop that starts ZTC again is refused locally for five minutes
124
125
  at a time instead of calling Router. A refusal Router gives no reset for is kept 15
125
126
  minutes after it was last met. An interactive launch shows what was recorded and lets you
126
- try.
127
+ try; a ZTC pane or a colony cell says where you still can.
127
128
 
128
129
  Signed in with Zerg Router, `/usage` shows your limits and usage, your monthly token
129
130
  quota and recent refusals, read from zergrouter.com with your own sign-in, and the status
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/zterm-darwin-arm64
3
3
  size: 33730352 bytes
4
- sha256: 9178b918bcb7c1dc3cb4e4a2d616fbe73a743d9860b2be2d4910fdbe08fa0ca7
4
+ sha256: 598ea3aa4997631a8e4df6deabd3cd3e32c3a4bcad0dd6e3b6f160c3dc2a4299
package/dist/App.js CHANGED
@@ -163,6 +163,16 @@ function createAgent(mode, skillPrompt, workspace) {
163
163
  ...workspace,
164
164
  });
165
165
  }
166
+ /**
167
+ * Whether input the person typed (`person`) takes their one real attempt past a Zerg Router refusal. Everything Ink
168
+ * takes is typed on its terminal, which in a ZTC another ZTC launched into one of its panes is a PTY the overseer's
169
+ * write_terminal_pane types into too, so nothing typed there does, as nothing typed there makes a choice only the
170
+ * person makes (see appContext's commandOrigin). A queued entry keeps who queued it (QueueEntry.person) and is asked
171
+ * here when it runs.
172
+ */
173
+ function takesRouterAttempt(person) {
174
+ return person && !launchedByAnotherZtc();
175
+ }
166
176
  // --- Main App ---
167
177
  export const App = () => {
168
178
  const renderCount = React.useRef(0);
@@ -285,14 +295,16 @@ export const App = () => {
285
295
  React.useEffect(() => {
286
296
  let active = true;
287
297
  let runtimeTimer;
288
- // A refusal an unattended run recorded holds this session's background work; the person's messages still try.
298
+ // A refusal an unattended run recorded holds this session's background work. The person's messages still try,
299
+ // except in a ZTC pane, where all that is typed is relayed (see takesRouterAttempt); the notice says which.
289
300
  const recordedRefusals = adoptRouterRefusalRecord('interactive');
301
+ const attempts = takesRouterAttempt(true) ? 'all' : 'none';
290
302
  // Shown after the launch readout settles: a second message would keep the readout from refreshing.
291
303
  const showRecordedRefusals = () => {
292
304
  if (!active || recordedRefusals.length === 0)
293
305
  return;
294
306
  setMessages(prev => [...prev, ...recordedRefusals.map(hold => ({ id: generateId(), role: 'system',
295
- content: formatRecordedRouterRefusal(hold), timestamp: new Date() }))]);
307
+ content: formatRecordedRouterRefusal(hold, attempts), timestamp: new Date() }))]);
296
308
  };
297
309
  const refreshUntouchedWelcome = (runtime) => {
298
310
  if (!active)
@@ -1402,8 +1414,10 @@ export const App = () => {
1402
1414
  queuePausedRef.current = false;
1403
1415
  abortControllerRef.current = retryController;
1404
1416
  await workspaceCoordinator.setActivity('running');
1405
- // The person asked for the request again: it gets one real attempt past a Zerg Router refusal, like a new message.
1406
- last.agent.admitPersonRequest();
1417
+ // The person asked for the request again: like a message they type, it gets one real attempt past a Zerg Router
1418
+ // refusal, except in a ZTC pane (see takesRouterAttempt).
1419
+ if (takesRouterAttempt(true))
1420
+ last.agent.admitPersonRequest();
1407
1421
  try {
1408
1422
  await runWithRetry(last.messages, last.agent, true, isActive, retryController.signal);
1409
1423
  }
@@ -2037,8 +2051,8 @@ export const App = () => {
2037
2051
  }
2038
2052
  });
2039
2053
  // A message the person typed gets one real attempt even while Zerg Router's refusal holds the route, sent at once
2040
- // or from the queue.
2041
- if (person)
2054
+ // or from the queue, except in a ZTC pane (see takesRouterAttempt).
2055
+ if (takesRouterAttempt(person))
2042
2056
  currentAgent.admitPersonRequest();
2043
2057
  try {
2044
2058
  await runWithRetry(requestMessages, currentAgent, false, isActive, controller.signal, () => {
@@ -2048,7 +2062,7 @@ export const App = () => {
2048
2062
  queueRef.current = queueRef.current.filter(entry => entry.delivery !== 'subturn');
2049
2063
  setQueue(queueRef.current);
2050
2064
  // The person's steering makes the request that carries it theirs, as their own message would.
2051
- if (pending.some(entry => entry.person === true))
2065
+ if (pending.some(entry => takesRouterAttempt(entry.person === true)))
2052
2066
  currentAgent.admitPersonRequest();
2053
2067
  // These messages become visible through the real history checkpoint
2054
2068
  // when the Agent admits them after the completed tool result.
@@ -8,8 +8,9 @@
8
8
  * changes (another model, account or route is another key). At most one real attempt every five minutes goes
9
9
  * through, so a raised limit takes effect within minutes, and a success for that route, account, provider and model
10
10
  * clears its hold. The person's own new message always gets one real attempt, since they may have just raised the
11
- * limit. A provider cooldown that ended a turn is the exception: nothing the person can change shortens it, so no
12
- * request, theirs included, is tried before it clears.
11
+ * limit, though what they type into a ZTC pane's or a colony cell's terminal, which the overseer types into too, is
12
+ * relayed and gets none (see the TUI's takesRouterAttempt). A provider cooldown that ended a turn is the exception:
13
+ * nothing the person can change shortens it, so no request, theirs included, is tried before it clears.
13
14
  *
14
15
  * The hold is keyed by the route (the Router or platform proxy URL), the account (a one-way fingerprint of the
15
16
  * credential, never the credential), the provider and the model. Keying every refusal by account, not only the credit
@@ -15,8 +15,18 @@ export declare function readRouterRefusalRecord(path?: string, now?: number): Ro
15
15
  * recorded, for a launch to show.
16
16
  */
17
17
  export declare function adoptRouterRefusalRecord(mode: 'unattended' | 'interactive', path?: string): RouterHold[];
18
+ /**
19
+ * Which of the person's messages get their one real attempt past a refusal in an interactive launch (see the TUI's
20
+ * takesRouterAttempt): 'all' in ZTC's main session; 'mirror' in a colony cell, whose terminal the overseer types into
21
+ * too, so only what comes from its browser mirror or the colony dashboard's Send Message (its /broadcast), not the
22
+ * prompt it is started with, which colony under a ZTC host types into that terminal; 'none' in a ZTC pane, which relays
23
+ * all it reads.
24
+ */
25
+ export type PersonRouterAttempts = 'all' | 'mirror' | 'none';
18
26
  /**
19
27
  * What an interactive launch says about a recorded refusal. A provider cooldown's words already say when to try again,
20
- * and nothing is sent before then; for anything else the person's next message still gets its attempt.
28
+ * and nothing is sent before then. For anything else it says where the person's next message still gets its attempt
29
+ * (`attempts`): anywhere in the main session; in a ZTC pane or a colony cell, what reaches its terminal is held like
30
+ * background work, so it says that and names where they can try instead.
21
31
  */
22
- export declare function formatRecordedRouterRefusal(hold: RouterHold): string;
32
+ export declare function formatRecordedRouterRefusal(hold: RouterHold, attempts: PersonRouterAttempts): string;
@@ -7,7 +7,10 @@
7
7
  * runs launched together make one between them. A success removes the entry. An interactive launch shows what is
8
8
  * recorded and holds it for its own background work (heartbeats, routines, workers), but every new message from the
9
9
  * person still gets one real attempt, since they may have just raised the limit (a provider cooldown excepted: nothing
10
- * is tried before it clears); it records nothing of its own, and a success there removes the entry too.
10
+ * is tried before it clears). What reaches a ZTC pane's or a colony cell's terminal is held like background work,
11
+ * since the overseer types there too, and such a launch says where the person can still try (see
12
+ * formatRecordedRouterRefusal). An interactive launch records nothing of its own, and a success there removes the entry
13
+ * too.
11
14
  *
12
15
  * The record holds the route, a one-way fingerprint of the account, the provider, the model and Router's public words
13
16
  * and fields for the refusal: no credential and nothing of the request. Every write replaces the file atomically
@@ -134,9 +137,21 @@ export function adoptRouterRefusalRecord(mode, path = routerRefusalRecordPath())
134
137
  }
135
138
  /**
136
139
  * What an interactive launch says about a recorded refusal. A provider cooldown's words already say when to try again,
137
- * and nothing is sent before then; for anything else the person's next message still gets its attempt.
140
+ * and nothing is sent before then. For anything else it says where the person's next message still gets its attempt
141
+ * (`attempts`): anywhere in the main session; in a ZTC pane or a colony cell, what reaches its terminal is held like
142
+ * background work, so it says that and names where they can try instead.
138
143
  */
139
- export function formatRecordedRouterRefusal(hold) {
144
+ export function formatRecordedRouterRefusal(hold, attempts) {
140
145
  const refused = `Zerg Router refused ${hold.provider}/${hold.model} for an unattended run at ${localRouterTime(hold.refusedAt)}: ${hold.message}`;
141
- return hold.waitOut ? refused : `${refused} Your next message still goes to Router, in case the limit has changed.`;
146
+ if (hold.waitOut)
147
+ return refused;
148
+ if (attempts === 'all')
149
+ return `${refused} Your next message still goes to Router, in case the limit has changed.`;
150
+ const held = 'is refused without contacting Router, like background work, except one real request every five minutes';
151
+ const elsewhere = attempts === 'mirror'
152
+ ? 'The overseer can type into this cell\'s terminal too, so what is typed there, which can include the prompt this cell'
153
+ + ` started with, ${held}. A message from this cell's browser mirror, the colony dashboard's Send Message or your`
154
+ + ' main session'
155
+ : `The overseer can type into this pane too, so what you send it ${held}. A message from your main session`;
156
+ return `${refused} ${elsewhere} still goes to Router, in case the limit has changed.`;
142
157
  }
@@ -45,7 +45,12 @@ export declare function waitForPaneCreatedOrError(tui: PaneCommandTransport, exp
45
45
  requestId?: string;
46
46
  }, timeoutMs?: number): Promise<RustEvent>;
47
47
  export declare function paneLimitReached(): boolean;
48
- /** Environment a ZTC child pane needs to join this workspace (relay, mirror bus, PATH). */
48
+ /**
49
+ * Environment a ZTC child pane needs to join this workspace (relay, mirror bus, PATH). Its mirror credential is its
50
+ * own, which the pane transport hands it as it creates the pane, in a one-time file its command line names
51
+ * (PaneCredentialBroker); the mirror's process-wide token, and this process's own credential when it is itself a pane,
52
+ * are never passed on.
53
+ */
49
54
  export declare function childZtcPaneEnv(): Record<string, string>;
50
55
  export declare function buildChildZtcPaneLaunch(extraArgs?: string[], childSessionId?: string, options?: {
51
56
  mirrorPort?: number;
@@ -428,7 +428,12 @@ function filterChildZtcArgs(args) {
428
428
  }
429
429
  return filtered;
430
430
  }
431
- /** Environment a ZTC child pane needs to join this workspace (relay, mirror bus, PATH). */
431
+ /**
432
+ * Environment a ZTC child pane needs to join this workspace (relay, mirror bus, PATH). Its mirror credential is its
433
+ * own, which the pane transport hands it as it creates the pane, in a one-time file its command line names
434
+ * (PaneCredentialBroker); the mirror's process-wide token, and this process's own credential when it is itself a pane,
435
+ * are never passed on.
436
+ */
432
437
  export function childZtcPaneEnv() {
433
438
  const env = {
434
439
  ZTC_PARENT_PID: String(process.pid),
@@ -436,9 +441,6 @@ export function childZtcPaneEnv() {
436
441
  if (process.env.ZTC_MIRROR_PORT) {
437
442
  env.ZTC_MIRROR_PORT = process.env.ZTC_MIRROR_PORT;
438
443
  }
439
- if (process.env.ZTC_MIRROR_INTERNAL_TOKEN) {
440
- env.ZTC_MIRROR_INTERNAL_TOKEN = process.env.ZTC_MIRROR_INTERNAL_TOKEN;
441
- }
442
444
  if (process.env.ZTC_PANE_RELAY) {
443
445
  env.ZTC_PANE_RELAY = process.env.ZTC_PANE_RELAY;
444
446
  }
@@ -7,4 +7,11 @@ export interface ParentMirrorClientOptions {
7
7
  colonyChild: boolean;
8
8
  }
9
9
  export declare function shouldMarkMirrorServerAsColonyChild(options: MirrorChildRoleOptions, env: Record<string, string | undefined>): boolean;
10
+ /**
11
+ * Whether this ZTC publishes to, and joins the bus of, the mirror of the ZTC that launched it into a pane. That needs
12
+ * the pane's own mirror credential, the one this ZTC took from its handoff or one ENV holds (or, from a parent before
13
+ * per-pane credentials, the token it handed its panes): a pane the renderer started again in place without one
14
+ * (restart_pane, or a replace a pane asked for through the relay) has none, and the mirror would refuse every request
15
+ * it made. A pane opened or resumed is handed one (see consumePaneCredentialHandoff).
16
+ */
10
17
  export declare function shouldAttachParentMirrorClient(options: ParentMirrorClientOptions, env: Record<string, string | undefined>): boolean;
@@ -1,10 +1,20 @@
1
+ import { paneMirrorCredentialHeaders } from '../web/pane_credentials.js';
1
2
  export function shouldMarkMirrorServerAsColonyChild(options, env) {
2
3
  if (env.ZTC_COLONY_CHILD)
3
4
  return true;
4
5
  return !options.explicitMirror && options.headlessMirror && !!env.ZTC_PANE_ID;
5
6
  }
7
+ /**
8
+ * Whether this ZTC publishes to, and joins the bus of, the mirror of the ZTC that launched it into a pane. That needs
9
+ * the pane's own mirror credential, the one this ZTC took from its handoff or one ENV holds (or, from a parent before
10
+ * per-pane credentials, the token it handed its panes): a pane the renderer started again in place without one
11
+ * (restart_pane, or a replace a pane asked for through the relay) has none, and the mirror would refuse every request
12
+ * it made. A pane opened or resumed is handed one (see consumePaneCredentialHandoff).
13
+ */
6
14
  export function shouldAttachParentMirrorClient(options, env) {
7
15
  if (!env.ZTC_MIRROR_PORT || !env.ZTC_PANE_ID)
8
16
  return false;
17
+ if (Object.keys(paneMirrorCredentialHeaders(env)).length === 0)
18
+ return false;
9
19
  return options.colonyChild || options.paneMode;
10
20
  }
@@ -69,6 +69,12 @@ export declare function reduceDesktopUpdateOwnerHandshake(phase: DesktopUpdateOw
69
69
  * permitted to exist when persistence rejects or the transport is unavailable.
70
70
  */
71
71
  export declare function prepareDesktopUpdateAuthorization(persistSession: (force: true) => Promise<void>, send: (command: DesktopUpdateRestartCommand) => boolean): Promise<DesktopUpdatePreparation>;
72
+ /**
73
+ * The arguments that start this ZTC again on SESSION_ID, from ARGV (its own, from its script on): its options, with any
74
+ * session they start or resume replaced by `--resume SESSION_ID` at the end, so a caller can add options after it. A
75
+ * task after an end of options (`--`), as a ZTC pane opened with a task has, is left out with it: the session already
76
+ * holds the task, and a resumed session is not sent it again, as a pane resumed from its saved spec is not.
77
+ */
72
78
  export declare function buildHotRestartArgs(argv: readonly string[], sessionId: string): string[];
73
79
  export declare function buildHotRestartLaunch(argv: readonly string[], sessionId: string, execPath: string, cwd?: string, desktopRuntime?: DesktopRuntime | null): HotRestartLaunch;
74
80
  export declare function buildDesktopUpdateRelaunchContext(argv: readonly string[], sessionId: string, execPath: string, cwd: string, ownerPid: number, desktopRuntime?: DesktopRuntime | null): string;
@@ -1,6 +1,7 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { pathToFileURL } from 'node:url';
3
3
  import { resolveOwnedCliLaunch } from '../desktop/cli_launch.js';
4
+ import { paneMirrorCredentialHeaders } from '../web/pane_credentials.js';
4
5
  const RESTART_SESSION_FLAGS = new Set(['--resume', '--continue', '-c', '--session-id']);
5
6
  /**
6
7
  * Reduce native updater protocol events and local persistence outcomes into
@@ -91,10 +92,19 @@ export async function prepareDesktopUpdateAuthorization(persistSession, send) {
91
92
  }
92
93
  return { status: 'authorization_requested' };
93
94
  }
95
+ /**
96
+ * The arguments that start this ZTC again on SESSION_ID, from ARGV (its own, from its script on): its options, with any
97
+ * session they start or resume replaced by `--resume SESSION_ID` at the end, so a caller can add options after it. A
98
+ * task after an end of options (`--`), as a ZTC pane opened with a task has, is left out with it: the session already
99
+ * holds the task, and a resumed session is not sent it again, as a pane resumed from its saved spec is not.
100
+ */
94
101
  export function buildHotRestartArgs(argv, sessionId) {
95
102
  const next = [];
96
103
  for (let i = 0; i < argv.length; i++) {
97
104
  const arg = argv[i];
105
+ // The end of options: what follows is the launch task.
106
+ if (arg === '--')
107
+ break;
98
108
  if (i === 1 && arg === 'resume') {
99
109
  const value = argv[i + 1];
100
110
  if (value && !value.startsWith('-'))
@@ -157,12 +167,12 @@ export async function requestColonyCellRestart(env = process.env, fetchImpl = fe
157
167
  throw new Error('ZTC_COLONY_WORKTREE_ID is missing');
158
168
  if (!parentMirrorPort)
159
169
  throw new Error('ZTC_COLONY_PARENT_MIRROR_PORT is missing');
170
+ // The cell's own pane credential for its overseer's mirror (or, under an overseer from before per-pane
171
+ // credentials, the token that overseer handed it).
160
172
  const headers = {
161
173
  'Content-Type': 'application/json',
174
+ ...paneMirrorCredentialHeaders(env),
162
175
  };
163
- if (env.ZTC_MIRROR_INTERNAL_TOKEN) {
164
- headers['x-ztc-internal-token'] = env.ZTC_MIRROR_INTERNAL_TOKEN;
165
- }
166
176
  const response = await fetchImpl(`http://localhost:${parentMirrorPort}/colony/agents/restart`, {
167
177
  method: 'POST',
168
178
  headers,
@@ -2,16 +2,27 @@ import { emitKeypressEvents } from 'node:readline';
2
2
  import { formatAskUserResponse } from './ask_user_response.js';
3
3
  import { sanitizeTerminalText } from '../ui/core/text_width.js';
4
4
  import { QuestionnaireWidget } from '../ui/widgets/questionnaire.js';
5
+ import { consumePaneCredentialHandoff, paneMirrorCredentialHeaders } from '../web/pane_credentials.js';
6
+ // The layout hands this monitor its credential in a one-time file its command line names, never in its environment,
7
+ // which any program running as this user can read: take it, and drop the flag, before reading the arguments.
8
+ consumePaneCredentialHandoff();
5
9
  const [mode, rawPort, ownerId, rawRefresh] = process.argv.slice(2);
6
10
  const port = Number(rawPort);
7
11
  const refreshMs = Number(rawRefresh);
8
- const token = process.env.ZTC_MIRROR_INTERNAL_TOKEN;
12
+ // The monitor pane's own credential, which also reads the runtime and answers its decisions (pane_credentials.ts).
13
+ const credential = paneMirrorCredentialHeaders(process.env);
9
14
  if (!['decisions', 'status'].includes(mode) || !Number.isInteger(port) || port < 1 || port > 65535
10
- || !ownerId || !token || !Number.isInteger(refreshMs) || refreshMs < 1 || refreshMs > 86400000) {
15
+ || !ownerId || !Number.isInteger(refreshMs) || refreshMs < 1 || refreshMs > 86400000) {
11
16
  process.stderr.write('Workspace monitor requires its live parent, owned port and refresh settings. Open a fresh /layout orchestrator.\n');
12
17
  process.exit(1);
13
18
  }
14
- const headers = { 'x-ztc-internal-token': token, 'x-ztc-workspace-owner': ownerId };
19
+ // A renderer restarts a pane in place with the command line it first had, which names the file this monitor took its
20
+ // credential from and deleted; only a new layout can give it one.
21
+ if (Object.keys(credential).length === 0) {
22
+ process.stderr.write('Workspace monitor has no credential for its ZTC\'s mirror: a monitor restarted in place starts without one. Close this pane and open a fresh /layout orchestrator.\n');
23
+ process.exit(1);
24
+ }
25
+ const headers = { ...credential, 'x-ztc-workspace-owner': ownerId };
15
26
  let snapshot = null;
16
27
  let selected = 0;
17
28
  let scroll = 0;
@@ -27,6 +38,9 @@ async function request(path, body) {
27
38
  ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(5000),
28
39
  });
29
40
  const value = await response.json();
41
+ // A mirror that no longer knows this monitor's credential is another incarnation: its owner changed.
42
+ if (response.status === 401)
43
+ throw new Error('Workspace owner changed; open a fresh layout.');
30
44
  if (!response.ok) {
31
45
  const error = value !== null && typeof value === 'object' && 'error' in value && typeof value.error === 'string'
32
46
  ? value.error : `Runtime request failed (${response.status})`;
@@ -4,6 +4,7 @@ import { join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { parseDocument } from 'yaml';
6
6
  import { buildZtcPaneLaunchCommand, createZtcLaunchSpec } from '../panes/ztc_launch.js';
7
+ import { PANE_CREDENTIAL_ENV, WORKSPACE_MONITOR_CREDENTIAL_REQUEST } from '../web/pane_credentials.js';
7
8
  const defaults = { main: 'Main', decisions: 'Decisions', status: 'Status', worker: 'Worker' };
8
9
  const isRecord = (value) => value !== null
9
10
  && typeof value === 'object' && !Array.isArray(value);
@@ -162,9 +163,15 @@ export async function openWorkspacePreset(transport, host, args) {
162
163
  const command = commands[index];
163
164
  const requestId = randomUUID();
164
165
  host.trackLaunch(requestId, spec);
166
+ // A worker is a ZTC pane, given a credential of its own; a monitor's own credential also reads the runtime it
167
+ // shows and answers its decisions (see pane_credentials.ts). Each is handed over in a one-time file its command line
168
+ // names, never in its environment. The monitor asks the mirror its command line names (host.mirrorPort), so its
169
+ // credential comes from that one, not from a /sim run's that host.env names meanwhile.
170
+ const env = spec.kind === 'ztc' ? host.env : { ...host.env, ZTC_MIRROR_PORT: String(host.mirrorPort),
171
+ [PANE_CREDENTIAL_ENV]: WORKSPACE_MONITOR_CREDENTIAL_REQUEST };
165
172
  const event = await request({ type: 'create_pane', request_id: requestId, command: command.command,
166
173
  args: command.args, cwd: command.cwd, title: spec.title, pane_type: spec.kind === 'ztc' ? 'ztc' : 'process',
167
- env: host.env, target: index === 0 ? 0 : created.at(-1),
174
+ env, target: index === 0 ? 0 : created.at(-1),
168
175
  new_window: index === 0 && rootLeaves.length > 1 }, event => event.type === 'pane_created' && event.request_id === requestId);
169
176
  if (event.type !== 'pane_created')
170
177
  throw new Error('Unexpected pane creation response');
package/dist/cli_main.js CHANGED
@@ -33,6 +33,11 @@ import { buildCliCommonStarts } from './onboarding/first_run.js';
33
33
  import { validateProfileName } from './config/profiles.js';
34
34
  import { loadDesktopRuntime } from './desktop/runtime.js';
35
35
  import { resolveOwnedCliLaunch } from './desktop/cli_launch.js';
36
+ import { consumePaneCredentialHandoff } from './web/pane_credentials.js';
37
+ // A ZTC pane is handed its mirror credential in a one-time file its command line names: take it, and the flag, before
38
+ // anything reads the arguments, and keep it out of the environment every program this ZTC starts inherits (see
39
+ // pane_credentials.ts).
40
+ consumePaneCredentialHandoff();
36
41
  // Information-only flags remain available to diagnose an incompatible bundle.
37
42
  const args = process.argv.slice(2);
38
43
  let desktopRuntime = null;
@@ -237,14 +237,16 @@ export declare class RatatuiApp {
237
237
  /** Busy Enter prompts waiting for the next completed tool batch. */
238
238
  private pendingSteering;
239
239
  /**
240
- * Steering the person entered (see submitPersonInput) that no request has carried yet. The first request that
241
- * carries one is theirs: it gets their one attempt past a Zerg Router refusal, as their message would when idle.
240
+ * Steering that takes the person's one attempt past a Zerg Router refusal (see takesRouterAttempt) and that no
241
+ * request has carried yet. The first request that carries one is theirs: it gets that attempt, as their message would
242
+ * when idle.
242
243
  */
243
244
  private personSteeringIds;
244
245
  /**
245
- * The person entered a message (see submitPersonInput) that the next turn to start carries. That turn takes it as it
246
- * starts and, once started, admits it on the agent that runs it (rebuilt meanwhile when the mode changed), so the
247
- * request carrying the message gets their one attempt past a Zerg Router refusal. A turn that fails to start drops it.
246
+ * The person entered a message that takes their one attempt past a Zerg Router refusal (see takesRouterAttempt), and
247
+ * the next turn to start carries it. That turn takes it as it starts and, once started, admits it on the agent that
248
+ * runs it (rebuilt meanwhile when the mode changed), so the request carrying the message gets the attempt. A turn
249
+ * that fails to start drops it. Typing that reaches a ZTC pane's or a colony cell's terminal never sets it.
248
250
  */
249
251
  private personMessagePending;
250
252
  private nativeSteeringInFlight;
@@ -272,7 +274,7 @@ export declare class RatatuiApp {
272
274
  private workspacePausedSnapshot;
273
275
  private workspacePausedEffectCwd;
274
276
  private workspacePausedQueueId;
275
- /** Input held over a workspace pause, and whether the person entered it (see handleSubmit's `person`). */
277
+ /** Input held over a workspace pause, and who entered it and where (see queueOrigin). */
276
278
  private workspacePendingInputs;
277
279
  private workspaceDeferredRun;
278
280
  private workspaceAdmissionTail;
@@ -628,10 +630,33 @@ export declare class RatatuiApp {
628
630
  */
629
631
  private executeCommandForTool;
630
632
  private startMirrorFromCommand;
633
+ /**
634
+ * In zmux, what SERVER delivers to a child pane with no bus connection of its own reaches the pane through this ZTC's
635
+ * renderer, typed into its terminal: browser input and another member's message as input, the overseer's control
636
+ * commands bare, and an agent's message for a Claude Code or Codex pane with its sender. The mirror ZTC starts with and
637
+ * each one /mirror start starts take them; without them a mirror queues the message for a bus connection the pane
638
+ * never makes.
639
+ */
640
+ private registerMirrorPaneFallbacks;
641
+ /**
642
+ * The overseer's MESSAGE while this ZTC runs no mirror (it started without one, or /mirror stop stopped it): there is
643
+ * no bus, so it is typed into the panes it is for. One for this ZTC itself reaches its own agent, as a mirror's member
644
+ * 0 hands it over. A Claude Code or Codex pane gets it as a mirror types it in (registerMirrorPaneFallbacks); any other
645
+ * pane, as the prompt "[Message from Overseer]: …". A broadcast reaches the ZTC panes, the members a bus would have,
646
+ * and no shell, which would run it as a command.
647
+ */
648
+ private typeOverseerMessage;
631
649
  private resolveOwnQuestion;
632
650
  private handleQuestionAnswer;
633
651
  private handleApprovalAnswer;
634
652
  private stopMirrorFromCommand;
653
+ /**
654
+ * Tell the pane transport which mirror this ZTC runs now, or that it runs none: a pane a pane opens through the relay
655
+ * is pointed at that mirror and gets its credential there, rather than at the one the renderer was started with, which
656
+ * /mirror stop and a /mirror start on another port leave behind (PaneCredentialBroker.setOwnerMirrorPort). Only a
657
+ * transport that opens panes takes it; NullTuiProcess opens none.
658
+ */
659
+ private setPaneTransportMirrorPort;
635
660
  private handleDictationEvent;
636
661
  /**
637
662
  * Whether the immediate (non-debounced) input path should be used.
@@ -952,25 +977,53 @@ export declare class RatatuiApp {
952
977
  /**
953
978
  * Submit what the person entered themselves (typed, dictated, sent from the browser mirror, or given on the command
954
979
  * line). It gets one real attempt even while a Zerg Router refusal holds the route, since they may have just raised
955
- * the limit. What the mirror's /broadcast delivers comes here too and keeps that attempt, as it always has. `via`:
956
- * where it was entered, this ZTC's terminal (its keys, dictation, the command line), the browser mirror or
957
- * /broadcast (see handleSubmit's `via`).
980
+ * the limit, unless it is relayed here: what a ZTC pane or a colony cell reads from its terminal, which the
981
+ * overseer's write_terminal_pane types into too, never gets it (see takesRouterAttempt). What the mirror's /broadcast
982
+ * delivers comes here too and keeps that attempt, as it always has. `via`: where it was entered, this ZTC's terminal
983
+ * (its keys, dictation, the command line), the browser mirror or /broadcast (see handleSubmit's `via`).
958
984
  */
959
985
  private submitPersonInput;
986
+ /**
987
+ * Submit what the mirror's input callback delivers. The browser's is the person's, and what /broadcast delivers keeps
988
+ * the attempt it always had (submitPersonInput). What a ZTC process or a pane posts ('relayed': the mirror's
989
+ * process-wide token or a pane's own credential) is never the person's: it runs as relayed input, so choices only the
990
+ * person makes refuse it and it takes no attempt past a Zerg Router refusal.
991
+ */
992
+ private submitMirrorInput;
960
993
  /**
961
994
  * Who entered input the queue holds for later, kept with its entry: handleSubmit's `person` and `via`. Each place
962
995
  * that sends a queued entry passes them back (`entry.person === true`, `entry.via ?? 'terminal'`), so the person's
963
- * line runs as theirs and relayed input stays relayed.
996
+ * line runs as theirs and relayed input stays relayed. A workspace pause keeps them the same way.
964
997
  */
965
998
  private queueOrigin;
999
+ /**
1000
+ * Whether what is entered from `via` is relayed here, whoever entered it, so a command in it makes none of the
1001
+ * person's choices. What a ZTC that another ZTC launched into one of its panes reads from its terminal is, whatever
1002
+ * its flags: a ZTC pane's ztc-tui, or a colony cell's own zmux, reads a PTY that the overseer's write_terminal_pane
1003
+ * and other panes type into too, so the person's typing there can't be told from theirs. A colony cell's own browser
1004
+ * mirror is still the person; everything a --pane child reads is relayed, its browser messages included. What a
1005
+ * mirror's /broadcast delivers is relayed in every ZTC, cell or not: only colony's send_to_worktree tool and its
1006
+ * dashboard post there.
1007
+ */
1008
+ private relayedHere;
1009
+ /**
1010
+ * Whether input takes the person's one real attempt past a Zerg Router refusal: they entered it (handleSubmit's
1011
+ * `person`) where it isn't relayed (see relayedHere), so nothing the overseer types into a ZTC pane or a colony cell
1012
+ * sends Router a request the refusal holds. What the mirror's /broadcast delivers keeps the attempt it always had,
1013
+ * relayed or not: the colony dashboard's send, which is the person, posts there.
1014
+ */
1015
+ private takesRouterAttempt;
966
1016
  /**
967
1017
  * `person`: the person entered this input themselves (see submitPersonInput). A /loop tick, a goal continuation,
968
1018
  * another pane's or the coordinator's message and a pane's initial task never are, so none of them passes a Zerg
969
1019
  * Router refusal the process holds; a queued entry is whoever queued it (QueueEntry.person and QueueEntry.via, which
970
1020
  * the queue passes back here). `via`: where the person entered it, this ZTC's terminal or the
971
1021
  * browser mirror, or else the mirror's /broadcast, which only colony's AgentBridge posts to (the overseer's
972
- * send_to_worktree tool and the colony dashboard's send). In a ZTC another ZTC launched into one of its panes, what
973
- * the terminal gives it isn't only the person's, and what /broadcast gives any ZTC never is (see the origin below).
1022
+ * send_to_worktree tool and the colony dashboard's send), or 'relayed', the mirror's routes posted by a ZTC process or
1023
+ * a pane, which is never the person's (submitMirrorInput). In a ZTC another ZTC launched into one of its panes, what
1024
+ * the terminal gives it isn't only the person's, and what /broadcast gives any ZTC never is (see relayedHere). What
1025
+ * is relayed here makes none of the person's choices and, unless /broadcast delivered it, passes no refusal either
1026
+ * (see takesRouterAttempt).
974
1027
  */
975
1028
  private handleSubmit;
976
1029
  /**
@@ -1036,25 +1089,33 @@ export declare class RatatuiApp {
1036
1089
  * Ask for the API key a direct route is missing, then send `input` as typed.
1037
1090
  * On cancel the text goes back to the composer. Only input typed in this
1038
1091
  * terminal or its mirror asks: queued input and pane children keep the setup
1039
- * message, and an open widget is never replaced.
1092
+ * message, and an open widget is never replaced. The send goes as whoever
1093
+ * entered it, from where (handleSubmit's `person` and `via`).
1040
1094
  */
1041
1095
  private askForSendCredential;
1042
1096
  private localWorkspace;
1043
1097
  private retireWorkspaceChoice;
1044
1098
  /**
1045
- * Only accepted-but-unadmitted sources belong to this local pause. `person`: the person entered it, so /sessions
1046
- * continue sends it as theirs, with its one real attempt past a Zerg Router refusal.
1099
+ * Only accepted-but-unadmitted sources belong to this local pause. `origin`: who entered it and where (see
1100
+ * queueOrigin), which /sessions continue sends it with, so the person's message keeps its one real attempt past a
1101
+ * Zerg Router refusal where it had one (see takesRouterAttempt).
1047
1102
  */
1048
1103
  private retainWorkspaceInput;
1049
1104
  private chooseWorkspaceAction;
1050
1105
  private pauseWorkspace;
1051
- /** `person`: the person entered `input` themselves, which a pause keeps with it (see retainWorkspaceInput). */
1106
+ /**
1107
+ * `origin`: who entered `input` and where (see queueOrigin), which a pause keeps with it (see
1108
+ * retainWorkspaceInput).
1109
+ */
1052
1110
  private guardWorkspaceAdmission;
1053
1111
  private waitForWorkspaceContinuation;
1054
1112
  private admitWorkspaceTool;
1055
1113
  private continueWorkspace;
1056
1114
  private isolateWorkspace;
1057
- /** Classify independently; admission decisions retain submission FIFO. */
1115
+ /**
1116
+ * Classify independently; admission decisions retain submission FIFO. `routerAttempt`: the input takes the person's
1117
+ * one real attempt past a Zerg Router refusal (see takesRouterAttempt), which it carries as steering.
1118
+ */
1058
1119
  private routeBusyInput;
1059
1120
  private routingInteractionOccupied;
1060
1121
  /** A transient choice shares the existing terminal and mirror widget contract. */
@@ -1062,6 +1123,10 @@ export declare class RatatuiApp {
1062
1123
  private retireBusyInputRouting;
1063
1124
  /** Restore only an empty composer; retain a competing draft in the transcript. */
1064
1125
  private restoreBusyDraft;
1126
+ /**
1127
+ * `routerAttempt`: the steering takes the person's one real attempt past a Zerg Router refusal (see
1128
+ * takesRouterAttempt).
1129
+ */
1065
1130
  private admitBusySteering;
1066
1131
  /**
1067
1132
  * Run the agent on the current messages.
@@ -1124,7 +1189,10 @@ export declare class RatatuiApp {
1124
1189
  private maybeFlushQueue;
1125
1190
  /** Publish each accepted source once, at its actual admission boundary. */
1126
1191
  private revealAdmittedSteering;
1127
- /** MESSAGES now go to the agent: when one is the person's own steering, the request that carries it is theirs. */
1192
+ /**
1193
+ * MESSAGES now go to the agent: when one is steering that takes the person's attempt (see personSteeringIds), the
1194
+ * request that carries it is theirs.
1195
+ */
1128
1196
  private admitPersonSteering;
1129
1197
  /** Put steering that missed a tool boundary after the finished answer. */
1130
1198
  private movePendingSteeringToEnd;
@@ -1367,6 +1435,7 @@ export declare class RatatuiApp {
1367
1435
  private displayWorkflowEvent;
1368
1436
  /** Render a batch event as a system message or trigger the approval widget. */
1369
1437
  private displayBatchEvent;
1438
+ /** What a ZTC pane needs to join this workspace; its mirror credential is its own (see pane.ts childZtcPaneEnv). */
1370
1439
  private childZtcPaneEnv;
1371
1440
  /**
1372
1441
  * ZTerm (or the palette) asked for a ZTC pane. The request may carry the