@zergai/ztc 0.23.1-dev.202611152321 → 0.24.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 (149) hide show
  1. package/README.md +299 -13
  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 +2 -2
  10. package/dist/agent/agent.js +57 -14
  11. package/dist/agent/backends/http_error.d.ts +2 -0
  12. package/dist/agent/backends/http_error.js +2 -0
  13. package/dist/agent/backends/router_gate.d.ts +3 -2
  14. package/dist/agent/backends/router_gate.js +5 -4
  15. package/dist/agent/backends/router_keys.d.ts +14 -0
  16. package/dist/agent/backends/router_keys.js +19 -0
  17. package/dist/agent/backends/router_refusal.d.ts +5 -3
  18. package/dist/agent/backends/router_refusal.js +28 -6
  19. package/dist/agent/backends/types.d.ts +1 -1
  20. package/dist/agent/backends/zrouter_stream.js +10 -6
  21. package/dist/agent/commands/agent_cli.d.ts +11 -1
  22. package/dist/agent/commands/agent_cli.js +295 -38
  23. package/dist/agent/commands/diff.js +4 -1
  24. package/dist/agent/commands/help.js +4 -1
  25. package/dist/agent/commands/plan.js +3 -1
  26. package/dist/agent/commands/session_redaction.d.ts +16 -0
  27. package/dist/agent/commands/session_redaction.js +77 -0
  28. package/dist/agent/commands/settings.js +144 -0
  29. package/dist/agent/commands/types.d.ts +5 -0
  30. package/dist/agent/commands/usage_spec.d.ts +4 -0
  31. package/dist/agent/commands/usage_spec.js +10 -4
  32. package/dist/agent/runtime/policy.d.ts +25 -0
  33. package/dist/agent/runtime/policy.js +154 -26
  34. package/dist/agent/runtime/source_verification.js +6 -2
  35. package/dist/agent/runtime/tool_runtime.js +81 -3
  36. package/dist/agent/tools/apply_patch.js +678 -131
  37. package/dist/agent/tools/bus_message.d.ts +26 -1
  38. package/dist/agent/tools/bus_message.js +126 -10
  39. package/dist/agent/tools/file.d.ts +16 -1
  40. package/dist/agent/tools/file.js +43 -5
  41. package/dist/agent/tools/index.d.ts +1 -1
  42. package/dist/agent/tools/index.js +1 -1
  43. package/dist/agent/tools/pane.js +5 -0
  44. package/dist/agent/tools/search.js +5 -1
  45. package/dist/agent/tools/supervision.js +16 -2
  46. package/dist/agent/tools/types.d.ts +22 -0
  47. package/dist/app/mirror_startup.d.ts +7 -5
  48. package/dist/app/mirror_startup.js +7 -5
  49. package/dist/app/navigator_mirrors.d.ts +20 -0
  50. package/dist/app/navigator_mirrors.js +36 -0
  51. package/dist/app/workspace_layout_controller.d.ts +11 -2
  52. package/dist/app/workspace_layout_controller.js +13 -2
  53. package/dist/batch/worktree.js +9 -1
  54. package/dist/cli_ratatui.d.ts +264 -12
  55. package/dist/cli_ratatui.js +1198 -103
  56. package/dist/config/types.d.ts +29 -0
  57. package/dist/desktop/daily/source_baseline.js +3 -1
  58. package/dist/diagnostics/session_export.d.ts +1 -0
  59. package/dist/diagnostics/session_export.js +229 -26
  60. package/dist/emulation/tool_adapters.js +42 -5
  61. package/dist/headless.js +24 -5
  62. package/dist/instance_registry.d.ts +7 -0
  63. package/dist/mcp/workspace_server.d.ts +12 -1
  64. package/dist/mcp/workspace_server.js +75 -8
  65. package/dist/panes/agent_cli.d.ts +60 -3
  66. package/dist/panes/agent_cli.js +169 -16
  67. package/dist/panes/agent_pane_sessions.d.ts +22 -0
  68. package/dist/panes/agent_pane_sessions.js +111 -0
  69. package/dist/panes/agent_panes.d.ts +77 -3
  70. package/dist/panes/agent_panes.js +199 -10
  71. package/dist/panes/agent_profiles.d.ts +5 -0
  72. package/dist/panes/agent_profiles.js +7 -0
  73. package/dist/panes/agent_resume.d.ts +134 -0
  74. package/dist/panes/agent_resume.js +155 -0
  75. package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
  76. package/dist/panes/agent_sessions/claude_head.js +122 -0
  77. package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
  78. package/dist/panes/agent_sessions/claude_store.js +223 -0
  79. package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
  80. package/dist/panes/agent_sessions/codex_head.js +161 -0
  81. package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
  82. package/dist/panes/agent_sessions/codex_store.js +187 -0
  83. package/dist/panes/agent_sessions/controller.d.ts +74 -0
  84. package/dist/panes/agent_sessions/controller.js +110 -0
  85. package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
  86. package/dist/panes/agent_sessions/cut_json.js +109 -0
  87. package/dist/panes/agent_sessions/limits.d.ts +48 -0
  88. package/dist/panes/agent_sessions/limits.js +48 -0
  89. package/dist/panes/agent_sessions/scan.d.ts +49 -0
  90. package/dist/panes/agent_sessions/scan.js +86 -0
  91. package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
  92. package/dist/panes/agent_sessions/store_fs.js +128 -0
  93. package/dist/panes/agent_sessions/stores.d.ts +36 -0
  94. package/dist/panes/agent_sessions/stores.js +89 -0
  95. package/dist/panes/agent_sessions/title.d.ts +9 -0
  96. package/dist/panes/agent_sessions/title.js +51 -0
  97. package/dist/panes/agent_sessions/types.d.ts +48 -0
  98. package/dist/panes/agent_sessions/types.js +2 -0
  99. package/dist/panes/reply_arbitrator.d.ts +39 -0
  100. package/dist/panes/reply_arbitrator.js +185 -0
  101. package/dist/panes/reply_modes.d.ts +291 -0
  102. package/dist/panes/reply_modes.js +598 -0
  103. package/dist/runtime_info.js +11 -2
  104. package/dist/session.js +4 -2
  105. package/dist/simulation/living/context.d.ts +8 -8
  106. package/dist/simulation/living/types.d.ts +5 -5
  107. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  108. package/dist/ui/ratatui/ipc_path.d.ts +5 -0
  109. package/dist/ui/ratatui/ipc_path.js +23 -3
  110. package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
  111. package/dist/ui/ratatui/pane_credential_broker.js +49 -14
  112. package/dist/ui/ratatui/pane_relay.d.ts +5 -2
  113. package/dist/ui/ratatui/pane_relay.js +86 -19
  114. package/dist/ui/ratatui/process.js +3 -0
  115. package/dist/ui/ratatui/protocol.d.ts +50 -1
  116. package/dist/ui/ratatui/protocol.js +56 -0
  117. package/dist/ui/ratatui/relay_policy.d.ts +39 -0
  118. package/dist/ui/ratatui/relay_policy.js +94 -0
  119. package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
  120. package/dist/ui/ratatui/screen_privacy.js +24 -0
  121. package/dist/ui/scrollback.js +8 -0
  122. package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
  123. package/dist/ui/widgets/agent_sessions_panel.js +542 -0
  124. package/dist/ui/widgets/log_view.d.ts +5 -1
  125. package/dist/ui/widgets/log_view.js +40 -4
  126. package/dist/utils/atomic_write.js +9 -11
  127. package/dist/utils/canonical_path.d.ts +19 -0
  128. package/dist/utils/canonical_path.js +44 -0
  129. package/dist/utils/compaction.d.ts +2 -1
  130. package/dist/utils/compaction.js +3 -1
  131. package/dist/utils/git_directory_names.d.ts +51 -0
  132. package/dist/utils/git_directory_names.js +429 -0
  133. package/dist/utils/temporary_write_root.d.ts +6 -1
  134. package/dist/utils/temporary_write_root.js +32 -2
  135. package/dist/utils/tool_result_message.d.ts +4 -1
  136. package/dist/utils/tool_result_message.js +6 -2
  137. package/dist/web/bus_hold.d.ts +70 -0
  138. package/dist/web/bus_hold.js +118 -0
  139. package/dist/web/mirror_client.d.ts +7 -3
  140. package/dist/web/mirror_client.js +61 -23
  141. package/dist/web/mirror_route_gate.d.ts +40 -0
  142. package/dist/web/mirror_route_gate.js +71 -0
  143. package/dist/web/mirror_stream.d.ts +147 -22
  144. package/dist/web/mirror_stream.js +350 -83
  145. package/dist/web/pane_credentials.d.ts +32 -1
  146. package/dist/web/pane_credentials.js +62 -2
  147. package/dist/workspace_collision.js +11 -2
  148. package/dist/zlm-embed.mjs +940 -273
  149. package/package.json +39 -7
