@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
@@ -0,0 +1,161 @@
1
+ /**
2
+ * What the head of a Codex rollout says about the session: its first session_meta line (id, folder, source, and
3
+ * whether it is a subagent's or attached to another thread) and the person's first request, as Codex's own session
4
+ * list previews it.
5
+ *
6
+ * The scanner reads bytes as they come, in any chunks, line by line. A line longer than CODEX_LINE_BYTES is skipped
7
+ * without being kept or parsed: Codex's world state and tool output run to megabytes, and no such line is ever a
8
+ * folder or a title. Nothing here throws, whatever the bytes.
9
+ */
10
+ import { CODEX_LINE_BYTES } from './limits.js';
11
+ /** What Codex puts before the person's words in a legacy request (codex-rs protocol's USER_MESSAGE_BEGIN). */
12
+ const USER_MESSAGE_BEGIN = '## My request for Codex:';
13
+ function isRecord(value) {
14
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
15
+ }
16
+ function hasItems(value) {
17
+ return Array.isArray(value) && value.length > 0;
18
+ }
19
+ /** Codex's preview of a request: the words after its prefix, else "[Image]" or "[Audio]" for one without words. */
20
+ function preview(message, image, audio) {
21
+ const at = message.indexOf(USER_MESSAGE_BEGIN);
22
+ const text = (at === -1 ? message : message.slice(at + USER_MESSAGE_BEGIN.length)).trim();
23
+ if (text)
24
+ return text;
25
+ if (image)
26
+ return '[Image]';
27
+ if (audio)
28
+ return '[Audio]';
29
+ return null;
30
+ }
31
+ /** The request an event_msg records: a legacy user_message, or a paginated rollout's completed UserMessage item. */
32
+ function eventRequest(payload) {
33
+ if (payload.type === 'user_message') {
34
+ return preview(typeof payload.message === 'string' ? payload.message : '', hasItems(payload.images) || hasItems(payload.local_images) || hasItems(payload.file_ids), hasItems(payload.audio) || hasItems(payload.local_audio) || hasItems(payload.audio_references));
35
+ }
36
+ if (payload.type !== 'item_completed' || !isRecord(payload.item) || payload.item.type !== 'UserMessage')
37
+ return null;
38
+ const content = Array.isArray(payload.item.content) ? payload.item.content : [];
39
+ let text = '';
40
+ let image = false;
41
+ let audio = false;
42
+ for (const input of content) {
43
+ if (!isRecord(input))
44
+ continue;
45
+ if (input.type === 'text' && typeof input.text === 'string')
46
+ text += input.text;
47
+ else if (input.type === 'image' || input.type === 'local_image')
48
+ image = true;
49
+ else if (input.type === 'audio' || input.type === 'local_audio')
50
+ audio = true;
51
+ }
52
+ return preview(text, image, audio);
53
+ }
54
+ /** Reads a rollout's bytes as they come, in any chunks. */
55
+ export class CodexHeadScanner {
56
+ lineBytes;
57
+ line = [];
58
+ lineLength = 0;
59
+ oversized = false;
60
+ head = { sawMeta: false, attached: false };
61
+ metaOnly;
62
+ /** `metaOnly`: done once the session_meta line is read, for a caller that wants only the session's folder. */
63
+ constructor(options = {}) {
64
+ this.lineBytes = options.lineBytes ?? CODEX_LINE_BYTES;
65
+ this.metaOnly = options.metaOnly === true;
66
+ }
67
+ /**
68
+ * True once the head holds everything a row needs, so no more bytes are wanted: the folder and the first request, or
69
+ * a session_meta that rules the session out of the picker (its folder is all a lookup by id still needs).
70
+ */
71
+ get done() {
72
+ return this.head.sawMeta && (this.metaOnly || this.head.firstRequest !== undefined || !codexSessionListable(this.head));
73
+ }
74
+ push(chunk) {
75
+ let start = 0;
76
+ while (!this.done && start < chunk.length) {
77
+ const newline = chunk.indexOf(0x0a, start);
78
+ this.append(chunk.subarray(start, newline === -1 ? chunk.length : newline));
79
+ if (newline === -1)
80
+ return;
81
+ this.finishLine();
82
+ start = newline + 1;
83
+ }
84
+ }
85
+ /** The head so far; `whole` when the bytes were the whole file, so a last line without a newline is complete. */
86
+ end(whole) {
87
+ if (whole && !this.done)
88
+ this.finishLine();
89
+ this.line = [];
90
+ this.lineLength = 0;
91
+ return { ...this.head };
92
+ }
93
+ append(part) {
94
+ if (this.oversized || part.length === 0)
95
+ return;
96
+ if (this.lineLength + part.length > this.lineBytes) {
97
+ this.oversized = true;
98
+ this.line = [];
99
+ this.lineLength = 0;
100
+ return;
101
+ }
102
+ this.line.push(Buffer.from(part));
103
+ this.lineLength += part.length;
104
+ }
105
+ finishLine() {
106
+ const text = !this.oversized && this.lineLength > 0 ? Buffer.concat(this.line).toString('utf8') : null;
107
+ this.line = [];
108
+ this.lineLength = 0;
109
+ this.oversized = false;
110
+ if (text !== null)
111
+ this.readLine(text);
112
+ }
113
+ readLine(text) {
114
+ let record;
115
+ try {
116
+ record = JSON.parse(text);
117
+ }
118
+ catch {
119
+ return;
120
+ }
121
+ if (!isRecord(record) || !isRecord(record.payload))
122
+ return;
123
+ const payload = record.payload;
124
+ if (record.type === 'session_meta') {
125
+ // Only the first: a fork's history copies its parent's session_meta after its own.
126
+ if (this.head.sawMeta)
127
+ return;
128
+ this.head.sawMeta = true;
129
+ if (typeof payload.id === 'string' && payload.id)
130
+ this.head.id = payload.id;
131
+ if (typeof payload.cwd === 'string' && payload.cwd)
132
+ this.head.cwd = payload.cwd;
133
+ if (payload.source !== undefined && payload.source !== null)
134
+ this.head.source = typeof payload.source === 'string' ? payload.source : 'other';
135
+ if (typeof payload.parent_thread_id === 'string' && payload.parent_thread_id)
136
+ this.head.parentThreadId = payload.parent_thread_id;
137
+ if (payload.attached_thread === true)
138
+ this.head.attached = true;
139
+ return;
140
+ }
141
+ if (record.type === 'event_msg' && this.head.firstRequest === undefined) {
142
+ const request = eventRequest(payload);
143
+ if (request !== null)
144
+ this.head.firstRequest = request;
145
+ }
146
+ }
147
+ }
148
+ /**
149
+ * Whether a session_meta leaves the session in the picker, as Codex's own list does: from the CLI or VS Code (or a
150
+ * rollout from before source was recorded), not a subagent's thread, and not attached to another.
151
+ */
152
+ export function codexSessionListable(head) {
153
+ const source = head.source;
154
+ return (source === undefined || source === 'cli' || source === 'vscode') && !head.parentThreadId && !head.attached;
155
+ }
156
+ /** The head of a rollout from its first bytes. */
157
+ export function parseCodexSessionHead(bytes, whole) {
158
+ const scanner = new CodexHeadScanner();
159
+ scanner.push(bytes);
160
+ return scanner.end(whole);
161
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Codex's sessions in a store: `sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl`, each read from its first megabyte at
3
+ * most, and only until its head has the folder and the first request; names come from the last 256 KiB of the
4
+ * store's `session_index.jsonl`, the newest entry for an id winning. `archived_sessions/` is never looked in, and
5
+ * nothing else in the store is read.
6
+ */
7
+ import { type CandidateRead, type ScanOptions } from './scan.js';
8
+ import { type SessionStoreFs } from './store_fs.js';
9
+ import type { AgentSessionStore } from './stores.js';
10
+ import type { AgentSessionRow, SessionCandidate, SessionListing } from './types.js';
11
+ export interface CodexListOptions extends ScanOptions {
12
+ fs?: SessionStoreFs;
13
+ /** Heads read at most (default HEAD_READS_PER_OPEN). */
14
+ maxReads?: number;
15
+ }
16
+ /**
17
+ * A rollout's row from its head, read in chunks until the head has the session's folder and first request, or to
18
+ * CODEX_HEAD_BYTES. The picker leaves out what Codex's own does: a source other than the CLI or VS Code, a subagent's
19
+ * thread, one attached to another, and a rollout read whole with no request of the person's; they are still found by
20
+ * id.
21
+ */
22
+ export declare function readCodexCandidate(candidate: SessionCandidate, fs?: SessionStoreFs, names?: ReadonlyMap<string, string>, options?: {
23
+ metaOnly?: boolean;
24
+ }): Promise<CandidateRead>;
25
+ /** The Codex sessions in these stores, newest first, from the heads of the newest `maxReads` rollouts. */
26
+ export declare function listCodexSessions(stores: readonly AgentSessionStore[], options?: CodexListOptions): Promise<SessionListing>;
27
+ /** The ids of the sessions in these stores whose ids start with `start` (lowercase), each once; nothing is opened. */
28
+ export declare function codexSessionIdsStarting(stores: readonly AgentSessionStore[], start: string, fs?: SessionStoreFs): Promise<string[]>;
29
+ /**
30
+ * This folder's latest session, for continue: the newest of the newest HEAD_READS_PER_OPEN rollouts whose session_meta
31
+ * names one of `folders` and leaves it in the picker, read to its first line, then to its first request to make sure
32
+ * it has one. Null when none does.
33
+ */
34
+ export declare function latestCodexSessionIn(stores: readonly AgentSessionStore[], folders: readonly string[], fs?: SessionStoreFs): Promise<AgentSessionRow | null>;
35
+ /** The links among a store's year, month and day folders, which are never followed; nothing is opened. */
36
+ export declare function codexFolderLinks(store: AgentSessionStore, fs?: SessionStoreFs): Promise<string[]>;
37
+ /**
38
+ * The session with this id in each store that holds it, from its newest rollout there: the day folders are listed
39
+ * by name, and only the one rollout found in a store is opened.
40
+ */
41
+ export declare function findCodexSession(stores: readonly AgentSessionStore[], id: string, options?: {
42
+ fs?: SessionStoreFs;
43
+ }): Promise<AgentSessionRow[]>;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Codex's sessions in a store: `sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl`, each read from its first megabyte at
3
+ * most, and only until its head has the folder and the first request; names come from the last 256 KiB of the
4
+ * store's `session_index.jsonl`, the newest entry for an id winning. `archived_sessions/` is never looked in, and
5
+ * nothing else in the store is read.
6
+ */
7
+ import { join } from 'node:path';
8
+ import { isSessionId } from '../agent_cli.js';
9
+ import { CodexHeadScanner, codexSessionListable } from './codex_head.js';
10
+ import { CODEX_HEAD_BYTES, CODEX_INDEX_TAIL_BYTES, HEAD_READS_PER_OPEN } from './limits.js';
11
+ import { byRecency, chooseReads, readInOrder } from './scan.js';
12
+ import { nodeSessionStoreFs, readFileTail } from './store_fs.js';
13
+ import { sessionTitle } from './title.js';
14
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
15
+ /** `rollout-YYYY-MM-DDThh-mm-ss-<thread id>[_<rollout id>].jsonl`, as codex-rs's rollout_file_name renders it. */
16
+ const ROLLOUT = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_${UUID})?\\.jsonl$`, 'i');
17
+ /** The year, month and day folders rollouts are kept in. */
18
+ const DATE_FOLDERS = [/^\d{4}$/, /^\d{2}$/, /^\d{2}$/];
19
+ /** Bytes read at a time from a rollout. */
20
+ const CHUNK_BYTES = 64 * 1024;
21
+ /**
22
+ * The rollouts of a store, by name and modification time, that `wanted` keeps; nothing is opened. A year, month or day
23
+ * folder that is a symbolic link is never followed: `onLink` hears of it.
24
+ */
25
+ async function rolloutCandidates(store, fs, wanted = () => true, onLink = () => { }) {
26
+ const found = [];
27
+ const walk = async (dir, depth) => {
28
+ const entries = await fs.list(dir);
29
+ await Promise.all(entries.map(async (entry) => {
30
+ const path = join(dir, entry.name);
31
+ if (entry.kind === 'directory' || entry.kind === 'link') {
32
+ if (depth >= DATE_FOLDERS.length || !DATE_FOLDERS[depth].test(entry.name))
33
+ return;
34
+ if (entry.kind === 'link')
35
+ onLink(path);
36
+ else
37
+ await walk(path, depth + 1);
38
+ return;
39
+ }
40
+ const id = entry.kind === 'file' ? ROLLOUT.exec(entry.name)?.[1]?.toLowerCase() : undefined;
41
+ if (!id || !wanted(id))
42
+ return;
43
+ const info = await fs.lstat(path);
44
+ if (info?.kind !== 'file')
45
+ return;
46
+ found.push({ cli: 'codex', id, path, profile: store.profile, mtimeMs: info.mtimeMs, group: '' });
47
+ }));
48
+ };
49
+ await walk(store.sessionsDir, 0);
50
+ return found;
51
+ }
52
+ /** The names given to sessions, from the end of the store's session_index.jsonl: the newest entry for each id. */
53
+ async function sessionNames(store, fs) {
54
+ const names = new Map();
55
+ const tail = await readFileTail(fs, join(store.configDir, 'session_index.jsonl'), CODEX_INDEX_TAIL_BYTES);
56
+ if (!tail)
57
+ return names;
58
+ const lines = tail.bytes.toString('utf8').split('\n');
59
+ // A tail that isn't the whole file starts inside a line.
60
+ if (!tail.whole)
61
+ lines.shift();
62
+ for (const line of lines) {
63
+ let entry;
64
+ try {
65
+ entry = JSON.parse(line);
66
+ }
67
+ catch {
68
+ continue;
69
+ }
70
+ if (typeof entry !== 'object' || entry === null)
71
+ continue;
72
+ const { id, thread_name: name } = entry;
73
+ if (typeof id === 'string' && typeof name === 'string')
74
+ names.set(id.toLowerCase(), name);
75
+ }
76
+ return names;
77
+ }
78
+ /**
79
+ * A rollout's row from its head, read in chunks until the head has the session's folder and first request, or to
80
+ * CODEX_HEAD_BYTES. The picker leaves out what Codex's own does: a source other than the CLI or VS Code, a subagent's
81
+ * thread, one attached to another, and a rollout read whole with no request of the person's; they are still found by
82
+ * id.
83
+ */
84
+ export async function readCodexCandidate(candidate, fs = nodeSessionStoreFs, names = new Map(), options = {}) {
85
+ const file = await fs.open(candidate.path);
86
+ if (!file)
87
+ return null;
88
+ const scanner = new CodexHeadScanner({ metaOnly: options.metaOnly === true });
89
+ let read = 0;
90
+ try {
91
+ const limit = Math.min(file.size, CODEX_HEAD_BYTES);
92
+ while (read < limit && !scanner.done) {
93
+ const chunk = await file.read(read, Math.min(CHUNK_BYTES, limit - read));
94
+ if (chunk.length === 0)
95
+ break;
96
+ scanner.push(chunk);
97
+ read += chunk.length;
98
+ }
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ finally {
104
+ await file.close().catch(() => { });
105
+ }
106
+ const whole = file.size <= CODEX_HEAD_BYTES && read >= file.size;
107
+ const head = scanner.end(whole);
108
+ const row = {
109
+ cli: 'codex',
110
+ id: candidate.id,
111
+ cwd: head.cwd ?? null,
112
+ folderVerified: head.cwd !== undefined,
113
+ mtimeMs: candidate.mtimeMs,
114
+ title: sessionTitle(names.get(candidate.id)) ?? sessionTitle(head.firstRequest),
115
+ profile: candidate.profile,
116
+ path: candidate.path,
117
+ };
118
+ const listed = head.sawMeta && codexSessionListable(head) && !(whole && head.firstRequest === undefined);
119
+ return { row, listed };
120
+ }
121
+ /** The Codex sessions in these stores, newest first, from the heads of the newest `maxReads` rollouts. */
122
+ export async function listCodexSessions(stores, options = {}) {
123
+ const fs = options.fs ?? nodeSessionStoreFs;
124
+ let links = 0;
125
+ const perStore = await Promise.all(stores.map(async (store) => {
126
+ const candidates = await rolloutCandidates(store, fs, () => true, () => { links += 1; });
127
+ return { store, candidates, names: candidates.length > 0 ? await sessionNames(store, fs) : new Map() };
128
+ }));
129
+ const names = new Map(perStore.map(entry => [entry.store.profile, entry.names]));
130
+ const candidates = perStore.flatMap(entry => entry.candidates);
131
+ const chosen = chooseReads(candidates, { maxReads: options.maxReads ?? HEAD_READS_PER_OPEN });
132
+ const scanned = await readInOrder(chosen, candidate => readCodexCandidate(candidate, fs, names.get(candidate.profile)), options);
133
+ return { ...scanned, older: candidates.length - chosen.length, links };
134
+ }
135
+ /** The ids of the sessions in these stores whose ids start with `start` (lowercase), each once; nothing is opened. */
136
+ export async function codexSessionIdsStarting(stores, start, fs = nodeSessionStoreFs) {
137
+ const ids = new Set();
138
+ for (const store of stores) {
139
+ for (const candidate of await rolloutCandidates(store, fs, id => id.startsWith(start)))
140
+ ids.add(candidate.id);
141
+ }
142
+ return [...ids].sort();
143
+ }
144
+ /**
145
+ * This folder's latest session, for continue: the newest of the newest HEAD_READS_PER_OPEN rollouts whose session_meta
146
+ * names one of `folders` and leaves it in the picker, read to its first line, then to its first request to make sure
147
+ * it has one. Null when none does.
148
+ */
149
+ export async function latestCodexSessionIn(stores, folders, fs = nodeSessionStoreFs) {
150
+ const wanted = new Set(folders.map(folder => folder.normalize('NFC')));
151
+ const candidates = (await Promise.all(stores.map(store => rolloutCandidates(store, fs)))).flat().sort(byRecency).slice(0, HEAD_READS_PER_OPEN);
152
+ for (const candidate of candidates) {
153
+ const meta = await readCodexCandidate(candidate, fs, new Map(), { metaOnly: true });
154
+ if (!meta || meta.row.cwd === null || !wanted.has(meta.row.cwd.normalize('NFC')))
155
+ continue;
156
+ const read = await readCodexCandidate(candidate, fs);
157
+ if (read?.listed)
158
+ return read.row;
159
+ }
160
+ return null;
161
+ }
162
+ /** The links among a store's year, month and day folders, which are never followed; nothing is opened. */
163
+ export async function codexFolderLinks(store, fs = nodeSessionStoreFs) {
164
+ const links = [];
165
+ await rolloutCandidates(store, fs, () => false, path => { links.push(path); });
166
+ return links;
167
+ }
168
+ /**
169
+ * The session with this id in each store that holds it, from its newest rollout there: the day folders are listed
170
+ * by name, and only the one rollout found in a store is opened.
171
+ */
172
+ export async function findCodexSession(stores, id, options = {}) {
173
+ if (!isSessionId(id))
174
+ return [];
175
+ const fs = options.fs ?? nodeSessionStoreFs;
176
+ const wanted = id.toLowerCase();
177
+ const rows = [];
178
+ for (const store of stores) {
179
+ const matches = (await rolloutCandidates(store, fs, candidate => candidate === wanted)).sort(byRecency);
180
+ if (matches.length === 0)
181
+ continue;
182
+ const read = await readCodexCandidate(matches[0], fs);
183
+ if (read)
184
+ rows.push(read.row);
185
+ }
186
+ return rows;
187
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The person's Claude Code and Codex sessions, for /claude and /codex in Main: looking one up by id, listing them for
3
+ * the picker, and what the messages about them name. Only Main has one (see CommandContext.agentSessions): what it
4
+ * reads is session metadata (each session's id, folder, last-active time and a title), from the head of each file,
5
+ * only when the person opens the picker or resumes, and it never leaves Main: no other pane, agent or mirror viewer
6
+ * reads Main's screen while the picker shows it (screen_privacy.ts), and nothing is sent anywhere (workspace spec §14).
7
+ */
8
+ import type { AgentCliId } from '../agent_cli.js';
9
+ import { type RegisteredProfileDirs } from '../agent_profiles.js';
10
+ import { type SessionStoreFs } from './store_fs.js';
11
+ import type { ResumeSignIn } from '../agent_resume.js';
12
+ import type { AgentSessionRow, SessionListing } from './types.js';
13
+ /** What the picker is opened for. */
14
+ export interface AgentSessionsPickerRequest {
15
+ mode: 'resume' | 'fork';
16
+ all: boolean;
17
+ here: boolean;
18
+ prompt?: string;
19
+ profile?: string;
20
+ }
21
+ export interface AgentSessionsController {
22
+ /**
23
+ * The home the stores and profiles are under, as given (HOME), never resolved: a profile's folder is passed to its
24
+ * CLI spelled as every other pane on it gets it, since Claude Code keys its Keychain entry to that folder as written.
25
+ */
26
+ readonly home: string;
27
+ /** That home's real path, for showing as ~/… the folders session files name, which the CLIs write resolved. */
28
+ readonly displayHome: string;
29
+ /** The CLI's own config folder and the names of the person's ZTC profiles for it, for messages. */
30
+ describeStores(cli: AgentCliId): {
31
+ ownDir: string;
32
+ profiles: string[];
33
+ };
34
+ /** The sign-in a resumed session starts on elsewhere: a profile's folder, or this computer's own when ZTC's env set it. */
35
+ signInFor(cli: AgentCliId, profile: string | null): ResumeSignIn;
36
+ /** The session with this id in each store that holds it; one whose file names no folder is this folder's (`cwd`) if it can be. */
37
+ find(cli: AgentCliId, id: string, options?: {
38
+ cwd?: string | null;
39
+ }): Promise<AgentSessionRow[]>;
40
+ /** The ids of the person's sessions that start with `start` (an id's first characters, as the picker shows them). */
41
+ matchIds(cli: AgentCliId, start: string): Promise<string[]>;
42
+ /**
43
+ * This folder's latest session the picker would list, for continue: across the stores, or only `profile`'s (null:
44
+ * this computer's own). Null when there is none, and the CLI's own continue is used.
45
+ */
46
+ latestHere(cli: AgentCliId, cwd: string, profile?: string | null): Promise<AgentSessionRow | null>;
47
+ /** The sessions to list, newest first, each as its file is read. */
48
+ list(cli: AgentCliId, options?: {
49
+ cwd?: string | null;
50
+ onRow?: (row: AgentSessionRow) => void;
51
+ }): Promise<SessionListing>;
52
+ /** The session folders ZTC doesn't follow because they are symbolic links: a store's own, or one inside it. */
53
+ linkedFolders(cli: AgentCliId): Promise<string[]>;
54
+ /**
55
+ * Whether a session's folder is there, asked off the event loop: false for one that isn't, isn't a folder, or doesn't
56
+ * answer within the deadline (FOLDER_CHECK_MS), as a sleeping NAS's or a dead mount's folder doesn't.
57
+ */
58
+ folderExists(path: string): Promise<boolean>;
59
+ /** Open the sessions picker in Main; absent where there is no picker to draw. */
60
+ openPicker?: (cli: AgentCliId, request: AgentSessionsPickerRequest) => void;
61
+ }
62
+ export interface AgentSessionsControllerOptions {
63
+ env?: NodeJS.ProcessEnv;
64
+ home?: string;
65
+ fs?: SessionStoreFs;
66
+ /** The profiles registered on folders of their own (panes.agentProfileDirs[cli]), read when needed. */
67
+ registered?: (cli: AgentCliId) => RegisteredProfileDirs;
68
+ openPicker?: AgentSessionsController['openPicker'];
69
+ /** Whether a path is a folder, following links (default: fs.promises.stat): the filesystem boundary of folderExists. */
70
+ folderStat?: (path: string) => Promise<boolean>;
71
+ /** How long a folder may take to answer before it counts as gone (default FOLDER_CHECK_MS). */
72
+ folderTimeoutMs?: number;
73
+ }
74
+ export declare function createAgentSessionsController(options?: AgentSessionsControllerOptions): AgentSessionsController;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The person's Claude Code and Codex sessions, for /claude and /codex in Main: looking one up by id, listing them for
3
+ * the picker, and what the messages about them name. Only Main has one (see CommandContext.agentSessions): what it
4
+ * reads is session metadata (each session's id, folder, last-active time and a title), from the head of each file,
5
+ * only when the person opens the picker or resumes, and it never leaves Main: no other pane, agent or mirror viewer
6
+ * reads Main's screen while the picker shows it (screen_privacy.ts), and nothing is sent anywhere (workspace spec §14).
7
+ */
8
+ import { promises as fsPromises, realpathSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { agentProfileDir, listAgentProfiles } from '../agent_profiles.js';
11
+ import { claudeSessionCandidates, claudeSessionIdsStarting, findClaudeSession, latestClaudeSessionIn, listClaudeSessions } from './claude_store.js';
12
+ import { codexFolderLinks, codexSessionIdsStarting, findCodexSession, latestCodexSessionIn, listCodexSessions } from './codex_store.js';
13
+ import { FOLDER_CHECK_MS, FOLDER_CHECKS_AT_ONCE } from './limits.js';
14
+ import { nodeSessionStoreFs } from './store_fs.js';
15
+ import { agentSessionStoreLinks, agentSessionStores, ownAgentConfigDir } from './stores.js';
16
+ /**
17
+ * folderExists over `stat`: at most FOLDER_CHECKS_AT_ONCE stats wait on the filesystem at once, each held until it
18
+ * settles, however long that is; a call answers false at its deadline, and one still queued then is never started.
19
+ */
20
+ function folderChecker(stat, timeoutMs) {
21
+ const queue = [];
22
+ let running = 0;
23
+ const pump = () => {
24
+ while (running < FOLDER_CHECKS_AT_ONCE && queue.length > 0) {
25
+ const job = queue.shift();
26
+ if (job.abandoned())
27
+ continue;
28
+ running += 1;
29
+ let asked;
30
+ try {
31
+ asked = stat(job.path);
32
+ }
33
+ catch {
34
+ asked = Promise.resolve(false);
35
+ }
36
+ void asked.catch(() => false).then(exists => {
37
+ running -= 1;
38
+ job.settle(exists);
39
+ pump();
40
+ });
41
+ }
42
+ };
43
+ return path => new Promise(resolve => {
44
+ let settled = false;
45
+ const finish = (exists) => {
46
+ if (settled)
47
+ return;
48
+ settled = true;
49
+ clearTimeout(timer);
50
+ resolve(exists);
51
+ };
52
+ // Kept referenced: whoever awaits the answer is owed one by the deadline.
53
+ const timer = setTimeout(() => finish(false), timeoutMs);
54
+ queue.push({ path, settle: finish, abandoned: () => settled });
55
+ pump();
56
+ });
57
+ }
58
+ export function createAgentSessionsController(options = {}) {
59
+ const env = options.env ?? process.env;
60
+ const home = options.home ?? homedir();
61
+ const fs = options.fs ?? nodeSessionStoreFs;
62
+ const registered = (cli) => options.registered?.(cli) ?? {};
63
+ const lookup = (cli) => ({ env, home, registered: registered(cli) });
64
+ const stores = (cli) => agentSessionStores(cli, lookup(cli));
65
+ let displayHome = home;
66
+ try {
67
+ displayHome = realpathSync(home);
68
+ }
69
+ catch {
70
+ // The home as given.
71
+ }
72
+ return {
73
+ home,
74
+ displayHome,
75
+ describeStores: cli => ({ ownDir: ownAgentConfigDir(cli, lookup(cli)), profiles: listAgentProfiles(cli, home, registered(cli)) }),
76
+ signInFor: (cli, profile) => (profile === null
77
+ ? { dir: env[cli === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME'] ? ownAgentConfigDir(cli, lookup(cli)) : null, profile: false }
78
+ : { dir: agentProfileDir(cli, profile, home, registered(cli)), profile: true }),
79
+ find: (cli, id, find = {}) => (cli === 'claude'
80
+ ? findClaudeSession(stores(cli), id, { fs, cwd: find.cwd ?? null })
81
+ : findCodexSession(stores(cli), id, { fs })),
82
+ latestHere: async (cli, cwd, profile) => {
83
+ const real = await fsPromises.realpath(cwd).catch(() => cwd);
84
+ const folders = [...new Set([real, cwd])];
85
+ const scoped = stores(cli).filter(store => profile === undefined || store.profile === profile);
86
+ return cli === 'claude' ? latestClaudeSessionIn(scoped, folders, fs) : latestCodexSessionIn(scoped, folders, fs);
87
+ },
88
+ matchIds: (cli, start) => (cli === 'claude'
89
+ ? claudeSessionIdsStarting(stores(cli), start.toLowerCase(), fs)
90
+ : codexSessionIdsStarting(stores(cli), start.toLowerCase(), fs)),
91
+ list: async (cli, list = {}) => {
92
+ const listing = await (cli === 'claude'
93
+ ? listClaudeSessions(stores(cli), { fs, cwd: list.cwd ?? null, ...(list.onRow ? { onRow: list.onRow } : {}) })
94
+ : listCodexSessions(stores(cli), { fs, ...(list.onRow ? { onRow: list.onRow } : {}) }));
95
+ return { ...listing, links: listing.links + agentSessionStoreLinks(cli, lookup(cli)).length };
96
+ },
97
+ linkedFolders: async (cli) => {
98
+ const inside = [];
99
+ for (const store of stores(cli)) {
100
+ if (cli === 'claude')
101
+ await claudeSessionCandidates(store, fs, path => { inside.push(path); });
102
+ else
103
+ inside.push(...await codexFolderLinks(store, fs));
104
+ }
105
+ return [...agentSessionStoreLinks(cli, lookup(cli)), ...inside];
106
+ },
107
+ folderExists: folderChecker(options.folderStat ?? (path => fsPromises.stat(path).then(info => info.isDirectory(), () => false)), options.folderTimeoutMs ?? FOLDER_CHECK_MS),
108
+ ...(options.openPicker ? { openPicker: options.openPicker } : {}),
109
+ };
110
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A JSON line that a session head ends inside, read as far as it is whole: a Claude Code session whose first prompt is
3
+ * a pasted screenshot or a long paste has that prompt's line cut by the 64 KiB head, and Claude Code writes the line's
4
+ * folder, entrypoint and sidechain flag ahead of its message.
5
+ *
6
+ * One pass over the text finds the last place it can be closed (after a whole value, or just inside a bracket), and
7
+ * the text up to there, closed, is parsed: `{"a":1,"b":{"c":"x` reads as {"a":1,"b":{}}. With `partialStrings`, a
8
+ * string value the cut falls inside is kept as far as the cut (an escape it cuts is dropped), so a long prompt's start
9
+ * can still be its title. A key the cut falls inside never is: its value is unknown. Nothing here throws.
10
+ */
11
+ /** The values of a JSON object or array cut short that are whole before the cut, closed; undefined when there are none. */
12
+ export declare function closeCutJson(text: string, options?: {
13
+ partialStrings?: boolean;
14
+ }): unknown;