@zergai/ztc 0.23.0-beta.1 → 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.
- package/README.md +299 -13
- package/bin/zmux-darwin-arm64 +0 -0
- package/bin/ztc-audio-darwin-arm64 +0 -0
- package/bin/ztc-capture-darwin-arm64 +0 -0
- package/bin/ztc-tui-darwin-arm64 +0 -0
- package/bin/zterm-darwin-arm64 +2 -2
- package/dist/agent/agent.js +57 -14
- package/dist/agent/backends/http_error.d.ts +2 -0
- package/dist/agent/backends/http_error.js +2 -0
- package/dist/agent/backends/router_gate.d.ts +3 -2
- package/dist/agent/backends/router_gate.js +5 -4
- package/dist/agent/backends/router_keys.d.ts +14 -0
- package/dist/agent/backends/router_keys.js +19 -0
- package/dist/agent/backends/router_refusal.d.ts +5 -3
- package/dist/agent/backends/router_refusal.js +28 -6
- package/dist/agent/backends/types.d.ts +1 -1
- package/dist/agent/backends/zrouter_stream.js +10 -6
- package/dist/agent/commands/agent_cli.d.ts +11 -1
- package/dist/agent/commands/agent_cli.js +295 -38
- package/dist/agent/commands/diff.js +4 -1
- package/dist/agent/commands/help.js +4 -1
- package/dist/agent/commands/plan.js +3 -1
- package/dist/agent/commands/session_redaction.d.ts +16 -0
- package/dist/agent/commands/session_redaction.js +77 -0
- package/dist/agent/commands/settings.js +144 -0
- package/dist/agent/commands/types.d.ts +5 -0
- package/dist/agent/commands/usage_spec.d.ts +4 -0
- package/dist/agent/commands/usage_spec.js +10 -4
- package/dist/agent/runtime/policy.d.ts +25 -0
- package/dist/agent/runtime/policy.js +154 -26
- package/dist/agent/runtime/source_verification.js +6 -2
- package/dist/agent/runtime/tool_runtime.js +81 -3
- package/dist/agent/tools/apply_patch.js +678 -131
- package/dist/agent/tools/bus_message.d.ts +26 -1
- package/dist/agent/tools/bus_message.js +126 -10
- package/dist/agent/tools/file.d.ts +16 -1
- package/dist/agent/tools/file.js +43 -5
- package/dist/agent/tools/index.d.ts +1 -1
- package/dist/agent/tools/index.js +1 -1
- package/dist/agent/tools/pane.js +5 -0
- package/dist/agent/tools/search.js +5 -1
- package/dist/agent/tools/supervision.js +16 -2
- package/dist/agent/tools/types.d.ts +22 -0
- package/dist/app/mirror_startup.d.ts +7 -5
- package/dist/app/mirror_startup.js +7 -5
- package/dist/app/navigator_mirrors.d.ts +20 -0
- package/dist/app/navigator_mirrors.js +36 -0
- package/dist/app/workspace_layout_controller.d.ts +11 -2
- package/dist/app/workspace_layout_controller.js +13 -2
- package/dist/batch/worktree.js +9 -1
- package/dist/cli_ratatui.d.ts +264 -12
- package/dist/cli_ratatui.js +1198 -103
- package/dist/config/types.d.ts +29 -0
- package/dist/desktop/daily/source_baseline.js +3 -1
- package/dist/diagnostics/session_export.d.ts +1 -0
- package/dist/diagnostics/session_export.js +229 -26
- package/dist/emulation/tool_adapters.js +42 -5
- package/dist/headless.js +24 -5
- package/dist/instance_registry.d.ts +7 -0
- package/dist/mcp/workspace_server.d.ts +12 -1
- package/dist/mcp/workspace_server.js +75 -8
- package/dist/panes/agent_cli.d.ts +60 -3
- package/dist/panes/agent_cli.js +169 -16
- package/dist/panes/agent_pane_sessions.d.ts +22 -0
- package/dist/panes/agent_pane_sessions.js +111 -0
- package/dist/panes/agent_panes.d.ts +77 -3
- package/dist/panes/agent_panes.js +199 -10
- package/dist/panes/agent_profiles.d.ts +5 -0
- package/dist/panes/agent_profiles.js +7 -0
- package/dist/panes/agent_resume.d.ts +134 -0
- package/dist/panes/agent_resume.js +155 -0
- package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
- package/dist/panes/agent_sessions/claude_head.js +122 -0
- package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
- package/dist/panes/agent_sessions/claude_store.js +223 -0
- package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
- package/dist/panes/agent_sessions/codex_head.js +161 -0
- package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
- package/dist/panes/agent_sessions/codex_store.js +187 -0
- package/dist/panes/agent_sessions/controller.d.ts +74 -0
- package/dist/panes/agent_sessions/controller.js +110 -0
- package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
- package/dist/panes/agent_sessions/cut_json.js +109 -0
- package/dist/panes/agent_sessions/limits.d.ts +48 -0
- package/dist/panes/agent_sessions/limits.js +48 -0
- package/dist/panes/agent_sessions/scan.d.ts +49 -0
- package/dist/panes/agent_sessions/scan.js +86 -0
- package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
- package/dist/panes/agent_sessions/store_fs.js +128 -0
- package/dist/panes/agent_sessions/stores.d.ts +36 -0
- package/dist/panes/agent_sessions/stores.js +89 -0
- package/dist/panes/agent_sessions/title.d.ts +9 -0
- package/dist/panes/agent_sessions/title.js +51 -0
- package/dist/panes/agent_sessions/types.d.ts +48 -0
- package/dist/panes/agent_sessions/types.js +2 -0
- package/dist/panes/reply_arbitrator.d.ts +39 -0
- package/dist/panes/reply_arbitrator.js +185 -0
- package/dist/panes/reply_modes.d.ts +291 -0
- package/dist/panes/reply_modes.js +598 -0
- package/dist/runtime_info.js +11 -2
- package/dist/session.js +4 -2
- package/dist/simulation/living/context.d.ts +8 -8
- package/dist/simulation/living/types.d.ts +5 -5
- package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
- package/dist/ui/ratatui/ipc_path.d.ts +5 -0
- package/dist/ui/ratatui/ipc_path.js +23 -3
- package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
- package/dist/ui/ratatui/pane_credential_broker.js +49 -14
- package/dist/ui/ratatui/pane_relay.d.ts +5 -2
- package/dist/ui/ratatui/pane_relay.js +86 -19
- package/dist/ui/ratatui/process.js +3 -0
- package/dist/ui/ratatui/protocol.d.ts +50 -1
- package/dist/ui/ratatui/protocol.js +56 -0
- package/dist/ui/ratatui/relay_policy.d.ts +39 -0
- package/dist/ui/ratatui/relay_policy.js +94 -0
- package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
- package/dist/ui/ratatui/screen_privacy.js +24 -0
- package/dist/ui/scrollback.js +8 -0
- package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
- package/dist/ui/widgets/agent_sessions_panel.js +542 -0
- package/dist/ui/widgets/log_view.d.ts +5 -1
- package/dist/ui/widgets/log_view.js +40 -4
- package/dist/utils/atomic_write.js +9 -11
- package/dist/utils/canonical_path.d.ts +19 -0
- package/dist/utils/canonical_path.js +44 -0
- package/dist/utils/compaction.d.ts +2 -1
- package/dist/utils/compaction.js +3 -1
- package/dist/utils/git_directory_names.d.ts +51 -0
- package/dist/utils/git_directory_names.js +429 -0
- package/dist/utils/temporary_write_root.d.ts +6 -1
- package/dist/utils/temporary_write_root.js +32 -2
- package/dist/utils/tool_result_message.d.ts +4 -1
- package/dist/utils/tool_result_message.js +6 -2
- package/dist/web/bus_hold.d.ts +70 -0
- package/dist/web/bus_hold.js +118 -0
- package/dist/web/mirror_client.d.ts +7 -3
- package/dist/web/mirror_client.js +61 -23
- package/dist/web/mirror_route_gate.d.ts +40 -0
- package/dist/web/mirror_route_gate.js +71 -0
- package/dist/web/mirror_stream.d.ts +147 -22
- package/dist/web/mirror_stream.js +350 -83
- package/dist/web/pane_credentials.d.ts +32 -1
- package/dist/web/pane_credentials.js +62 -2
- package/dist/workspace_collision.js +11 -2
- package/dist/zlm-embed.mjs +940 -273
- package/package.json +34 -12
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opening a Claude Code or Codex session again: the rule for what its pane starts with and where (resumeLaunchPlan),
|
|
3
|
+
* and the thin call that opens it like any pane the person opens (openResumedAgentPane).
|
|
4
|
+
*/
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { AGENT_CLIS, formatCliArguments } from './agent_cli.js';
|
|
7
|
+
import { openAgentSessionPanes } from './agent_pane_sessions.js';
|
|
8
|
+
import { openAgentPane } from './agent_panes.js';
|
|
9
|
+
import { agentProfileArgs, agentProfileClearedEnv, agentProfileEnv } from './agent_profiles.js';
|
|
10
|
+
/**
|
|
11
|
+
* The CLI's own words that resume or fork a session, and point Codex at this folder for --here. A Claude Code fork is
|
|
12
|
+
* given its new id (--session-id with --fork-session), so the pane holding it is known (agent_pane_sessions.ts).
|
|
13
|
+
*/
|
|
14
|
+
function resumeWords(cli, mode, id, here, newSessionId) {
|
|
15
|
+
if (cli === 'claude')
|
|
16
|
+
return mode === 'fork' ? ['--resume', id, '--fork-session', '--session-id', newSessionId()] : ['--resume', id];
|
|
17
|
+
// A folder named on Codex's command line is the one it resumes in, so it doesn't ask which.
|
|
18
|
+
return [...(here ? ['-C', here] : []), mode === 'fork' ? 'fork' : 'resume', id];
|
|
19
|
+
}
|
|
20
|
+
function withPrompt(words, prompt) {
|
|
21
|
+
return prompt?.trim() ? { words, prompt } : { words };
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* How a session is opened again: in its own folder, on the sign-in whose store holds it, with Claude Code's
|
|
25
|
+
* `--resume <id>` (and `--fork-session`) or Codex's `resume <id>` (or `fork <id>`), and its next prompt as the CLI's
|
|
26
|
+
* argument. With `here`, in this folder instead. A folder the session names that is gone, or one its file doesn't
|
|
27
|
+
* name or Claude Code's project folder doesn't confirm, is refused, never swapped for this one: the agent would work
|
|
28
|
+
* against paths that aren't there. `here` is how the person chooses this folder for it.
|
|
29
|
+
*/
|
|
30
|
+
export function resumeLaunchPlan(target, options) {
|
|
31
|
+
let cwd;
|
|
32
|
+
if (options.here) {
|
|
33
|
+
cwd = options.cwdNow;
|
|
34
|
+
}
|
|
35
|
+
else if (target.cwd === null || !target.folderVerified) {
|
|
36
|
+
return { error: 'folder-unknown' };
|
|
37
|
+
}
|
|
38
|
+
else if (!options.folderExists(target.cwd)) {
|
|
39
|
+
return { error: 'folder-gone', folder: target.cwd };
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
cwd = target.cwd;
|
|
43
|
+
}
|
|
44
|
+
const words = resumeWords(target.cli, options.mode, target.id, options.here ? options.cwdNow : null, options.newSessionId ?? randomUUID);
|
|
45
|
+
return { plan: { cli: target.cli, request: withPrompt(words, options.prompt), cwd, profile: target.profile } };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The most recent session in this folder: Claude Code's `--continue`, Codex's `resume --last`, which each CLI finds
|
|
49
|
+
* itself. ZTC reads nothing for it; it starts on the profile asked for, else the one new panes start on.
|
|
50
|
+
*/
|
|
51
|
+
export function continueLaunchPlan(cli, options) {
|
|
52
|
+
const words = cli === 'claude' ? ['--continue'] : ['resume', '--last'];
|
|
53
|
+
return { cli, request: withPrompt(words, options.prompt), cwd: options.cwdNow, profile: options.profile };
|
|
54
|
+
}
|
|
55
|
+
/** A session by its name, which the CLI looks for itself (`--resume <name>`, `resume <name>`), in this folder. */
|
|
56
|
+
export function nameLaunchPlan(cli, name, options) {
|
|
57
|
+
const words = cli === 'claude' ? ['--resume', name] : ['resume', name];
|
|
58
|
+
return { cli, request: withPrompt(words, options.prompt), cwd: options.cwdNow, profile: options.profile };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Open the plan's pane exactly as any /claude or /codex pane the person opens: openAgentPane, so it gets the same
|
|
62
|
+
* permission defaults, workspace server, kitty settings, MotSi wrapping and name ("Claude Code", "Codex @work", never
|
|
63
|
+
* the session's title). The profile is passed explicitly when the plan names one (null: this computer's own
|
|
64
|
+
* sign-in), so it wins over the profile new panes start on.
|
|
65
|
+
*/
|
|
66
|
+
export async function openResumedAgentPane(transport, plan, deps = {}) {
|
|
67
|
+
return openAgentPane(transport, {
|
|
68
|
+
cli: plan.cli,
|
|
69
|
+
request: plan.request,
|
|
70
|
+
cwd: plan.cwd,
|
|
71
|
+
openedBy: 'person',
|
|
72
|
+
...(plan.profile !== undefined ? { profile: plan.profile } : {}),
|
|
73
|
+
...(deps.findBinary ? { findBinary: deps.findBinary } : {}),
|
|
74
|
+
...(deps.server !== undefined ? { server: deps.server } : {}),
|
|
75
|
+
...(deps.env ? { env: deps.env } : {}),
|
|
76
|
+
...(deps.motsi !== undefined ? { motsi: deps.motsi } : {}),
|
|
77
|
+
...(deps.profilesHome ? { profilesHome: deps.profilesHome } : {}),
|
|
78
|
+
...(deps.target !== undefined ? { target: deps.target } : {}),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A Claude Code or Codex pane the workspace saved, PANE_ID, whose program isn't running (restored "Not started", or
|
|
83
|
+
* exited), started again on the session its saved launch held (SESSION, from agentPaneSession): opened as the person's
|
|
84
|
+
* /claude resume <id> opens it, in its folder on the sign-in whose store holds it, `--resume <id>` in a pane Main knows
|
|
85
|
+
* and answers, next to PANE_ID, which then closes. Its saved command would start a fresh session's `--session-id <id>`
|
|
86
|
+
* over again, in a pane Main doesn't know. Says what happened; null when no store holds the session (one started and
|
|
87
|
+
* never written to), so the saved command runs as it was saved. A session a running pane holds is gone to there, and
|
|
88
|
+
* one PANE_ID itself runs is refused. Throws, saying why, when it can't be opened.
|
|
89
|
+
*/
|
|
90
|
+
export async function resumeSavedAgentPane(transport, paneId, session, sessions, options) {
|
|
91
|
+
const label = AGENT_CLIS[session.cli].label;
|
|
92
|
+
const open = (await openAgentSessionPanes(transport)).get(`${session.cli}:${session.id}`);
|
|
93
|
+
if (open === paneId)
|
|
94
|
+
throw new Error(`Pane ${paneId} still runs that ${label} session; its saved command starts only once it has stopped.`);
|
|
95
|
+
if (open !== undefined) {
|
|
96
|
+
transport.send({ type: 'focus_pane', pane_id: open });
|
|
97
|
+
return `That ${label} session is already open in pane ${open}.`;
|
|
98
|
+
}
|
|
99
|
+
const matches = await sessions.find(session.cli, session.id, { cwd: options.cwdNow });
|
|
100
|
+
if (matches.length === 0)
|
|
101
|
+
return null;
|
|
102
|
+
if (matches.length > 1) {
|
|
103
|
+
throw new Error(`That ${label} session is in ${matches.length} sign-ins' stores, so ZTC doesn't choose one: /${session.cli} resume `
|
|
104
|
+
+ 'lists them, and @<profile> before resume opens the one you choose.');
|
|
105
|
+
}
|
|
106
|
+
const target = matches[0];
|
|
107
|
+
// Asked off the event loop, with a deadline: a folder that doesn't answer counts as gone.
|
|
108
|
+
const exists = target.cwd !== null && target.folderVerified ? await sessions.folderExists(target.cwd) : false;
|
|
109
|
+
const planned = resumeLaunchPlan(target, { mode: 'resume', here: false, cwdNow: options.cwdNow, folderExists: () => exists });
|
|
110
|
+
if ('error' in planned) {
|
|
111
|
+
throw new Error(planned.error === 'folder-gone'
|
|
112
|
+
? `That ${label} session's folder no longer exists. To resume it in this folder: /${session.cli} resume ${session.id} --here.`
|
|
113
|
+
: `ZTC can't tell which folder that ${label} session works in. To resume it in this folder: /${session.cli} resume ${session.id} --here.`);
|
|
114
|
+
}
|
|
115
|
+
const opened = await openResumedAgentPane(transport, planned.plan, { ...options.deps, profilesHome: sessions.home, target: paneId });
|
|
116
|
+
if (opened.error)
|
|
117
|
+
throw new Error(opened.error);
|
|
118
|
+
// The placeholder goes once the session's pane has opened beside it.
|
|
119
|
+
transport.send({ type: 'close_pane', pane_id: paneId });
|
|
120
|
+
return [openedSessionLine(opened, 'resume'), opened.notice].filter(Boolean).join(' ');
|
|
121
|
+
}
|
|
122
|
+
// ── What is said about a resumed session ────────────────────────────────────
|
|
123
|
+
/**
|
|
124
|
+
* What Main says once a session's pane opened: the pane, and nothing of the session, its folder or a prompt. Other
|
|
125
|
+
* panes and their agents may read Main's screen (workspace spec §7.4), so with panes no line names those.
|
|
126
|
+
*/
|
|
127
|
+
export function openedSessionLine(opened, how) {
|
|
128
|
+
const doing = how === 'fork' ? 'forking that session' : how === 'continue' ? "continuing this folder's latest session" : 'resuming that session';
|
|
129
|
+
return `Opened ${opened.title} in pane ${opened.paneId}, ${doing}.`;
|
|
130
|
+
}
|
|
131
|
+
/** `~/…` for a folder under the home the stores are read from. */
|
|
132
|
+
export function homeRelative(path, home) {
|
|
133
|
+
return path === home ? '~' : path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
|
|
134
|
+
}
|
|
135
|
+
/** The command as the person reads it: the permission flag ZTC added, then the CLI's own words and the prompt. */
|
|
136
|
+
export function shownAgentCommand(binary, request, permissionArgs = []) {
|
|
137
|
+
const words = [...permissionArgs, ...request.words, ...(request.prompt ? ['--', request.prompt] : [])];
|
|
138
|
+
return words.length > 0 ? `${binary} ${formatCliArguments(words)}` : binary;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Where there are no panes: the command that resumes the plan's session in another terminal, in its folder and on its
|
|
142
|
+
* sign-in as its pane would start: `dir`, the config folder to name (a profile's, or this computer's own when ZTC's
|
|
143
|
+
* environment set it, else null), and on a profile (`options.profile`) Claude Code's sign-in overrides unset
|
|
144
|
+
* (agentProfileClearedEnv) or Codex's file store (agentProfileArgs). ZTC's bypass flag is a pane default, so it isn't
|
|
145
|
+
* in it, and nothing is copied to the clipboard.
|
|
146
|
+
*/
|
|
147
|
+
export function elsewhereCommandLine(plan, dir, options = {}) {
|
|
148
|
+
const profile = options.profile === true;
|
|
149
|
+
const unset = profile ? agentProfileClearedEnv(plan.cli) : [];
|
|
150
|
+
const variables = dir ? Object.entries(agentProfileEnv(plan.cli, dir)).map(([name, value]) => `${name}=${formatCliArguments([value])}`) : [];
|
|
151
|
+
const prefix = [...(unset.length > 0 ? ['env', ...unset.flatMap(name => ['-u', name])] : []), ...variables];
|
|
152
|
+
const request = profile ? { ...plan.request, words: [...agentProfileArgs(plan.cli), ...plan.request.words] } : plan.request;
|
|
153
|
+
const command = shownAgentCommand(AGENT_CLIS[plan.cli].binary, request);
|
|
154
|
+
return `Run this in another terminal: cd ${formatCliArguments([plan.cwd])} && ${[...prefix, command].join(' ')}`;
|
|
155
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the head of a Claude Code session file says about the session: its folder, where it was started from, whether
|
|
3
|
+
* it is a subagent's, and the texts a title comes from. The head of a file cut at 64 KiB ends inside a line, which
|
|
4
|
+
* counts as far as it is whole (cut_json.ts): a first prompt that is a pasted screenshot or a long paste runs past the
|
|
5
|
+
* head, and Claude Code writes the line's folder ahead of its message. Nothing here throws, whatever the bytes.
|
|
6
|
+
*/
|
|
7
|
+
export interface ClaudeSessionHead {
|
|
8
|
+
/** The first folder a line names. */
|
|
9
|
+
cwd?: string;
|
|
10
|
+
/** The first entrypoint a line names: cli, claude-vscode, sdk-ts… */
|
|
11
|
+
entrypoint?: string;
|
|
12
|
+
/** Whether the first line that says so marks the file a sidechain (a subagent's transcript). */
|
|
13
|
+
sidechain: boolean;
|
|
14
|
+
/** The last name given with /rename or -n in the head. */
|
|
15
|
+
customTitle?: string;
|
|
16
|
+
/** The last title Claude Code generated in the head. */
|
|
17
|
+
aiTitle?: string;
|
|
18
|
+
/** The last summary line in the head. */
|
|
19
|
+
summary?: string;
|
|
20
|
+
/** The person's first prompt. */
|
|
21
|
+
firstPrompt?: string;
|
|
22
|
+
/** Whether that first prompt is /loop, which Claude Code's own picker leaves out. */
|
|
23
|
+
firstPromptIsLoop: boolean;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Read the head of a session file; `whole` when it is the whole file, so its last line is complete. Otherwise the head
|
|
27
|
+
* ends inside a line, or after its newline (an empty last piece), and that line counts as far as it is whole: its
|
|
28
|
+
* fields before the cut, and for a first prompt, its text up to the cut.
|
|
29
|
+
*/
|
|
30
|
+
export declare function parseClaudeSessionHead(text: string, whole: boolean): ClaudeSessionHead;
|
|
31
|
+
/** The session's title: its name, Claude Code's title for it, its summary, then its first prompt. */
|
|
32
|
+
export declare function claudeSessionTitle(head: ClaudeSessionHead): string | null;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the head of a Claude Code session file says about the session: its folder, where it was started from, whether
|
|
3
|
+
* it is a subagent's, and the texts a title comes from. The head of a file cut at 64 KiB ends inside a line, which
|
|
4
|
+
* counts as far as it is whole (cut_json.ts): a first prompt that is a pasted screenshot or a long paste runs past the
|
|
5
|
+
* head, and Claude Code writes the line's folder ahead of its message. Nothing here throws, whatever the bytes.
|
|
6
|
+
*/
|
|
7
|
+
import { closeCutJson } from './cut_json.js';
|
|
8
|
+
import { COMMAND_TAG_CHARS } from './limits.js';
|
|
9
|
+
import { sessionTitle } from './title.js';
|
|
10
|
+
function isRecord(value) {
|
|
11
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
12
|
+
}
|
|
13
|
+
function parseLine(line) {
|
|
14
|
+
if (!line.trim())
|
|
15
|
+
return null;
|
|
16
|
+
try {
|
|
17
|
+
const value = JSON.parse(line);
|
|
18
|
+
return isRecord(value) ? value : null;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** A message's text: its string, or its text blocks joined; "[Image]" for images alone; nothing for tool results. */
|
|
25
|
+
function contentText(content) {
|
|
26
|
+
if (typeof content === 'string')
|
|
27
|
+
return content;
|
|
28
|
+
if (!Array.isArray(content))
|
|
29
|
+
return '';
|
|
30
|
+
const texts = [];
|
|
31
|
+
let image = false;
|
|
32
|
+
for (const block of content) {
|
|
33
|
+
if (!isRecord(block))
|
|
34
|
+
continue;
|
|
35
|
+
if (block.type === 'text' && typeof block.text === 'string')
|
|
36
|
+
texts.push(block.text);
|
|
37
|
+
else if (block.type === 'image')
|
|
38
|
+
image = true;
|
|
39
|
+
}
|
|
40
|
+
const text = texts.join('\n');
|
|
41
|
+
return text.trim() ? text : image ? '[Image]' : '';
|
|
42
|
+
}
|
|
43
|
+
const LOCAL_COMMAND_CAVEAT = 'Caveat: The messages below were generated by the user while running local commands';
|
|
44
|
+
/**
|
|
45
|
+
* The person's prompt on a user line, or null for a line that is no prompt of theirs: one Claude Code marks meta or
|
|
46
|
+
* shows only in the transcript, a compaction's summary, a tool result, a local command's output or its caveat. A slash
|
|
47
|
+
* command reads as `/name args`. Its tags are looked for in the prompt's first COMMAND_TAG_CHARS only, and the name's
|
|
48
|
+
* pattern can't backtrack across what it skips: a greedy run that stops at the first "<", trimmed after.
|
|
49
|
+
*/
|
|
50
|
+
function userPrompt(record) {
|
|
51
|
+
if (record.isMeta === true || record.isCompactSummary === true || record.isVisibleInTranscriptOnly === true)
|
|
52
|
+
return null;
|
|
53
|
+
const message = record.message;
|
|
54
|
+
if (!isRecord(message) || (message.role !== undefined && message.role !== 'user'))
|
|
55
|
+
return null;
|
|
56
|
+
const text = contentText(message.content).trim();
|
|
57
|
+
if (!text || text.startsWith('<local-command-') || text.startsWith(LOCAL_COMMAND_CAVEAT))
|
|
58
|
+
return null;
|
|
59
|
+
if (/^<command-(?:name|message|args)>/.test(text)) {
|
|
60
|
+
const tags = text.slice(0, COMMAND_TAG_CHARS);
|
|
61
|
+
const name = /<command-name>([^<]*)<\/command-name>/.exec(tags)?.[1]?.trim() ?? '';
|
|
62
|
+
if (!name)
|
|
63
|
+
return null;
|
|
64
|
+
const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(tags)?.[1]?.trim() ?? '';
|
|
65
|
+
const command = name.startsWith('/') ? name : `/${name}`;
|
|
66
|
+
return { text: args ? `${command} ${args}` : command, loop: command === '/loop' };
|
|
67
|
+
}
|
|
68
|
+
return { text, loop: /^\/loop(?:\s|$)/.test(text) };
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Read the head of a session file; `whole` when it is the whole file, so its last line is complete. Otherwise the head
|
|
72
|
+
* ends inside a line, or after its newline (an empty last piece), and that line counts as far as it is whole: its
|
|
73
|
+
* fields before the cut, and for a first prompt, its text up to the cut.
|
|
74
|
+
*/
|
|
75
|
+
export function parseClaudeSessionHead(text, whole) {
|
|
76
|
+
const head = { sidechain: false, firstPromptIsLoop: false };
|
|
77
|
+
const lines = text.split('\n');
|
|
78
|
+
const cut = whole ? undefined : lines.pop();
|
|
79
|
+
let sidechainKnown = false;
|
|
80
|
+
/** One line's record; its prompt is read from `promptRecord`, a cut line's with its last string kept. */
|
|
81
|
+
const take = (record, promptRecord) => {
|
|
82
|
+
if (!sidechainKnown && typeof record.isSidechain === 'boolean') {
|
|
83
|
+
head.sidechain = record.isSidechain;
|
|
84
|
+
sidechainKnown = true;
|
|
85
|
+
}
|
|
86
|
+
if (head.cwd === undefined && typeof record.cwd === 'string' && record.cwd)
|
|
87
|
+
head.cwd = record.cwd;
|
|
88
|
+
if (head.entrypoint === undefined && typeof record.entrypoint === 'string' && record.entrypoint)
|
|
89
|
+
head.entrypoint = record.entrypoint;
|
|
90
|
+
if (record.type === 'custom-title' && typeof record.customTitle === 'string')
|
|
91
|
+
head.customTitle = record.customTitle;
|
|
92
|
+
else if (record.type === 'ai-title' && typeof record.aiTitle === 'string')
|
|
93
|
+
head.aiTitle = record.aiTitle;
|
|
94
|
+
else if (record.type === 'summary' && typeof record.summary === 'string')
|
|
95
|
+
head.summary = record.summary;
|
|
96
|
+
else if (record.type === 'user' && head.firstPrompt === undefined && record.isSidechain !== true) {
|
|
97
|
+
const prompt = userPrompt(promptRecord);
|
|
98
|
+
if (prompt) {
|
|
99
|
+
head.firstPrompt = prompt.text;
|
|
100
|
+
head.firstPromptIsLoop = prompt.loop;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
for (const line of lines) {
|
|
105
|
+
const record = parseLine(line);
|
|
106
|
+
if (record)
|
|
107
|
+
take(record, record);
|
|
108
|
+
}
|
|
109
|
+
if (cut?.trim()) {
|
|
110
|
+
// Only what is whole before the cut: never a folder or entrypoint the cut falls inside.
|
|
111
|
+
const record = closeCutJson(cut);
|
|
112
|
+
if (isRecord(record)) {
|
|
113
|
+
const partial = record.type === 'user' && head.firstPrompt === undefined ? closeCutJson(cut, { partialStrings: true }) : undefined;
|
|
114
|
+
take(record, isRecord(partial) ? partial : record);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return head;
|
|
118
|
+
}
|
|
119
|
+
/** The session's title: its name, Claude Code's title for it, its summary, then its first prompt. */
|
|
120
|
+
export function claudeSessionTitle(head) {
|
|
121
|
+
return sessionTitle(head.customTitle) ?? sessionTitle(head.aiTitle) ?? sessionTitle(head.summary) ?? sessionTitle(head.firstPrompt);
|
|
122
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code's sessions in a store: `projects/<project folder>/<session id>.jsonl`, each read from its first 64 KiB.
|
|
3
|
+
*
|
|
4
|
+
* Only files named exactly `<uuid>.jsonl` directly in a project folder are sessions: Claude Code keeps a session's
|
|
5
|
+
* subagents and tool results in a folder named after it, and old sidechains and copies under other names. Each is
|
|
6
|
+
* looked at without following a link, and opened only when it is a regular file. Nothing else in the store is read.
|
|
7
|
+
*/
|
|
8
|
+
import { type CandidateRead, type ScanOptions } from './scan.js';
|
|
9
|
+
import { type SessionStoreFs } from './store_fs.js';
|
|
10
|
+
import type { AgentSessionStore } from './stores.js';
|
|
11
|
+
import type { AgentSessionRow, SessionCandidate, SessionListing } from './types.js';
|
|
12
|
+
export interface ClaudeListOptions extends ScanOptions {
|
|
13
|
+
fs?: SessionStoreFs;
|
|
14
|
+
/** This folder: its project folders' newest, and its subfolders', are read even when older than the newest the scan reads. */
|
|
15
|
+
cwd?: string | null;
|
|
16
|
+
/** Heads read of the newest of all, and as many again at most of this folder's besides them (default HEAD_READS_PER_OPEN). */
|
|
17
|
+
maxReads?: number;
|
|
18
|
+
}
|
|
19
|
+
/** The project folder name Claude Code keeps a folder's sessions under: each character but a letter or digit is "-". */
|
|
20
|
+
export declare function claudeProjectDirName(cwd: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* The session files of a store, by name and modification time; nothing is opened. A project folder that is a symbolic
|
|
23
|
+
* link is never followed: `onLink` hears of it.
|
|
24
|
+
*/
|
|
25
|
+
export declare function claudeSessionCandidates(store: AgentSessionStore, fs?: SessionStoreFs, onLink?: (path: string) => void): Promise<SessionCandidate[]>;
|
|
26
|
+
/**
|
|
27
|
+
* A candidate's row from its head. The picker leaves out what Claude Code's own picker does (a subagent's transcript,
|
|
28
|
+
* a session from the Agent SDK or the desktop app, one whose first prompt is /loop) and a file read whole with
|
|
29
|
+
* neither a prompt nor a title; such rows are still found by id. A head that names no folder (its first prompt starts
|
|
30
|
+
* past 64 KiB) is this folder's, `cwd`, when its project folder is the one Claude Code makes for this folder: Claude
|
|
31
|
+
* Code resumes it from here.
|
|
32
|
+
*/
|
|
33
|
+
export declare function readClaudeCandidate(candidate: SessionCandidate, fs?: SessionStoreFs, options?: {
|
|
34
|
+
cwd?: string | null;
|
|
35
|
+
}): Promise<CandidateRead>;
|
|
36
|
+
/**
|
|
37
|
+
* The Claude Code sessions in these stores, newest first: the newest files' heads, `maxReads` of them, and besides
|
|
38
|
+
* them the newest `maxReads` in this folder's project folders and its subfolders' (found by name, then placed by the
|
|
39
|
+
* head's folder). A session whose head names no folder, and isn't this folder's, takes the folder of another session
|
|
40
|
+
* read from its project folder, as soon as one is.
|
|
41
|
+
*/
|
|
42
|
+
export declare function listClaudeSessions(stores: readonly AgentSessionStore[], options?: ClaudeListOptions): Promise<SessionListing>;
|
|
43
|
+
/**
|
|
44
|
+
* This folder's latest session, for continue: from the project folders Claude Code keeps for one of `folders` (this
|
|
45
|
+
* folder as given and as resolved), newest first, the first whose head leaves it in the picker, reading CONTINUE_READS
|
|
46
|
+
* heads at most. Null when none does.
|
|
47
|
+
*/
|
|
48
|
+
export declare function latestClaudeSessionIn(stores: readonly AgentSessionStore[], folders: readonly string[], fs?: SessionStoreFs): Promise<AgentSessionRow | null>;
|
|
49
|
+
/** The ids of the sessions in these stores whose ids start with `start` (lowercase), each once; nothing is opened. */
|
|
50
|
+
export declare function claudeSessionIdsStarting(stores: readonly AgentSessionStore[], start: string, fs?: SessionStoreFs): Promise<string[]>;
|
|
51
|
+
/**
|
|
52
|
+
* The session with this id in each store that holds it, from its newest file there. Each project folder is looked in
|
|
53
|
+
* for `<id>.jsonl` without opening anything; only the one file found in a store is opened, and, when its head names
|
|
54
|
+
* no folder and its project folder isn't this folder's (`cwd`), the newest other session in its project folder.
|
|
55
|
+
*/
|
|
56
|
+
export declare function findClaudeSession(stores: readonly AgentSessionStore[], id: string, options?: {
|
|
57
|
+
fs?: SessionStoreFs;
|
|
58
|
+
cwd?: string | null;
|
|
59
|
+
}): Promise<AgentSessionRow[]>;
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code's sessions in a store: `projects/<project folder>/<session id>.jsonl`, each read from its first 64 KiB.
|
|
3
|
+
*
|
|
4
|
+
* Only files named exactly `<uuid>.jsonl` directly in a project folder are sessions: Claude Code keeps a session's
|
|
5
|
+
* subagents and tool results in a folder named after it, and old sidechains and copies under other names. Each is
|
|
6
|
+
* looked at without following a link, and opened only when it is a regular file. Nothing else in the store is read.
|
|
7
|
+
*/
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { isSessionId } from '../agent_cli.js';
|
|
10
|
+
import { claudeSessionTitle, parseClaudeSessionHead } from './claude_head.js';
|
|
11
|
+
import { CLAUDE_HEAD_BYTES, CONTINUE_READS, HEAD_READS_PER_OPEN } from './limits.js';
|
|
12
|
+
import { byRecency, chooseReads, readInOrder } from './scan.js';
|
|
13
|
+
import { nodeSessionStoreFs, readFileHead } from './store_fs.js';
|
|
14
|
+
/** A session file's name: a lowercase canonical UUID and .jsonl, as Claude Code names them. */
|
|
15
|
+
const SESSION_FILE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.jsonl$/;
|
|
16
|
+
/** Claude Code shortens a project folder name past this many characters, adding a hash of the whole path. */
|
|
17
|
+
const PROJECT_NAME_LIMIT = 200;
|
|
18
|
+
/** The project folder name Claude Code keeps a folder's sessions under: each character but a letter or digit is "-". */
|
|
19
|
+
export function claudeProjectDirName(cwd) {
|
|
20
|
+
return cwd.replace(/[^a-zA-Z0-9]/g, '-');
|
|
21
|
+
}
|
|
22
|
+
/** Whether a project folder is the one Claude Code makes for `cwd`. */
|
|
23
|
+
function isProjectFolderOf(group, cwd) {
|
|
24
|
+
const name = claudeProjectDirName(cwd);
|
|
25
|
+
return name.length <= PROJECT_NAME_LIMIT ? group === name : group.startsWith(name.slice(0, PROJECT_NAME_LIMIT));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The session files of a store, by name and modification time; nothing is opened. A project folder that is a symbolic
|
|
29
|
+
* link is never followed: `onLink` hears of it.
|
|
30
|
+
*/
|
|
31
|
+
export async function claudeSessionCandidates(store, fs = nodeSessionStoreFs, onLink = () => { }) {
|
|
32
|
+
const entries = await fs.list(store.sessionsDir);
|
|
33
|
+
for (const entry of entries)
|
|
34
|
+
if (entry.kind === 'link')
|
|
35
|
+
onLink(join(store.sessionsDir, entry.name));
|
|
36
|
+
const projects = entries.filter(entry => entry.kind === 'directory');
|
|
37
|
+
const perProject = await Promise.all(projects.map(async (project) => {
|
|
38
|
+
const dir = join(store.sessionsDir, project.name);
|
|
39
|
+
const files = (await fs.list(dir)).filter(entry => entry.kind === 'file' && SESSION_FILE.test(entry.name));
|
|
40
|
+
const found = await Promise.all(files.map(async (entry) => {
|
|
41
|
+
const path = join(dir, entry.name);
|
|
42
|
+
const info = await fs.lstat(path);
|
|
43
|
+
if (info?.kind !== 'file')
|
|
44
|
+
return null;
|
|
45
|
+
return { cli: 'claude', id: entry.name.slice(0, -'.jsonl'.length), path, profile: store.profile, mtimeMs: info.mtimeMs, group: project.name };
|
|
46
|
+
}));
|
|
47
|
+
return found.filter((candidate) => candidate !== null);
|
|
48
|
+
}));
|
|
49
|
+
return perProject.flat();
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* A candidate's row from its head. The picker leaves out what Claude Code's own picker does (a subagent's transcript,
|
|
53
|
+
* a session from the Agent SDK or the desktop app, one whose first prompt is /loop) and a file read whole with
|
|
54
|
+
* neither a prompt nor a title; such rows are still found by id. A head that names no folder (its first prompt starts
|
|
55
|
+
* past 64 KiB) is this folder's, `cwd`, when its project folder is the one Claude Code makes for this folder: Claude
|
|
56
|
+
* Code resumes it from here.
|
|
57
|
+
*/
|
|
58
|
+
export async function readClaudeCandidate(candidate, fs = nodeSessionStoreFs, options = {}) {
|
|
59
|
+
const read = await readFileHead(fs, candidate.path, CLAUDE_HEAD_BYTES);
|
|
60
|
+
if (!read)
|
|
61
|
+
return null;
|
|
62
|
+
const head = parseClaudeSessionHead(read.bytes.toString('utf8'), read.whole);
|
|
63
|
+
const title = claudeSessionTitle(head);
|
|
64
|
+
const here = head.cwd === undefined && options.cwd && isProjectFolderOf(candidate.group, options.cwd) ? options.cwd : null;
|
|
65
|
+
const cwd = head.cwd ?? here;
|
|
66
|
+
const row = {
|
|
67
|
+
cli: 'claude',
|
|
68
|
+
id: candidate.id,
|
|
69
|
+
cwd,
|
|
70
|
+
folderVerified: cwd !== null && isProjectFolderOf(candidate.group, cwd),
|
|
71
|
+
mtimeMs: candidate.mtimeMs,
|
|
72
|
+
title,
|
|
73
|
+
profile: candidate.profile,
|
|
74
|
+
path: candidate.path,
|
|
75
|
+
};
|
|
76
|
+
const entrypoint = head.entrypoint ?? '';
|
|
77
|
+
const listed = !head.sidechain && !entrypoint.startsWith('sdk-') && entrypoint !== 'claude-desktop' && !head.firstPromptIsLoop
|
|
78
|
+
&& !(read.whole && title === null);
|
|
79
|
+
return { row, listed };
|
|
80
|
+
}
|
|
81
|
+
/** A row whose head names no folder, placed in `cwd`, the folder of another session in its project folder. */
|
|
82
|
+
function placedIn(row, cwd) {
|
|
83
|
+
return { ...row, cwd, folderVerified: true };
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The Claude Code sessions in these stores, newest first: the newest files' heads, `maxReads` of them, and besides
|
|
87
|
+
* them the newest `maxReads` in this folder's project folders and its subfolders' (found by name, then placed by the
|
|
88
|
+
* head's folder). A session whose head names no folder, and isn't this folder's, takes the folder of another session
|
|
89
|
+
* read from its project folder, as soon as one is.
|
|
90
|
+
*/
|
|
91
|
+
export async function listClaudeSessions(stores, options = {}) {
|
|
92
|
+
const fs = options.fs ?? nodeSessionStoreFs;
|
|
93
|
+
let links = 0;
|
|
94
|
+
const candidates = (await Promise.all(stores.map(store => claudeSessionCandidates(store, fs, () => { links += 1; })))).flat();
|
|
95
|
+
const here = options.cwd ? claudeProjectDirName(options.cwd) : null;
|
|
96
|
+
const chosen = chooseReads(candidates, {
|
|
97
|
+
maxReads: options.maxReads ?? HEAD_READS_PER_OPEN,
|
|
98
|
+
...(here ? { priority: (candidate) => candidate.group === here || candidate.group.startsWith(`${here}-`) } : {}),
|
|
99
|
+
});
|
|
100
|
+
// Each project folder's first folder read, and the rows still waiting for one.
|
|
101
|
+
const folders = new Map();
|
|
102
|
+
const waiting = new Map();
|
|
103
|
+
const scanned = await readInOrder(chosen, async (candidate) => {
|
|
104
|
+
const read = await readClaudeCandidate(candidate, fs, { cwd: options.cwd ?? null });
|
|
105
|
+
if (!read)
|
|
106
|
+
return read;
|
|
107
|
+
const { row } = read;
|
|
108
|
+
if (row.cwd !== null) {
|
|
109
|
+
if (row.folderVerified && !folders.has(candidate.group))
|
|
110
|
+
folders.set(candidate.group, row.cwd);
|
|
111
|
+
return read;
|
|
112
|
+
}
|
|
113
|
+
const known = folders.get(candidate.group);
|
|
114
|
+
if (known !== undefined)
|
|
115
|
+
return { ...read, row: placedIn(row, known) };
|
|
116
|
+
waiting.set(row, candidate.group);
|
|
117
|
+
return read;
|
|
118
|
+
}, options);
|
|
119
|
+
const listing = { ...scanned, older: candidates.length - chosen.length, links };
|
|
120
|
+
if (waiting.size === 0)
|
|
121
|
+
return listing;
|
|
122
|
+
return {
|
|
123
|
+
...listing,
|
|
124
|
+
rows: listing.rows.map(row => {
|
|
125
|
+
const group = waiting.get(row);
|
|
126
|
+
const known = group === undefined ? undefined : folders.get(group);
|
|
127
|
+
return known === undefined ? row : placedIn(row, known);
|
|
128
|
+
}),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* This folder's latest session, for continue: from the project folders Claude Code keeps for one of `folders` (this
|
|
133
|
+
* folder as given and as resolved), newest first, the first whose head leaves it in the picker, reading CONTINUE_READS
|
|
134
|
+
* heads at most. Null when none does.
|
|
135
|
+
*/
|
|
136
|
+
export async function latestClaudeSessionIn(stores, folders, fs = nodeSessionStoreFs) {
|
|
137
|
+
const candidates = [];
|
|
138
|
+
for (const store of stores) {
|
|
139
|
+
const projects = (await fs.list(store.sessionsDir))
|
|
140
|
+
.filter(entry => entry.kind === 'directory' && folders.some(folder => isProjectFolderOf(entry.name, folder)));
|
|
141
|
+
for (const project of projects) {
|
|
142
|
+
const dir = join(store.sessionsDir, project.name);
|
|
143
|
+
for (const entry of await fs.list(dir)) {
|
|
144
|
+
if (entry.kind !== 'file' || !SESSION_FILE.test(entry.name))
|
|
145
|
+
continue;
|
|
146
|
+
const info = await fs.lstat(join(dir, entry.name));
|
|
147
|
+
if (info?.kind === 'file') {
|
|
148
|
+
candidates.push({ cli: 'claude', id: entry.name.slice(0, -'.jsonl'.length), path: join(dir, entry.name), profile: store.profile,
|
|
149
|
+
mtimeMs: info.mtimeMs, group: project.name });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
for (const candidate of candidates.sort(byRecency).slice(0, CONTINUE_READS)) {
|
|
155
|
+
const read = await readClaudeCandidate(candidate, fs, { cwd: folders[0] ?? null });
|
|
156
|
+
if (read?.listed)
|
|
157
|
+
return read.row;
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
/** The ids of the sessions in these stores whose ids start with `start` (lowercase), each once; nothing is opened. */
|
|
162
|
+
export async function claudeSessionIdsStarting(stores, start, fs = nodeSessionStoreFs) {
|
|
163
|
+
const ids = new Set();
|
|
164
|
+
for (const store of stores) {
|
|
165
|
+
const projects = (await fs.list(store.sessionsDir)).filter(entry => entry.kind === 'directory');
|
|
166
|
+
for (const project of projects) {
|
|
167
|
+
for (const entry of await fs.list(join(store.sessionsDir, project.name))) {
|
|
168
|
+
if (entry.kind === 'file' && SESSION_FILE.test(entry.name) && entry.name.startsWith(start))
|
|
169
|
+
ids.add(entry.name.slice(0, -'.jsonl'.length));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return [...ids].sort();
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The folder of another session in a project folder, for one whose head names none: the newest other session file's,
|
|
177
|
+
* read from its head, when Claude Code's project folder for it is this one. One more head read, on resume only.
|
|
178
|
+
*/
|
|
179
|
+
async function siblingFolder(store, found, fs) {
|
|
180
|
+
const dir = join(store.sessionsDir, found.group);
|
|
181
|
+
const others = (await fs.list(dir)).filter(entry => entry.kind === 'file' && SESSION_FILE.test(entry.name) && entry.name !== `${found.id}.jsonl`);
|
|
182
|
+
const candidates = (await Promise.all(others.map(async (entry) => {
|
|
183
|
+
const path = join(dir, entry.name);
|
|
184
|
+
const info = await fs.lstat(path);
|
|
185
|
+
if (info?.kind !== 'file')
|
|
186
|
+
return null;
|
|
187
|
+
return { cli: 'claude', id: entry.name.slice(0, -'.jsonl'.length), path, profile: store.profile, mtimeMs: info.mtimeMs, group: found.group };
|
|
188
|
+
}))).filter((candidate) => candidate !== null).sort(byRecency);
|
|
189
|
+
if (candidates.length === 0)
|
|
190
|
+
return null;
|
|
191
|
+
const read = await readClaudeCandidate(candidates[0], fs);
|
|
192
|
+
return read && read.row.cwd !== null && read.row.folderVerified ? read.row.cwd : null;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The session with this id in each store that holds it, from its newest file there. Each project folder is looked in
|
|
196
|
+
* for `<id>.jsonl` without opening anything; only the one file found in a store is opened, and, when its head names
|
|
197
|
+
* no folder and its project folder isn't this folder's (`cwd`), the newest other session in its project folder.
|
|
198
|
+
*/
|
|
199
|
+
export async function findClaudeSession(stores, id, options = {}) {
|
|
200
|
+
if (!isSessionId(id))
|
|
201
|
+
return [];
|
|
202
|
+
const fs = options.fs ?? nodeSessionStoreFs;
|
|
203
|
+
const name = `${id.toLowerCase()}.jsonl`;
|
|
204
|
+
const rows = [];
|
|
205
|
+
for (const store of stores) {
|
|
206
|
+
const projects = (await fs.list(store.sessionsDir)).filter(entry => entry.kind === 'directory');
|
|
207
|
+
const matches = (await Promise.all(projects.map(async (project) => {
|
|
208
|
+
const path = join(store.sessionsDir, project.name, name);
|
|
209
|
+
const info = await fs.lstat(path);
|
|
210
|
+
if (info?.kind !== 'file')
|
|
211
|
+
return null;
|
|
212
|
+
return { cli: 'claude', id: id.toLowerCase(), path, profile: store.profile, mtimeMs: info.mtimeMs, group: project.name };
|
|
213
|
+
}))).filter((candidate) => candidate !== null).sort(byRecency);
|
|
214
|
+
if (matches.length === 0)
|
|
215
|
+
continue;
|
|
216
|
+
const read = await readClaudeCandidate(matches[0], fs, { cwd: options.cwd ?? null });
|
|
217
|
+
if (!read)
|
|
218
|
+
continue;
|
|
219
|
+
const sibling = read.row.cwd === null ? await siblingFolder(store, matches[0], fs) : null;
|
|
220
|
+
rows.push(sibling === null ? read.row : placedIn(read.row, sibling));
|
|
221
|
+
}
|
|
222
|
+
return rows;
|
|
223
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
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
|
+
export interface CodexSessionHead {
|
|
11
|
+
/** Whether the rollout's first session_meta line was read. */
|
|
12
|
+
sawMeta: boolean;
|
|
13
|
+
id?: string;
|
|
14
|
+
cwd?: string;
|
|
15
|
+
/** session_meta's source: cli, vscode, exec, mcp…, or "other" for one that isn't a plain name. */
|
|
16
|
+
source?: string;
|
|
17
|
+
/** Set for a subagent's thread. */
|
|
18
|
+
parentThreadId?: string;
|
|
19
|
+
/** Whether the thread is attached to a parent's. */
|
|
20
|
+
attached: boolean;
|
|
21
|
+
/** The person's first request, as Codex's own list previews it. */
|
|
22
|
+
firstRequest?: string;
|
|
23
|
+
}
|
|
24
|
+
/** Reads a rollout's bytes as they come, in any chunks. */
|
|
25
|
+
export declare class CodexHeadScanner {
|
|
26
|
+
private readonly lineBytes;
|
|
27
|
+
private line;
|
|
28
|
+
private lineLength;
|
|
29
|
+
private oversized;
|
|
30
|
+
private readonly head;
|
|
31
|
+
private readonly metaOnly;
|
|
32
|
+
/** `metaOnly`: done once the session_meta line is read, for a caller that wants only the session's folder. */
|
|
33
|
+
constructor(options?: {
|
|
34
|
+
lineBytes?: number;
|
|
35
|
+
metaOnly?: boolean;
|
|
36
|
+
});
|
|
37
|
+
/**
|
|
38
|
+
* True once the head holds everything a row needs, so no more bytes are wanted: the folder and the first request, or
|
|
39
|
+
* a session_meta that rules the session out of the picker (its folder is all a lookup by id still needs).
|
|
40
|
+
*/
|
|
41
|
+
get done(): boolean;
|
|
42
|
+
push(chunk: Uint8Array): void;
|
|
43
|
+
/** The head so far; `whole` when the bytes were the whole file, so a last line without a newline is complete. */
|
|
44
|
+
end(whole: boolean): CodexSessionHead;
|
|
45
|
+
private append;
|
|
46
|
+
private finishLine;
|
|
47
|
+
private readLine;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Whether a session_meta leaves the session in the picker, as Codex's own list does: from the CLI or VS Code (or a
|
|
51
|
+
* rollout from before source was recorded), not a subagent's thread, and not attached to another.
|
|
52
|
+
*/
|
|
53
|
+
export declare function codexSessionListable(head: CodexSessionHead): boolean;
|
|
54
|
+
/** The head of a rollout from its first bytes. */
|
|
55
|
+
export declare function parseCodexSessionHead(bytes: Uint8Array, whole: boolean): CodexSessionHead;
|