@@ -22,6 +22,7 @@ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprot
22
22
  import { agentZtcPaneEnv, closeTerminalPaneTool, listWorkspacePanes, readTerminalPaneTool, setPaneToolsOwnId, setPaneToolsTuiProcess, waitForPaneCreatedOrError, writeTerminalPaneTool, } from '../agent/tools/pane.js';
23
23
  import { AGENT_CLIS, findAgentCli, nextPaneTitle, workspaceMcpProgram } from '../panes/agent_cli.js';
24
24
  import { TYPED_ENTER_DELAY_MS, formatAgentPaneMessage, openAgentPane } from '../panes/agent_panes.js';
25
+ import { MAX_REPLY_CAP, parseReplyMode, ReplyModeError } from '../panes/reply_modes.js';
25
26
  import { sessionNamePaneTitle } from '../panes/labels.js';
26
27
  import { MOTSI_PANE_ENV, remoteViewMotsi, throughMotsi } from '../panes/motsi.js';
27
28
  import { configStore } from '../config.js';
@@ -35,6 +36,35 @@ const PANE_REF = {
35
36
  description: 'The pane: its id, or its name as list_panes shows it.',
36
37
  anyOf: [{ type: 'integer', minimum: 0 }, { type: 'string', minLength: 1 }],
37
38
  };
39
+ /** send_message's reply_mode: how pane 0 answers this pane by itself in the exchange a message to it starts. */
40
+ const REPLY_MODE = {
41
+ description: 'For a message to pane 0: how pane 0 answers you by itself in the exchange this message starts, the run of '
42
+ + 'answers back and forth between you and pane 0. "uncapped": it answers every message. {"capped": N} (N from 1 to '
43
+ + `${MAX_REPLY_CAP}): it answers N times with no message from the person in pane 0, says so in the last answer ("no more automatic `
44
+ + 'answers in this exchange"), then holds your messages for the person until their next message in pane 0, or until you send '
45
+ + 'a different reply_mode. {"arbitrator": NAME}: before each answer after the first, pane 0 asks the arbitrator whether the '
46
+ + 'exchange should go on, and shows each decision; NAME is "model" (a model on pane 0\'s own route) or an arbitrator the '
47
+ + 'person set up in ZTC\'s /settings, and any other name is refused; the arbitrator\'s timeout, error or unreadable answer '
48
+ + 'stops the exchange. Omitted: the person\'s default (/settings → Panes → Agent reply mode; capped at 5 unless they '
49
+ + 'changed it). The mode holds for the exchange: the person\'s message in pane 0 starts its count again, and only the pane '
50
+ + 'that starts an exchange sets its mode, so once pane 0 has started one with you, yours is not applied and the answer '
51
+ + 'says so. Repeating the same mode changes nothing.',
52
+ anyOf: [
53
+ { type: 'string', enum: ['uncapped'] },
54
+ {
55
+ type: 'object',
56
+ properties: { capped: { type: 'integer', minimum: 1, maximum: MAX_REPLY_CAP } },
57
+ required: ['capped'],
58
+ additionalProperties: false,
59
+ },
60
+ {
61
+ type: 'object',
62
+ properties: { arbitrator: { type: 'string', minLength: 1, description: '"model", or the name of an arbitrator the person set up.' } },
63
+ required: ['arbitrator'],
64
+ additionalProperties: false,
65
+ },
66
+ ],
67
+ };
38
68
  const TOOLS = [
39
69
  {
40
70
  name: 'list_panes',
@@ -90,12 +120,13 @@ const TOOLS = [
90
120
  },
91
121
  {
92
122
  name: 'send_message',
93
- description: 'Send a message to another pane\'s agent, or "all" for every ZTC agent. ZTC agents receive it as a message from you; Claude Code and Codex panes see it typed in with your pane\'s name. Replies come back to you the same way: typed into your input, starting "[Message from …]".',
123
+ description: 'Send a message to another pane\'s agent, or "all" for every ZTC agent. ZTC agents receive it as a message from you; Claude Code and Codex panes see it typed in with your pane\'s name. Replies come back to you typed into your input. Pane 0, the ZTC that runs this workspace, answers a message you send it once it has finished the work on it: "[Answer from …]" followed by its answer (cut short when it is long, ending with the read_pane of pane 0 that shows it whole), or what stopped it or keeps it waiting. Other replies start "[Message from …]". How often pane 0 answers you by itself in a row is the exchange\'s reply_mode, which the pane that starts the exchange chooses: capped at 5 answers unless you or the person choose otherwise.',
94
124
  inputSchema: {
95
125
  type: 'object',
96
126
  properties: {
97
127
  to: { description: 'A pane id or name, or "all".', anyOf: [{ type: 'integer', minimum: 0 }, { type: 'string', minLength: 1 }] },
98
128
  text: { type: 'string', minLength: 1 },
129
+ reply_mode: REPLY_MODE,
99
130
  },
100
131
  required: ['to', 'text'],
101
132
  additionalProperties: false,
@@ -103,7 +134,7 @@ const TOOLS = [
103
134
  },
104
135
  {
105
136
  name: 'close_pane',
106
- description: 'Close a pane and stop its program. Your own pane and Main (pane 0) cannot be closed this way.',
137
+ description: 'Close a pane and stop its program. Your own pane and pane 0, ZTC\'s Main, cannot be closed this way.',
107
138
  inputSchema: { type: 'object', properties: { pane: PANE_REF }, required: ['pane'], additionalProperties: false },
108
139
  },
109
140
  ];
@@ -361,24 +392,46 @@ export function createWorkspaceMcpServer(options) {
361
392
  const text = String(args.text ?? '').trim();
362
393
  if (!text)
363
394
  throw new ToolError('text is required.');
395
+ let replyMode;
396
+ if (args.reply_mode !== undefined && args.reply_mode !== null) {
397
+ try {
398
+ replyMode = parseReplyMode(args.reply_mode);
399
+ }
400
+ catch (error) {
401
+ if (error instanceof ReplyModeError)
402
+ throw new ToolError(`The message wasn't sent: ${error.message}`);
403
+ throw error;
404
+ }
405
+ }
364
406
  const broadcast = typeof args.to === 'string' && args.to.trim().toLowerCase() === 'all';
365
407
  const target = broadcast ? null : await findPane(args.to);
408
+ // Only pane 0 answers this pane by itself, so a reply mode means something only on a message for it.
409
+ const forPaneZero = target?.id === 0;
410
+ const unapplied = replyMode !== undefined && !forPaneZero
411
+ ? ' Its reply_mode wasn\'t applied: only pane 0 answers you by itself, so a reply mode goes with a message for pane 0.' : '';
366
412
  // On the bus this pane speaks as itself, which its credential stands for; a server with no pane id has no bus.
367
413
  if (options.bus && ownPaneId !== null) {
368
414
  const from = { id: ownPaneId, name: await ownName() };
369
- await options.bus.send({ from, to: target ? target.id : 'all', type: 'ztc_message', text });
370
- return target ? `Message sent to ${paneName(target)} (pane ${target.id}).` : 'Message sent to every ZTC agent.';
415
+ const sent = await options.bus.send({ from, to: target ? target.id : 'all', type: 'ztc_message', text,
416
+ ...(replyMode !== undefined && forPaneZero ? { replyMode } : {}) });
417
+ const said = sent?.replyNotice ? ` ${sent.replyNotice}` : '';
418
+ // A ZTC pane still starting gets it when it joins the bus.
419
+ if (sent?.held)
420
+ return `${sent.held}${said}${unapplied}`;
421
+ return `${target ? `Message sent to ${paneName(target)} (pane ${target.id}).` : 'Message sent to every ZTC agent.'}${said}${unapplied}`;
371
422
  }
372
423
  if (!target)
373
424
  throw new ToolError('Sending to "all" needs ZTC\'s message bus, which this pane cannot reach; send to one pane at a time.');
374
425
  const from = { id: ownPaneId ?? -1, name: await ownName() };
426
+ // Pane 0 takes no typed message (writeTerminalPaneTool refuses it, saying to use send_message), so off the bus a
427
+ // reply mode never reaches it.
375
428
  await typeInto(target, formatAgentPaneMessage({ from, text }), true);
376
- return `Message typed into ${paneName(target)} (pane ${target.id}).`;
429
+ return `Message typed into ${paneName(target)} (pane ${target.id}).${unapplied}`;
377
430
  },
378
431
  close_pane: async (args) => {
379
432
  const pane = await findPane(args.pane);
380
433
  if (pane.id === 0)
381
- throw new ToolError('Main (pane 0) stays open while ZTC runs, so it can\'t be closed this way; the user quits ZTC to close it.');
434
+ throw new ToolError('Pane 0 is ZTC\'s Main, which stays open while ZTC runs, so it can\'t be closed this way; the user quits ZTC to close it.');
382
435
  if (pane.id === ownPaneId)
383
436
  throw new ToolError('That is your own pane; the user can close it, or you can exit.');
384
437
  return String(await closeTerminalPaneTool.execute({ pane_id: pane.id }));
@@ -428,8 +481,22 @@ export function mirrorBusSender(env = process.env) {
428
481
  let text = '';
429
482
  res.on('data', (chunk) => { text += chunk.toString(); });
430
483
  res.on('end', () => {
431
- if (res.statusCode === 200)
432
- resolve();
484
+ let answer = {};
485
+ try {
486
+ answer = JSON.parse(text) ?? {};
487
+ }
488
+ catch { /* not the mirror's JSON */ }
489
+ // What pane 0 said of the message's reply mode, or of the exchange it is in, goes with a delivered or held one.
490
+ const said = typeof answer.replyNotice === 'string' && answer.replyNotice ? { replyNotice: answer.replyNotice } : {};
491
+ if (res.statusCode === 200) {
492
+ resolve(said.replyNotice ? said : undefined);
493
+ return;
494
+ }
495
+ // Held for a ZTC pane still starting, or refused: the mirror's words say which.
496
+ if (res.statusCode === 202 && answer.held === true && typeof answer.notice === 'string')
497
+ resolve({ held: answer.notice, ...said });
498
+ else if (typeof answer.error === 'string' && answer.error)
499
+ reject(new ToolError(`ZTC's message bus refused the message: ${answer.error}`));
433
500
  else
434
501
  reject(new ToolError(`ZTC's message bus refused the message (HTTP ${res.statusCode}): ${text.slice(0, 200)}`));
435
502
  });
@@ -69,6 +69,62 @@ export interface AgentLaunchRequest {
69
69
  * apostrophes and all (`/claude don't touch the migrations`).
70
70
  */
71
71
  export declare function parseAgentCommandBody(body: string): AgentLaunchRequest;
72
+ /** A session id as Claude Code and Codex write them: a canonical 8-4-4-4-12 hex UUID. */
73
+ export declare function isSessionId(value: string): boolean;
74
+ /** Resume a session as it is, or fork it: copy it into a new one. */
75
+ export type AgentResumeMode = 'resume' | 'fork';
76
+ /**
77
+ * What `/claude` and `/codex` were asked: a launch as before, the sessions picker, one session by id, the most recent
78
+ * session in this folder, a session by name (passed to the CLI), or a resume form ZTC can't read.
79
+ */
80
+ export type AgentCommand = {
81
+ kind: 'launch';
82
+ request: AgentLaunchRequest;
83
+ } | {
84
+ kind: 'picker';
85
+ mode: AgentResumeMode;
86
+ all: boolean;
87
+ here: boolean;
88
+ prompt?: string;
89
+ profile?: string;
90
+ } | {
91
+ kind: 'session';
92
+ mode: AgentResumeMode;
93
+ id: string;
94
+ here: boolean;
95
+ prompt?: string;
96
+ profile?: string;
97
+ } | {
98
+ kind: 'continue';
99
+ prompt?: string;
100
+ profile?: string;
101
+ } | {
102
+ kind: 'name';
103
+ name: string;
104
+ prompt?: string;
105
+ profile?: string;
106
+ } | {
107
+ kind: 'error';
108
+ message: string;
109
+ };
110
+ /**
111
+ * Read the text after `/claude` or `/codex`, and a leading `@profile` as parseAgentCommandBody does.
112
+ *
113
+ * A first word of `resume`, `continue`, `fork`, `sessions` or `show-resumable` is a resume form when what follows is
114
+ * nothing, starts with an option, starts with a session id, or (for resume and fork) is one word with options: the
115
+ * words are split as the CLI's would be, up to a standalone `--`, and what follows that is the session's next prompt,
116
+ * kept as typed. Any other text after those words, such as two plain words ("resume the parser work") or words that
117
+ * don't split ("resume don't stop"), is the opening prompt, as before. A leading standalone `--` starts a fresh
118
+ * session with the rest as its prompt.
119
+ */
120
+ export declare function parseAgentCommand(cli: AgentCliId, body: string): AgentCommand;
121
+ /**
122
+ * The session id Claude Code's own `--resume <id>`, `-r <id>` or `--resume=<id>` names among the person's words,
123
+ * before any `--`, lowercase; null for none, for a name, and for `-r` alone (Claude Code's own picker).
124
+ */
125
+ export declare function claudeResumeFlagId(words: readonly string[]): string | null;
126
+ /** Whether the person's words for Claude Code, before any `--`, choose its session themselves (CLAUDE_SESSION_FLAGS). */
127
+ export declare function choosesClaudeSession(words: readonly string[]): boolean;
72
128
  /** Whether ZTC starts Claude Code and Codex without their permission prompts: `panes.agentPermissions`. */
73
129
  export type AgentPermissions = 'bypass' | 'ask';
74
130
  /** The flag that starts each CLI without asking before it runs commands (`claude --help` 2.1.322, `codex --help` 0.167.2). */
@@ -135,10 +191,11 @@ export declare function workspaceMcpArgs(id: AgentCliId, server: PaneProgram | n
135
191
  /**
136
192
  * The CLI's full argument list. Codex takes its overrides first, before any
137
193
  * subcommand. Claude Code's `--mcp-config` takes several values, so it goes
138
- * after the user's flags, ahead of a `--` they typed, and a prompt follows its
139
- * own `--` so a prompt starting with "-" is never read as a flag.
194
+ * after the user's flags, ahead of a `--` they typed, then ZTC's own `after`
195
+ * (a fresh session's --session-id), and a prompt follows its own `--` so a
196
+ * prompt starting with "-" is never read as a flag.
140
197
  */
141
- export declare function agentCliArgs(id: AgentCliId, request: AgentLaunchRequest, server: PaneProgram | null): string[];
198
+ export declare function agentCliArgs(id: AgentCliId, request: AgentLaunchRequest, server: PaneProgram | null, after?: readonly string[]): string[];
142
199
  /**
143
200
  * Run the binary from a login shell, as custom panes are, so PATH and the rest
144
201
  * of the login environment apply. The binary and its arguments travel as
@@ -100,9 +100,18 @@ export class CliArgumentsError extends Error {
100
100
  * group, a backslash escapes, and `$`, backticks, globs and `;` stay literal.
101
101
  */
102
102
  export function splitCliArguments(raw) {
103
+ return scanCliWords(raw, false).words;
104
+ }
105
+ /**
106
+ * splitCliArguments' scanner. With `stopAtSeparator`, it stops at the first standalone `--` (unquoted, unescaped) and
107
+ * returns the raw text after it as `rest`, unread, so what follows can be kept exactly as typed.
108
+ */
109
+ function scanCliWords(raw, stopAtSeparator) {
103
110
  const words = [];
104
111
  let word = '';
105
112
  let inWord = false;
113
+ // Whether the word being read has a quote or an escape in it: such a `--` is a word, never the separator.
114
+ let literal = false;
106
115
  let quote = null;
107
116
  for (let i = 0; i < raw.length; i++) {
108
117
  const char = raw[i];
@@ -130,8 +139,10 @@ export function splitCliArguments(raw) {
130
139
  if (char === "'" || char === '"') {
131
140
  quote = char;
132
141
  inWord = true;
142
+ literal = true;
133
143
  }
134
144
  else if (char === '\\') {
145
+ literal = true;
135
146
  if (i + 1 >= raw.length) {
136
147
  word += char;
137
148
  inWord = true;
@@ -146,10 +157,13 @@ export function splitCliArguments(raw) {
146
157
  }
147
158
  else if (/\s/.test(char)) {
148
159
  if (inWord) {
160
+ if (stopAtSeparator && !literal && word === '--')
161
+ return { words, rest: raw.slice(i) };
149
162
  words.push(word);
150
163
  word = '';
151
164
  inWord = false;
152
165
  }
166
+ literal = false;
153
167
  }
154
168
  else {
155
169
  word += char;
@@ -159,9 +173,12 @@ export function splitCliArguments(raw) {
159
173
  if (quote) {
160
174
  throw new CliArgumentsError(`Unclosed ${quote === '"' ? 'double' : 'single'} quote in the arguments.`);
161
175
  }
162
- if (inWord)
176
+ if (inWord) {
177
+ if (stopAtSeparator && !literal && word === '--')
178
+ return { words, rest: '' };
163
179
  words.push(word);
164
- return words;
180
+ }
181
+ return { words };
165
182
  }
166
183
  /** Words as a shell would accept them back: quoted only where needed. */
167
184
  export function formatCliArguments(words) {
@@ -177,16 +194,7 @@ export function formatCliArguments(words) {
177
194
  * apostrophes and all (`/claude don't touch the migrations`).
178
195
  */
179
196
  export function parseAgentCommandBody(body) {
180
- let text = body.trim();
181
- let profile;
182
- const named = /^@(\S+)(?:\s+|$)/.exec(text);
183
- if (named) {
184
- profile = named[1];
185
- if (!isProfileName(profile)) {
186
- throw new CliArgumentsError(`"${profile}" is not a profile name: use letters, digits, ".", "_" or "-", up to 32.`);
187
- }
188
- text = text.slice(named[0].length).trim();
189
- }
197
+ const { profile, text } = splitProfile(body);
190
198
  const withProfile = (request) => (profile ? { ...request, profile } : request);
191
199
  if (!text)
192
200
  return withProfile({ words: [] });
@@ -194,6 +202,150 @@ export function parseAgentCommandBody(body) {
194
202
  return withProfile({ words: splitCliArguments(text) });
195
203
  return withProfile({ words: [], prompt: text });
196
204
  }
205
+ /** A leading `@name` (a ZTC sign-in profile), and the text after it, trimmed. */
206
+ function splitProfile(body) {
207
+ const text = body.trim();
208
+ const named = /^@(\S+)(?:\s+|$)/.exec(text);
209
+ if (!named)
210
+ return { text };
211
+ const profile = named[1];
212
+ if (!isProfileName(profile)) {
213
+ throw new CliArgumentsError(`"${profile}" is not a profile name: use letters, digits, ".", "_" or "-", up to 32.`);
214
+ }
215
+ return { profile, text: text.slice(named[0].length).trim() };
216
+ }
217
+ // ── Resuming sessions ───────────────────────────────────────────────────────
218
+ /** A session id as Claude Code (v4) and Codex (v7) write them: a canonical 8-4-4-4-12 hex UUID, in either case. */
219
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
220
+ /** A session id as Claude Code and Codex write them: a canonical 8-4-4-4-12 hex UUID. */
221
+ export function isSessionId(value) {
222
+ return SESSION_ID.test(value);
223
+ }
224
+ /** Each resume word's options; anything else is an error that names the forms. */
225
+ const RESUME_OPTIONS = Object.freeze({
226
+ resume: ['--all', '--here', '--last'],
227
+ fork: ['--all', '--here'],
228
+ continue: [],
229
+ sessions: ['--all'],
230
+ 'show-resumable': ['--all'],
231
+ });
232
+ function isResumeWord(word) {
233
+ return Object.hasOwn(RESUME_OPTIONS, word);
234
+ }
235
+ /** What a resume word takes, said when it is given something else. */
236
+ function resumeFormsError(cli, word) {
237
+ const own = cli === 'claude'
238
+ ? `for Claude Code's own flags use /claude --resume <id> …`
239
+ : `for Codex's own flags, start with them: /codex -m <model> …`;
240
+ const forms = {
241
+ resume: `takes a session id, --all, --here, --last and -- <prompt>; ${own}`,
242
+ fork: 'takes a session id, --all, --here and -- <prompt>.',
243
+ continue: 'takes only -- <prompt>.',
244
+ sessions: 'takes only --all.',
245
+ 'show-resumable': 'takes only --all.',
246
+ };
247
+ return { kind: 'error', message: `/${cli} ${word} ${forms[word]}` };
248
+ }
249
+ /**
250
+ * Read the text after `/claude` or `/codex`, and a leading `@profile` as parseAgentCommandBody does.
251
+ *
252
+ * A first word of `resume`, `continue`, `fork`, `sessions` or `show-resumable` is a resume form when what follows is
253
+ * nothing, starts with an option, starts with a session id, or (for resume and fork) is one word with options: the
254
+ * words are split as the CLI's would be, up to a standalone `--`, and what follows that is the session's next prompt,
255
+ * kept as typed. Any other text after those words, such as two plain words ("resume the parser work") or words that
256
+ * don't split ("resume don't stop"), is the opening prompt, as before. A leading standalone `--` starts a fresh
257
+ * session with the rest as its prompt.
258
+ */
259
+ export function parseAgentCommand(cli, body) {
260
+ const today = () => ({ kind: 'launch', request: parseAgentCommandBody(body) });
261
+ const { profile, text } = splitProfile(body);
262
+ const withProfile = (value) => (profile ? { ...value, profile } : value);
263
+ if (text === '--' || /^--\s/.test(text)) {
264
+ const prompt = text.slice(2).trim();
265
+ return { kind: 'launch', request: withProfile(prompt ? { words: [], prompt } : { words: [] }) };
266
+ }
267
+ const word = /^\S+/.exec(text)?.[0] ?? '';
268
+ if (!isResumeWord(word))
269
+ return today();
270
+ let scanned;
271
+ try {
272
+ scanned = scanCliWords(text.slice(word.length), true);
273
+ }
274
+ catch {
275
+ return today();
276
+ }
277
+ const { words } = scanned;
278
+ const positional = words.filter(item => !item.startsWith('-'));
279
+ const options = words.filter(item => item.startsWith('-'));
280
+ const resumeForm = words.length === 0 || words[0].startsWith('-') || isSessionId(words[0])
281
+ || ((word === 'resume' || word === 'fork') && positional.length === 1);
282
+ if (!resumeForm)
283
+ return today();
284
+ const prompt = scanned.rest?.trim();
285
+ const withPrompt = (value) => withProfile(prompt ? { ...value, prompt } : value);
286
+ if (options.some(option => !RESUME_OPTIONS[word].includes(option)) || positional.length > 1)
287
+ return resumeFormsError(cli, word);
288
+ const all = options.includes('--all');
289
+ const here = options.includes('--here');
290
+ const target = positional[0];
291
+ switch (word) {
292
+ case 'continue':
293
+ return target === undefined ? withPrompt({ kind: 'continue' }) : resumeFormsError(cli, word);
294
+ case 'sessions':
295
+ case 'show-resumable':
296
+ if (target !== undefined || scanned.rest !== undefined)
297
+ return resumeFormsError(cli, word);
298
+ return withProfile({ kind: 'picker', mode: 'resume', all, here: false });
299
+ case 'resume':
300
+ if (options.includes('--last'))
301
+ return target === undefined ? withPrompt({ kind: 'continue' }) : resumeFormsError(cli, word);
302
+ if (target === undefined)
303
+ return withPrompt({ kind: 'picker', mode: 'resume', all, here });
304
+ if (isSessionId(target))
305
+ return withPrompt({ kind: 'session', mode: 'resume', id: target.toLowerCase(), here });
306
+ return withPrompt({ kind: 'name', name: target });
307
+ case 'fork':
308
+ if (target === undefined)
309
+ return withPrompt({ kind: 'picker', mode: 'fork', all, here });
310
+ if (!isSessionId(target))
311
+ return resumeFormsError(cli, word);
312
+ return withPrompt({ kind: 'session', mode: 'fork', id: target.toLowerCase(), here });
313
+ }
314
+ }
315
+ /**
316
+ * The session id Claude Code's own `--resume <id>`, `-r <id>` or `--resume=<id>` names among the person's words,
317
+ * before any `--`, lowercase; null for none, for a name, and for `-r` alone (Claude Code's own picker).
318
+ */
319
+ export function claudeResumeFlagId(words) {
320
+ for (let i = 0; i < words.length; i++) {
321
+ const word = words[i];
322
+ if (word === '--')
323
+ return null;
324
+ const value = word === '--resume' || word === '-r' ? words[i + 1]
325
+ : word.startsWith('--resume=') ? word.slice('--resume='.length) : undefined;
326
+ if (value !== undefined)
327
+ return isSessionId(value) ? value.toLowerCase() : null;
328
+ }
329
+ return null;
330
+ }
331
+ /**
332
+ * Claude Code's flags that choose the session it runs (`claude --help` 2.1.325, cli-reference): continuing,
333
+ * resuming, forking or naming one, a cloud session, a pull request's picker, and print mode, whose sessions are no
334
+ * pane's. A fresh session ZTC starts without them is given its id (openAgentPane), so the pane holding it is known.
335
+ */
336
+ const CLAUDE_SESSION_FLAGS = new Set([
337
+ '--continue', '-c', '--resume', '-r', '--session-id', '--fork-session', '--teleport', '--from-pr', '-p', '--print', '--no-session-persistence',
338
+ ]);
339
+ /** Whether the person's words for Claude Code, before any `--`, choose its session themselves (CLAUDE_SESSION_FLAGS). */
340
+ export function choosesClaudeSession(words) {
341
+ for (const word of words) {
342
+ if (word === '--')
343
+ return false;
344
+ if (CLAUDE_SESSION_FLAGS.has(word.startsWith('--') ? word.split('=', 1)[0] : word))
345
+ return true;
346
+ }
347
+ return false;
348
+ }
197
349
  /** The flag that starts each CLI without asking before it runs commands (`claude --help` 2.1.322, `codex --help` 0.167.2). */
198
350
  export const PERMISSION_BYPASS_FLAGS = Object.freeze({
199
351
  claude: '--dangerously-skip-permissions',
@@ -383,11 +535,12 @@ export function workspaceMcpArgs(id, server) {
383
535
  /**
384
536
  * The CLI's full argument list. Codex takes its overrides first, before any
385
537
  * subcommand. Claude Code's `--mcp-config` takes several values, so it goes
386
- * after the user's flags, ahead of a `--` they typed, and a prompt follows its
387
- * own `--` so a prompt starting with "-" is never read as a flag.
538
+ * after the user's flags, ahead of a `--` they typed, then ZTC's own `after`
539
+ * (a fresh session's --session-id), and a prompt follows its own `--` so a
540
+ * prompt starting with "-" is never read as a flag.
388
541
  */
389
- export function agentCliArgs(id, request, server) {
390
- const attach = workspaceMcpArgs(id, server);
542
+ export function agentCliArgs(id, request, server, after = []) {
543
+ const attach = [...workspaceMcpArgs(id, server), ...after];
391
544
  const prompt = request.prompt?.trim() ? ['--', request.prompt] : [];
392
545
  if (id === 'codex')
393
546
  return [...attach, ...request.words, ...prompt];
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Which Claude Code or Codex session each agent pane holds, from the command line it was started with, so a session
3
+ * already open in a ZTC pane is gone to rather than opened twice: two CLIs writing one session would interleave it.
4
+ *
5
+ * Only what ZTC can read off the pane's own launch counts: Claude Code's `--session-id <id>` (which ZTC gives every
6
+ * fork it opens) or `--resume <id>` without `--fork-session`, and Codex's `resume <id>`. A fresh session's id, or a
7
+ * Codex fork's, is the CLI's own to choose, so such a pane holds nothing ZTC knows of.
8
+ */
9
+ import type { PaneCommandTransport } from '../ui/ratatui/pane_relay.js';
10
+ import { type AgentCliId } from './agent_cli.js';
11
+ /** The session a pane started with these words holds, if they say. */
12
+ export declare function agentPaneSession(command: string | undefined, args: readonly string[] | undefined): {
13
+ cli: AgentCliId;
14
+ id: string;
15
+ } | null;
16
+ /**
17
+ * The panes holding a Claude Code or Codex session, by `<cli>:<id>`, from the renderer's session state (each pane with
18
+ * the command it runs). Only a pane whose program runs holds one: not one the renderer restored without running it
19
+ * ("Not started", its saved command kept), nor one its list of panes says isn't alive, its CLI having exited. Empty
20
+ * without panes, or when the renderer doesn't answer in time.
21
+ */
22
+ export declare function openAgentSessionPanes(transport: PaneCommandTransport | null, timeoutMs?: number): Promise<Map<string, number>>;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Which Claude Code or Codex session each agent pane holds, from the command line it was started with, so a session
3
+ * already open in a ZTC pane is gone to rather than opened twice: two CLIs writing one session would interleave it.
4
+ *
5
+ * Only what ZTC can read off the pane's own launch counts: Claude Code's `--session-id <id>` (which ZTC gives every
6
+ * fork it opens) or `--resume <id>` without `--fork-session`, and Codex's `resume <id>`. A fresh session's id, or a
7
+ * Codex fork's, is the CLI's own to choose, so such a pane holds nothing ZTC knows of.
8
+ */
9
+ import { basename } from 'node:path';
10
+ import { claudeResumeFlagId, isSessionId } from './agent_cli.js';
11
+ /** The launchers' names, as a pane's command line names them (through a login shell or `motsi run` or not). */
12
+ const LAUNCHERS = new Map([
13
+ ['claude', 'claude'], ['claude.exe', 'claude'], ['codex', 'codex'], ['codex.exe', 'codex'],
14
+ ]);
15
+ /** Codex's options that take the next word as their value, among those before a subcommand. */
16
+ const CODEX_VALUE_OPTIONS = new Set([
17
+ '-c', '--config', '-C', '--cd', '-m', '--model', '-p', '--profile', '-s', '--sandbox', '-a', '--ask-for-approval', '-i', '--image',
18
+ '--add-dir', '--remote', '--local-provider', '-e', '--enable', '--disable',
19
+ ]);
20
+ function claudeSession(words) {
21
+ let session = null;
22
+ let fork = false;
23
+ for (let i = 0; i < words.length; i++) {
24
+ const word = words[i];
25
+ if (word === '--')
26
+ break;
27
+ if (word === '--fork-session')
28
+ fork = true;
29
+ const value = word === '--session-id' ? words[i + 1] : word.startsWith('--session-id=') ? word.slice('--session-id='.length) : undefined;
30
+ if (value !== undefined && isSessionId(value))
31
+ session = value.toLowerCase();
32
+ }
33
+ if (session)
34
+ return session;
35
+ const resumed = claudeResumeFlagId(words);
36
+ return resumed && !fork ? resumed : null;
37
+ }
38
+ function codexSession(words) {
39
+ for (let i = 0; i < words.length; i++) {
40
+ const word = words[i];
41
+ if (CODEX_VALUE_OPTIONS.has(word)) {
42
+ i++;
43
+ continue;
44
+ }
45
+ if (word.startsWith('-') && word !== '--')
46
+ continue;
47
+ // The first word that is no option: `resume <id>`, or another subcommand, `--` or a prompt.
48
+ const next = words[i + 1];
49
+ return word === 'resume' && next !== undefined && isSessionId(next) ? next.toLowerCase() : null;
50
+ }
51
+ return null;
52
+ }
53
+ /** The session a pane started with these words holds, if they say. */
54
+ export function agentPaneSession(command, args) {
55
+ const words = [command ?? '', ...(args ?? [])];
56
+ const at = words.findIndex(word => LAUNCHERS.has(basename(word)));
57
+ if (at === -1)
58
+ return null;
59
+ const cli = LAUNCHERS.get(basename(words[at]));
60
+ const rest = words.slice(at + 1);
61
+ const id = cli === 'claude' ? claudeSession(rest) : codexSession(rest);
62
+ return id ? { cli, id } : null;
63
+ }
64
+ /**
65
+ * The panes holding a Claude Code or Codex session, by `<cli>:<id>`, from the renderer's session state (each pane with
66
+ * the command it runs). Only a pane whose program runs holds one: not one the renderer restored without running it
67
+ * ("Not started", its saved command kept), nor one its list of panes says isn't alive, its CLI having exited. Empty
68
+ * without panes, or when the renderer doesn't answer in time.
69
+ */
70
+ export async function openAgentSessionPanes(transport, timeoutMs = 1500) {
71
+ const open = new Map();
72
+ if (!transport || !transport.isMuxMode)
73
+ return open;
74
+ // Asked together; a list that doesn't come in time leaves only the restored panes out.
75
+ const [state, listed] = await Promise.all([rendererAnswer(transport, { type: 'get_session_state' }, 'session_state', timeoutMs),
76
+ rendererAnswer(transport, { type: 'list_panes' }, 'pane_list', timeoutMs)]);
77
+ if (!state)
78
+ return open;
79
+ const stopped = new Set((listed?.panes ?? []).filter(pane => pane.is_alive === false).map(pane => pane.id));
80
+ for (const pane of state.state.panes ?? []) {
81
+ if (pane.restoration_status || stopped.has(pane.id))
82
+ continue;
83
+ const held = agentPaneSession(pane.command, pane.args);
84
+ const key = held ? `${held.cli}:${held.id}` : null;
85
+ if (key && !open.has(key))
86
+ open.set(key, pane.id);
87
+ }
88
+ return open;
89
+ }
90
+ /**
91
+ * The renderer's first event of type TYPE after COMMAND, or null when it refuses the command or sends none within
92
+ * TIMEOUT_MS; either way nothing is left listening.
93
+ */
94
+ function rendererAnswer(transport, command, type, timeoutMs) {
95
+ return new Promise(resolve => {
96
+ let settled = false;
97
+ const finish = (event) => {
98
+ if (settled)
99
+ return;
100
+ settled = true;
101
+ clearTimeout(timer);
102
+ unsubscribe();
103
+ resolve(event);
104
+ };
105
+ const unsubscribe = transport.on(event => { if (event.type === type)
106
+ finish(event); });
107
+ const timer = setTimeout(() => finish(null), timeoutMs);
108
+ if (!transport.send(command))
109
+ finish(null);
110
+ });
111
+ }