@agentex/agent 0.0.24 → 0.0.26
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/CHANGELOG.md +338 -0
- package/LICENSE +21 -0
- package/README.md +52 -0
- package/dist/derived.d.ts +5 -3
- package/dist/derived.d.ts.map +1 -1
- package/dist/derived.js +11 -7
- package/dist/derived.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/providers/acp/index.d.ts +1 -1
- package/dist/providers/acp/index.d.ts.map +1 -1
- package/dist/providers/acp/index.js +5 -97
- package/dist/providers/acp/index.js.map +1 -1
- package/dist/providers/acp/session.d.ts +8 -1
- package/dist/providers/acp/session.d.ts.map +1 -1
- package/dist/providers/acp/session.js +94 -0
- package/dist/providers/acp/session.js.map +1 -1
- package/dist/providers/claude/attach.d.ts +8 -0
- package/dist/providers/claude/attach.d.ts.map +1 -0
- package/dist/providers/claude/attach.js +113 -0
- package/dist/providers/claude/attach.js.map +1 -0
- package/dist/providers/claude/goal-capability.d.ts +15 -0
- package/dist/providers/claude/goal-capability.d.ts.map +1 -0
- package/dist/providers/claude/goal-capability.js +20 -0
- package/dist/providers/claude/goal-capability.js.map +1 -0
- package/dist/providers/claude/index.d.ts.map +1 -1
- package/dist/providers/claude/index.js +8 -4
- package/dist/providers/claude/index.js.map +1 -1
- package/dist/providers/claude/session.d.ts +11 -9
- package/dist/providers/claude/session.d.ts.map +1 -1
- package/dist/providers/claude/session.js +29 -14
- package/dist/providers/claude/session.js.map +1 -1
- package/dist/providers/codex/attach.d.ts +9 -0
- package/dist/providers/codex/attach.d.ts.map +1 -0
- package/dist/providers/codex/attach.js +93 -0
- package/dist/providers/codex/attach.js.map +1 -0
- package/dist/providers/codex/goal-capability.d.ts +13 -0
- package/dist/providers/codex/goal-capability.d.ts.map +1 -0
- package/dist/providers/codex/goal-capability.js +18 -0
- package/dist/providers/codex/goal-capability.js.map +1 -0
- package/dist/providers/codex/index.d.ts +1 -0
- package/dist/providers/codex/index.d.ts.map +1 -1
- package/dist/providers/codex/index.js +9 -6
- package/dist/providers/codex/index.js.map +1 -1
- package/dist/providers/codex/session.d.ts +11 -7
- package/dist/providers/codex/session.d.ts.map +1 -1
- package/dist/providers/codex/session.js +24 -12
- package/dist/providers/codex/session.js.map +1 -1
- package/dist/providers/codex/transcript-normalize.d.ts +28 -0
- package/dist/providers/codex/transcript-normalize.d.ts.map +1 -0
- package/dist/providers/codex/transcript-normalize.js +191 -0
- package/dist/providers/codex/transcript-normalize.js.map +1 -0
- package/dist/providers/cursor/index.d.ts.map +1 -1
- package/dist/providers/cursor/index.js +2 -2
- package/dist/providers/cursor/index.js.map +1 -1
- package/dist/providers/openclaw/index.d.ts.map +1 -1
- package/dist/providers/openclaw/index.js +2 -2
- package/dist/providers/openclaw/index.js.map +1 -1
- package/dist/providers/opencode/index.d.ts.map +1 -1
- package/dist/providers/opencode/index.js +3 -5
- package/dist/providers/opencode/index.js.map +1 -1
- package/dist/providers/pi/index.d.ts.map +1 -1
- package/dist/providers/pi/index.js +3 -5
- package/dist/providers/pi/index.js.map +1 -1
- package/dist/providers/process/index.d.ts.map +1 -1
- package/dist/providers/process/index.js +2 -2
- package/dist/providers/process/index.js.map +1 -1
- package/dist/registry.d.ts +0 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +0 -4
- package/dist/registry.js.map +1 -1
- package/dist/sessions/index.d.ts +3 -0
- package/dist/sessions/index.d.ts.map +1 -0
- package/dist/sessions/index.js +2 -0
- package/dist/sessions/index.js.map +1 -0
- package/dist/sessions/record.d.ts +43 -0
- package/dist/sessions/record.d.ts.map +1 -0
- package/dist/sessions/record.js +85 -0
- package/dist/sessions/record.js.map +1 -0
- package/dist/types.d.ts +119 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/uuid.d.ts +7 -1
- package/dist/utils/uuid.d.ts.map +1 -1
- package/dist/utils/uuid.js +21 -1
- package/dist/utils/uuid.js.map +1 -1
- package/package.json +64 -7
- package/src/derived.ts +311 -0
- package/src/goals/controller.ts +442 -0
- package/src/goals/index.ts +21 -0
- package/src/goals/normalize.ts +173 -0
- package/src/goals/sentinel.ts +90 -0
- package/src/index.ts +270 -0
- package/src/providers/_shared/http-agent.ts +304 -0
- package/src/providers/acp/index.ts +103 -0
- package/src/providers/acp/parse.ts +131 -0
- package/src/providers/acp/session.ts +744 -0
- package/src/providers/claude/attach.ts +147 -0
- package/src/providers/claude/codec.ts +43 -0
- package/src/providers/claude/execute.ts +300 -0
- package/src/providers/claude/goal-capability.ts +21 -0
- package/src/providers/claude/index.ts +72 -0
- package/src/providers/claude/mcp.ts +82 -0
- package/src/providers/claude/parse.ts +824 -0
- package/src/providers/claude/session.ts +1192 -0
- package/src/providers/claude/transcript.ts +555 -0
- package/src/providers/codex/attach.ts +123 -0
- package/src/providers/codex/codec.ts +50 -0
- package/src/providers/codex/execute.ts +337 -0
- package/src/providers/codex/goal-capability.ts +19 -0
- package/src/providers/codex/index.ts +57 -0
- package/src/providers/codex/modes.ts +159 -0
- package/src/providers/codex/parse.ts +691 -0
- package/src/providers/codex/plan-mode.ts +49 -0
- package/src/providers/codex/session.ts +1287 -0
- package/src/providers/codex/transcript-normalize.ts +197 -0
- package/src/providers/codex/transcript.ts +487 -0
- package/src/providers/codex/usage-scanner.ts +178 -0
- package/src/providers/copilot/index.ts +19 -0
- package/src/providers/cursor/codec.ts +44 -0
- package/src/providers/cursor/execute.ts +271 -0
- package/src/providers/cursor/index.ts +25 -0
- package/src/providers/cursor/parse.ts +288 -0
- package/src/providers/gemini/index.ts +21 -0
- package/src/providers/openclaw/codec.ts +40 -0
- package/src/providers/openclaw/execute.ts +19 -0
- package/src/providers/openclaw/index.ts +29 -0
- package/src/providers/opencode/codec.ts +50 -0
- package/src/providers/opencode/event-parse.ts +141 -0
- package/src/providers/opencode/execute.ts +251 -0
- package/src/providers/opencode/http-session.ts +427 -0
- package/src/providers/opencode/index.ts +30 -0
- package/src/providers/opencode/parse.ts +203 -0
- package/src/providers/opencode/server.ts +0 -0
- package/src/providers/pi/codec.ts +44 -0
- package/src/providers/pi/execute.ts +297 -0
- package/src/providers/pi/index.ts +30 -0
- package/src/providers/pi/parse.ts +231 -0
- package/src/providers/pi/session.ts +381 -0
- package/src/providers/process/execute.ts +148 -0
- package/src/providers/process/index.ts +52 -0
- package/src/registry.ts +40 -0
- package/src/sessions/index.ts +8 -0
- package/src/sessions/record.ts +108 -0
- package/src/types.ts +1638 -0
- package/src/utils/ask-user-question.ts +57 -0
- package/src/utils/auth.ts +661 -0
- package/src/utils/binary.ts +179 -0
- package/src/utils/endpoint.ts +172 -0
- package/src/utils/env.ts +63 -0
- package/src/utils/execute-all.ts +68 -0
- package/src/utils/exit-plan-mode.ts +40 -0
- package/src/utils/instructions.ts +427 -0
- package/src/utils/process.ts +223 -0
- package/src/utils/runtime-config.ts +100 -0
- package/src/utils/runtime-homes.ts +49 -0
- package/src/utils/skill-commands.ts +493 -0
- package/src/utils/skills.ts +500 -0
- package/src/utils/template.ts +16 -0
- package/src/utils/tool-names.ts +51 -0
- package/src/utils/uuid.ts +21 -0
- package/src/utils/workspace.ts +156 -0
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code writes a durable JSONL transcript for every session under
|
|
3
|
+
* `<claudeHome>/projects/<sanitized-cwd>/<sessionId>.jsonl`. The on-disk lines
|
|
4
|
+
* use the same JSON shape Claude streams over stdout, so {@link parseStreamLine}
|
|
5
|
+
* handles them unchanged. These helpers cover the two parts the consuming
|
|
6
|
+
* host can't easily derive itself: where the file lives, and how to stream
|
|
7
|
+
* it back as `StreamEvent`s.
|
|
8
|
+
*
|
|
9
|
+
* Encoding rules are verified against Claude Code's open-source source
|
|
10
|
+
* (`sessionStoragePortable.ts:sanitizePath`):
|
|
11
|
+
* 1. Replace EVERY non-alphanumeric character with `-`
|
|
12
|
+
* (not just `/` and `.` — also `_`, space, `:`, etc.)
|
|
13
|
+
* 2. If the sanitized name exceeds {@link MAX_SANITIZED_LENGTH} (200),
|
|
14
|
+
* truncate and append a hash suffix
|
|
15
|
+
* 3. Canonicalize the cwd via `realpath` + NFC first so symlinks
|
|
16
|
+
* (e.g. macOS `/tmp` → `/private/tmp`) resolve to the same project dir
|
|
17
|
+
*
|
|
18
|
+
* The CLI does not expose a flag for the transcript path; the only source of
|
|
19
|
+
* truth is the open-source `sessionStoragePortable.ts`.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { createReadStream } from "node:fs";
|
|
23
|
+
import { readdir, realpath, stat, open as fsOpen } from "node:fs/promises";
|
|
24
|
+
import * as os from "node:os";
|
|
25
|
+
import * as path from "node:path";
|
|
26
|
+
import * as readline from "node:readline";
|
|
27
|
+
|
|
28
|
+
import { getDefaultRuntimeHome, getRuntimeHomeEnvVar } from "../../utils/runtime-homes.js";
|
|
29
|
+
import type { FoundTranscript, StreamEvent, TranscriptOps } from "../../types.js";
|
|
30
|
+
import { parseStreamLine } from "./parse.js";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Maximum length of a sanitized project-directory name before truncation +
|
|
34
|
+
* hash suffix kicks in. Mirrors Claude Code's `MAX_SANITIZED_LENGTH`. Most
|
|
35
|
+
* filesystems cap individual filename segments at 255 bytes; the gap leaves
|
|
36
|
+
* room for the hash suffix.
|
|
37
|
+
*/
|
|
38
|
+
export const MAX_SANITIZED_LENGTH = 200;
|
|
39
|
+
|
|
40
|
+
/** Bytes scanned from the tail of the file in {@link peekClaudeTranscript}. */
|
|
41
|
+
const PEEK_TAIL_BYTES = 16 * 1024;
|
|
42
|
+
|
|
43
|
+
/** Filter rule: skip these Claude wrapper-event types when streaming a transcript. */
|
|
44
|
+
const SKIP_ON_DISK_TYPES = new Set([
|
|
45
|
+
// Internal enqueue/dequeue bookkeeping that Claude writes for its own
|
|
46
|
+
// scheduler; the on-disk file is the only place these surface. They carry
|
|
47
|
+
// no user-visible content and shouldn't be replayed.
|
|
48
|
+
"queue-operation",
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* djb2 string hash returning an unsigned base-36 string. Deterministic across
|
|
53
|
+
* runtimes — Claude Code's source uses `Bun.hash` under Bun (a different
|
|
54
|
+
* algorithm), so for cwd paths longer than {@link MAX_SANITIZED_LENGTH} the
|
|
55
|
+
* exact directory name will differ between Bun and Node. {@link getClaudeTranscriptPath}
|
|
56
|
+
* compensates with a prefix-match fallback when the exact path is missing.
|
|
57
|
+
*/
|
|
58
|
+
function djb2Base36(input: string): string {
|
|
59
|
+
let hash = 0;
|
|
60
|
+
for (let i = 0; i < input.length; i++) {
|
|
61
|
+
hash = ((hash << 5) - hash + input.charCodeAt(i)) | 0;
|
|
62
|
+
}
|
|
63
|
+
return Math.abs(hash).toString(36);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Encode an absolute path into Claude's project-directory name. Mirrors
|
|
68
|
+
* `sanitizePath` in Claude Code's open-source `sessionStoragePortable.ts`.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* sanitizeProjectPath("/Users/foo/bar") // → "-Users-foo-bar"
|
|
72
|
+
* sanitizeProjectPath("/Users/foo/.config") // → "-Users-foo--config"
|
|
73
|
+
* sanitizeProjectPath("/Users/foo/my_app") // → "-Users-foo-my-app"
|
|
74
|
+
* // (underscore is non-alphanumeric)
|
|
75
|
+
*/
|
|
76
|
+
export function sanitizeProjectPath(name: string): string {
|
|
77
|
+
const sanitized = name.replace(/[^a-zA-Z0-9]/g, "-");
|
|
78
|
+
if (sanitized.length <= MAX_SANITIZED_LENGTH) return sanitized;
|
|
79
|
+
return `${sanitized.slice(0, MAX_SANITIZED_LENGTH)}-${djb2Base36(name)}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Resolve Claude's config home directory. Mirrors `getClaudeConfigHomeDir` in
|
|
84
|
+
* Claude Code, including the NFC normalization needed to keep paths consistent
|
|
85
|
+
* with macOS HFS+/APFS Unicode handling.
|
|
86
|
+
*/
|
|
87
|
+
export function resolveClaudeHome(override?: string): string {
|
|
88
|
+
if (override) return override.normalize("NFC");
|
|
89
|
+
const envVar = getRuntimeHomeEnvVar("claude");
|
|
90
|
+
const fromEnv = envVar ? process.env[envVar] : undefined;
|
|
91
|
+
const base = fromEnv ?? getDefaultRuntimeHome("claude") ?? path.join(os.homedir(), ".claude");
|
|
92
|
+
return base.normalize("NFC");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Canonicalize a cwd path to match what Claude Code stores. `realpath`
|
|
97
|
+
* resolves symlinks (`/tmp` → `/private/tmp` on macOS) and NFC unifies the
|
|
98
|
+
* two Unicode normalizations macOS accepts for filenames with accents.
|
|
99
|
+
*
|
|
100
|
+
* Returns the NFC-normalized input on `realpath` failure (e.g., directory
|
|
101
|
+
* was deleted after the session ran), since the directory name on disk was
|
|
102
|
+
* computed against whatever the cwd was at session start.
|
|
103
|
+
*/
|
|
104
|
+
export async function canonicalizeCwd(cwd: string): Promise<string> {
|
|
105
|
+
try {
|
|
106
|
+
return (await realpath(cwd)).normalize("NFC");
|
|
107
|
+
} catch {
|
|
108
|
+
return cwd.normalize("NFC");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
// Public API
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
export interface GetClaudeTranscriptPathOptions {
|
|
117
|
+
/** Claude's session id (UUID). Same value as the `session_id` field on stream events. */
|
|
118
|
+
sessionId: string;
|
|
119
|
+
/**
|
|
120
|
+
* The working directory Claude was launched in. Canonicalized via `realpath`
|
|
121
|
+
* + NFC before encoding, matching Claude's own behavior.
|
|
122
|
+
*/
|
|
123
|
+
cwd: string;
|
|
124
|
+
/**
|
|
125
|
+
* Override the Claude config home. Defaults to `$CLAUDE_CONFIG_DIR` or
|
|
126
|
+
* `~/.claude`. Useful in tests and for hosts pointing Claude at a
|
|
127
|
+
* non-standard home.
|
|
128
|
+
*/
|
|
129
|
+
claudeHome?: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface ClaudeTranscriptLocation {
|
|
133
|
+
/** Absolute path to the JSONL file. May not exist on disk yet. */
|
|
134
|
+
filePath: string;
|
|
135
|
+
/** The project-directory name (sanitized cwd) under `<claudeHome>/projects/`. */
|
|
136
|
+
projectDir: string;
|
|
137
|
+
/** The canonicalized cwd that was used to compute {@link projectDir}. */
|
|
138
|
+
canonicalCwd: string;
|
|
139
|
+
/** The Claude config home that was used. */
|
|
140
|
+
claudeHome: string;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Compute the on-disk JSONL path for a Claude session. Performs `realpath`
|
|
145
|
+
* canonicalization on the cwd and applies the same encoding rules Claude
|
|
146
|
+
* Code uses internally.
|
|
147
|
+
*
|
|
148
|
+
* For cwd paths sanitized longer than {@link MAX_SANITIZED_LENGTH}, the
|
|
149
|
+
* deterministic djb2 hash suffix may not match what Claude wrote (Claude Code
|
|
150
|
+
* uses `Bun.hash` under Bun). If the exact path doesn't exist and the
|
|
151
|
+
* sanitized name was truncated, this function falls back to a prefix scan
|
|
152
|
+
* under `<claudeHome>/projects/` and returns the first matching directory.
|
|
153
|
+
*/
|
|
154
|
+
export async function getClaudeTranscriptPath(
|
|
155
|
+
opts: GetClaudeTranscriptPathOptions,
|
|
156
|
+
): Promise<ClaudeTranscriptLocation> {
|
|
157
|
+
if (!opts.sessionId) throw new Error("getClaudeTranscriptPath: sessionId is required");
|
|
158
|
+
if (!opts.cwd) throw new Error("getClaudeTranscriptPath: cwd is required");
|
|
159
|
+
|
|
160
|
+
const claudeHome = resolveClaudeHome(opts.claudeHome);
|
|
161
|
+
const canonicalCwd = await canonicalizeCwd(opts.cwd);
|
|
162
|
+
const sanitized = sanitizeProjectPath(canonicalCwd);
|
|
163
|
+
const fileName = `${opts.sessionId}.jsonl`;
|
|
164
|
+
const projectsRoot = path.join(claudeHome, "projects");
|
|
165
|
+
|
|
166
|
+
// Primary: exact match. Covers the common case (short paths, same hash algorithm).
|
|
167
|
+
const exactPath = path.join(projectsRoot, sanitized, fileName);
|
|
168
|
+
if (await pathExists(exactPath)) {
|
|
169
|
+
return { filePath: exactPath, projectDir: sanitized, canonicalCwd, claudeHome };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Long-path fallback: Claude under Bun uses `Bun.hash` for the suffix;
|
|
173
|
+
// we use djb2. The truncated prefix is identical, so prefix-scan to find
|
|
174
|
+
// the actual on-disk directory. Mirrors open-source `findProjectDir`.
|
|
175
|
+
if (sanitized.length > MAX_SANITIZED_LENGTH) {
|
|
176
|
+
const prefix = sanitized.slice(0, MAX_SANITIZED_LENGTH);
|
|
177
|
+
try {
|
|
178
|
+
const entries = await readdir(projectsRoot, { withFileTypes: true });
|
|
179
|
+
for (const entry of entries) {
|
|
180
|
+
if (!entry.isDirectory()) continue;
|
|
181
|
+
if (!entry.name.startsWith(`${prefix}-`)) continue;
|
|
182
|
+
const candidate = path.join(projectsRoot, entry.name, fileName);
|
|
183
|
+
if (await pathExists(candidate)) {
|
|
184
|
+
return { filePath: candidate, projectDir: entry.name, canonicalCwd, claudeHome };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
} catch {
|
|
188
|
+
// projectsRoot missing or unreadable — fall through to deterministic path.
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return { filePath: exactPath, projectDir: sanitized, canonicalCwd, claudeHome };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ---------------------------------------------------------------------------
|
|
196
|
+
// Find-by-id (resume case: cwd unknown)
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
export interface FindClaudeTranscriptOptions {
|
|
200
|
+
/** Claude's session id (UUID). */
|
|
201
|
+
sessionId: string;
|
|
202
|
+
/** Override the Claude config home. */
|
|
203
|
+
claudeHome?: string;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface FoundClaudeTranscript {
|
|
207
|
+
/** Absolute path to the JSONL file. */
|
|
208
|
+
filePath: string;
|
|
209
|
+
/** The project-directory name (sanitized cwd) under `<claudeHome>/projects/`. */
|
|
210
|
+
projectDir: string;
|
|
211
|
+
/**
|
|
212
|
+
* The literal cwd Claude was launched with, recovered from the first
|
|
213
|
+
* `system.init` event in the transcript. `null` if the file has no init
|
|
214
|
+
* event (e.g., truncated transcript) or it never recorded a cwd.
|
|
215
|
+
*
|
|
216
|
+
* This is the only way to recover the original cwd — `projectDir` is the
|
|
217
|
+
* sanitized form, which is one-way (multiple cwds can collide on the same
|
|
218
|
+
* sanitized name, though it's rare).
|
|
219
|
+
*/
|
|
220
|
+
cwd: string | null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Scan `<claudeHome>/projects/*` looking for `<sessionId>.jsonl`. Use this
|
|
225
|
+
* when you have a session ID but don't know which cwd Claude was launched
|
|
226
|
+
* in — typical for resume-by-id flows.
|
|
227
|
+
*
|
|
228
|
+
* Session IDs are unique across project directories, so the first match is
|
|
229
|
+
* authoritative. The original cwd is recovered from the transcript's first
|
|
230
|
+
* `system.init` event (Claude writes one at session start carrying `cwd`).
|
|
231
|
+
*
|
|
232
|
+
* Returns `null` if no project directory contains the session file.
|
|
233
|
+
*/
|
|
234
|
+
export async function findClaudeTranscriptBySessionId(
|
|
235
|
+
opts: FindClaudeTranscriptOptions,
|
|
236
|
+
): Promise<FoundClaudeTranscript | null> {
|
|
237
|
+
if (!opts.sessionId) {
|
|
238
|
+
throw new Error("findClaudeTranscriptBySessionId: sessionId is required");
|
|
239
|
+
}
|
|
240
|
+
const claudeHome = resolveClaudeHome(opts.claudeHome);
|
|
241
|
+
const projectsRoot = path.join(claudeHome, "projects");
|
|
242
|
+
const fileName = `${opts.sessionId}.jsonl`;
|
|
243
|
+
|
|
244
|
+
let entries;
|
|
245
|
+
try {
|
|
246
|
+
entries = await readdir(projectsRoot, { withFileTypes: true });
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
for (const entry of entries) {
|
|
252
|
+
if (!entry.isDirectory()) continue;
|
|
253
|
+
const candidate = path.join(projectsRoot, entry.name, fileName);
|
|
254
|
+
if (!(await pathExists(candidate))) continue;
|
|
255
|
+
const cwd = await readCwdFromTranscript(candidate);
|
|
256
|
+
return { filePath: candidate, projectDir: entry.name, cwd };
|
|
257
|
+
}
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Read the cwd field from the first transcript line that carries one.
|
|
263
|
+
*
|
|
264
|
+
* Claude's on-disk format does NOT emit a `system.init` event the way the
|
|
265
|
+
* stream wire format does. Instead, every event line (`user`, `assistant`,
|
|
266
|
+
* etc.) carries its own `cwd`, `sessionId`, `gitBranch`, `version` envelope.
|
|
267
|
+
* Read the first few lines raw, extract the first `cwd` we find.
|
|
268
|
+
*
|
|
269
|
+
* Returns `null` if no line in the first ~50 carries a `cwd` field.
|
|
270
|
+
*/
|
|
271
|
+
async function readCwdFromTranscript(filePath: string): Promise<string | null> {
|
|
272
|
+
const fh = await fsOpen(filePath, "r").catch(() => null);
|
|
273
|
+
if (!fh) return null;
|
|
274
|
+
|
|
275
|
+
try {
|
|
276
|
+
const stream = fh.createReadStream({ encoding: "utf8", autoClose: false });
|
|
277
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
278
|
+
let count = 0;
|
|
279
|
+
try {
|
|
280
|
+
for await (const raw of rl) {
|
|
281
|
+
if (++count > 50) break;
|
|
282
|
+
const trimmed = raw.trim();
|
|
283
|
+
if (!trimmed) continue;
|
|
284
|
+
try {
|
|
285
|
+
const obj = JSON.parse(trimmed) as Record<string, unknown>;
|
|
286
|
+
// Outer envelope: every Claude line carries `cwd` at the top level.
|
|
287
|
+
if (typeof obj["cwd"] === "string" && obj["cwd"]) {
|
|
288
|
+
return obj["cwd"] as string;
|
|
289
|
+
}
|
|
290
|
+
// Forward-compat: streaming-style init events also have cwd.
|
|
291
|
+
if (
|
|
292
|
+
obj["type"] === "system" &&
|
|
293
|
+
obj["subtype"] === "init" &&
|
|
294
|
+
typeof obj["cwd"] === "string"
|
|
295
|
+
) {
|
|
296
|
+
return obj["cwd"] as string;
|
|
297
|
+
}
|
|
298
|
+
} catch {
|
|
299
|
+
// skip malformed
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
} finally {
|
|
303
|
+
rl.close();
|
|
304
|
+
stream.destroy();
|
|
305
|
+
}
|
|
306
|
+
} finally {
|
|
307
|
+
await fh.close();
|
|
308
|
+
}
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function pathExists(filePath: string): Promise<boolean> {
|
|
313
|
+
try {
|
|
314
|
+
await stat(filePath);
|
|
315
|
+
return true;
|
|
316
|
+
} catch {
|
|
317
|
+
return false;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// ---------------------------------------------------------------------------
|
|
322
|
+
// Streaming read
|
|
323
|
+
// ---------------------------------------------------------------------------
|
|
324
|
+
|
|
325
|
+
export interface ReadClaudeTranscriptOptions {
|
|
326
|
+
/** Absolute path to the JSONL file. */
|
|
327
|
+
filePath: string;
|
|
328
|
+
/**
|
|
329
|
+
* Byte offset to resume from. Must be line-aligned (the position immediately
|
|
330
|
+
* after a `\n`). Use an offset previously yielded by this function.
|
|
331
|
+
* Defaults to 0 (read from the start).
|
|
332
|
+
*/
|
|
333
|
+
fromOffset?: number;
|
|
334
|
+
/**
|
|
335
|
+
* Defensive dedup: if set, skip events whose {@link StreamEvent.eventId}
|
|
336
|
+
* matches and any events from the same line. Useful when `fromOffset` is
|
|
337
|
+
* missing or stale; the consumer's unique-index on `eventId` makes
|
|
338
|
+
* duplicates safe anyway, but this saves a round trip.
|
|
339
|
+
*
|
|
340
|
+
* Behavior: drop events up to and including the first one whose eventId
|
|
341
|
+
* matches; resume yielding from the next line.
|
|
342
|
+
*/
|
|
343
|
+
sinceEventId?: string;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export interface ClaudeTranscriptYield {
|
|
347
|
+
/** A parsed `StreamEvent` from the transcript. */
|
|
348
|
+
event: StreamEvent;
|
|
349
|
+
/**
|
|
350
|
+
* Byte offset immediately AFTER the trailing `\n` of the line this event
|
|
351
|
+
* came from. Pass this back as {@link ReadClaudeTranscriptOptions.fromOffset}
|
|
352
|
+
* to resume on the next line. Events sharing a line share an offset.
|
|
353
|
+
*/
|
|
354
|
+
offset: number;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Stream-read a Claude transcript JSONL, yielding parsed `StreamEvent`s.
|
|
359
|
+
*
|
|
360
|
+
* Behavior:
|
|
361
|
+
* - Returns an empty async iterable if the file doesn't exist (no throw).
|
|
362
|
+
* - Skips wrapper types in {@link SKIP_ON_DISK_TYPES} (currently `queue-operation`).
|
|
363
|
+
* - Skips lines that fail to parse as JSON (`parseStreamLine` returns []).
|
|
364
|
+
* - Seeks into the file with `createReadStream` so multi-megabyte transcripts
|
|
365
|
+
* don't load fully into memory.
|
|
366
|
+
*
|
|
367
|
+
* The yielded `offset` lets the caller checkpoint after each event and
|
|
368
|
+
* resume from that offset on the next call.
|
|
369
|
+
*/
|
|
370
|
+
export async function* readClaudeTranscript(
|
|
371
|
+
opts: ReadClaudeTranscriptOptions,
|
|
372
|
+
): AsyncIterable<ClaudeTranscriptYield> {
|
|
373
|
+
const { filePath, fromOffset = 0, sinceEventId } = opts;
|
|
374
|
+
|
|
375
|
+
// Fast-path: file missing → empty iterable, no throw.
|
|
376
|
+
if (!(await pathExists(filePath))) return;
|
|
377
|
+
|
|
378
|
+
const stream = createReadStream(filePath, { start: fromOffset, encoding: undefined });
|
|
379
|
+
|
|
380
|
+
// Suppress stray ENOENT (file deleted between stat and open) — readline
|
|
381
|
+
// raises the same condition through its own iterator, which we catch below.
|
|
382
|
+
stream.on("error", () => {});
|
|
383
|
+
|
|
384
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
385
|
+
|
|
386
|
+
let pos = fromOffset;
|
|
387
|
+
let stillSkippingPastSince = !!sinceEventId;
|
|
388
|
+
|
|
389
|
+
try {
|
|
390
|
+
for await (const line of rl) {
|
|
391
|
+
// readline strips the trailing `\n` (and the `\r` from `\r\n`). Claude
|
|
392
|
+
// writes Unix line endings, so we account for `\n` only. A `\r\n` file
|
|
393
|
+
// would yield offsets 1 byte short per line — accepted as a corner
|
|
394
|
+
// case; resume from such an offset would skip one stray `\r`.
|
|
395
|
+
const lineByteLen = Buffer.byteLength(line, "utf8");
|
|
396
|
+
pos += lineByteLen + 1;
|
|
397
|
+
|
|
398
|
+
if (!line) continue;
|
|
399
|
+
const trimmed = line.trim();
|
|
400
|
+
if (!trimmed) continue;
|
|
401
|
+
|
|
402
|
+
if (looksLikeSkippedType(trimmed)) continue;
|
|
403
|
+
|
|
404
|
+
const events = parseStreamLine(trimmed);
|
|
405
|
+
if (events.length === 0) continue;
|
|
406
|
+
|
|
407
|
+
if (stillSkippingPastSince) {
|
|
408
|
+
if (events.some((e) => e.eventId === sinceEventId)) {
|
|
409
|
+
// Found the boundary line — skip ALL events on it and resume from the next.
|
|
410
|
+
stillSkippingPastSince = false;
|
|
411
|
+
}
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
for (const event of events) {
|
|
416
|
+
yield { event, offset: pos };
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
} catch (err) {
|
|
420
|
+
// Swallow ENOENT (race: file deleted after the existence check); rethrow others.
|
|
421
|
+
const e = err as NodeJS.ErrnoException;
|
|
422
|
+
if (e?.code !== "ENOENT") throw err;
|
|
423
|
+
} finally {
|
|
424
|
+
rl.close();
|
|
425
|
+
stream.destroy();
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Quick pre-parse check for wrapper types we want to skip. Cheaper than a
|
|
431
|
+
* full `JSON.parse`; falls through to the parser if uncertain.
|
|
432
|
+
*/
|
|
433
|
+
function looksLikeSkippedType(line: string): boolean {
|
|
434
|
+
for (const t of SKIP_ON_DISK_TYPES) {
|
|
435
|
+
if (line.includes(`"type":"${t}"`) || line.includes(`"type": "${t}"`)) {
|
|
436
|
+
return true;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// ---------------------------------------------------------------------------
|
|
443
|
+
// Peek (cheap last-event read)
|
|
444
|
+
// ---------------------------------------------------------------------------
|
|
445
|
+
|
|
446
|
+
export interface ClaudePeekResult {
|
|
447
|
+
/** Last successfully parsed event, or null if the file is empty/missing/unparseable. */
|
|
448
|
+
lastEvent: StreamEvent | null;
|
|
449
|
+
/** Total size of the file in bytes, or null if the file is missing. */
|
|
450
|
+
size: number | null;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Drift-check primitive. Reads up to {@link PEEK_TAIL_BYTES} from the end of
|
|
455
|
+
* the file, parses the last complete line, and returns the last event plus
|
|
456
|
+
* total file size.
|
|
457
|
+
*
|
|
458
|
+
* Does NOT stream the whole file — designed to be called frequently as a
|
|
459
|
+
* cheap "has this changed since I last checked?" probe. Walks back through
|
|
460
|
+
* the buffer if the last line is a skipped wrapper type or fails to parse.
|
|
461
|
+
*
|
|
462
|
+
* Returns `{ lastEvent: null, size }` if the tail buffer holds no parseable
|
|
463
|
+
* line — caller should fall back to a full read if it needs guaranteed data.
|
|
464
|
+
*/
|
|
465
|
+
export async function peekClaudeTranscript(filePath: string): Promise<ClaudePeekResult> {
|
|
466
|
+
let size: number;
|
|
467
|
+
try {
|
|
468
|
+
const s = await stat(filePath);
|
|
469
|
+
size = s.size;
|
|
470
|
+
} catch {
|
|
471
|
+
return { lastEvent: null, size: null };
|
|
472
|
+
}
|
|
473
|
+
if (size === 0) return { lastEvent: null, size: 0 };
|
|
474
|
+
|
|
475
|
+
const readBytes = Math.min(PEEK_TAIL_BYTES, size);
|
|
476
|
+
const start = size - readBytes;
|
|
477
|
+
const startedMidFile = start > 0;
|
|
478
|
+
|
|
479
|
+
let handle;
|
|
480
|
+
try {
|
|
481
|
+
handle = await fsOpen(filePath, "r");
|
|
482
|
+
} catch {
|
|
483
|
+
return { lastEvent: null, size };
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
try {
|
|
487
|
+
const buf = Buffer.alloc(readBytes);
|
|
488
|
+
await handle.read(buf, 0, readBytes, start);
|
|
489
|
+
const text = buf.toString("utf8");
|
|
490
|
+
|
|
491
|
+
// Split on `\n`, drop the trailing empty entry from a final newline.
|
|
492
|
+
const lines = text.split("\n");
|
|
493
|
+
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
|
|
494
|
+
|
|
495
|
+
// If we started mid-file, line[0] is partial — never trust it.
|
|
496
|
+
const minIdx = startedMidFile ? 1 : 0;
|
|
497
|
+
|
|
498
|
+
for (let i = lines.length - 1; i >= minIdx; i--) {
|
|
499
|
+
const raw = lines[i];
|
|
500
|
+
if (raw === undefined) continue;
|
|
501
|
+
const trimmed = raw.trim();
|
|
502
|
+
if (!trimmed) continue;
|
|
503
|
+
if (looksLikeSkippedType(trimmed)) continue;
|
|
504
|
+
const events = parseStreamLine(trimmed);
|
|
505
|
+
const last = events[events.length - 1];
|
|
506
|
+
if (!last) continue;
|
|
507
|
+
return { lastEvent: last, size };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
return { lastEvent: null, size };
|
|
511
|
+
} finally {
|
|
512
|
+
await handle.close();
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// ---------------------------------------------------------------------------
|
|
517
|
+
// Polymorphic facade
|
|
518
|
+
// ---------------------------------------------------------------------------
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Polymorphic transcript ops for Claude. Delegates to the named functions
|
|
522
|
+
* above; mounted as `claudeProvider.transcript` so apps doing runtime-
|
|
523
|
+
* dispatched recovery can call `getProvider(name).transcript.find(...)`
|
|
524
|
+
* without a switch statement.
|
|
525
|
+
*
|
|
526
|
+
* Apps that know they're on Claude at compile time should prefer the named
|
|
527
|
+
* helpers (`getClaudeTranscriptPath`, `findClaudeTranscriptBySessionId`) —
|
|
528
|
+
* they return richer types (`canonicalCwd`, `projectDir`, `claudeHome`) that
|
|
529
|
+
* the polymorphic interface flattens away.
|
|
530
|
+
*/
|
|
531
|
+
export const claudeTranscriptOps: TranscriptOps<StreamEvent> = {
|
|
532
|
+
async find(opts): Promise<FoundTranscript | null> {
|
|
533
|
+
// Fast path: cwd hint provided → direct O(1) lookup.
|
|
534
|
+
if (opts.cwd) {
|
|
535
|
+
const loc = await getClaudeTranscriptPath({
|
|
536
|
+
sessionId: opts.sessionId,
|
|
537
|
+
cwd: opts.cwd,
|
|
538
|
+
});
|
|
539
|
+
if (await pathExists(loc.filePath)) {
|
|
540
|
+
return { filePath: loc.filePath, cwd: loc.canonicalCwd };
|
|
541
|
+
}
|
|
542
|
+
// cwd was wrong (e.g. session was launched in a different worktree);
|
|
543
|
+
// fall through to scan.
|
|
544
|
+
}
|
|
545
|
+
const found = await findClaudeTranscriptBySessionId({ sessionId: opts.sessionId });
|
|
546
|
+
if (!found) return null;
|
|
547
|
+
return { filePath: found.filePath, cwd: found.cwd };
|
|
548
|
+
},
|
|
549
|
+
read(opts) {
|
|
550
|
+
return readClaudeTranscript(opts);
|
|
551
|
+
},
|
|
552
|
+
peek(filePath) {
|
|
553
|
+
return peekClaudeTranscript(filePath);
|
|
554
|
+
},
|
|
555
|
+
};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AttachOptions,
|
|
3
|
+
CatchUpOptions,
|
|
4
|
+
CatchUpYield,
|
|
5
|
+
FoundTranscript,
|
|
6
|
+
LastTurnStatus,
|
|
7
|
+
SessionAttachment,
|
|
8
|
+
SessionContext,
|
|
9
|
+
SessionRecord,
|
|
10
|
+
} from "../../types.js";
|
|
11
|
+
import {
|
|
12
|
+
assertSessionRecord,
|
|
13
|
+
createSessionRecord,
|
|
14
|
+
MalformedSessionRecordError,
|
|
15
|
+
} from "../../sessions/record.js";
|
|
16
|
+
import { getRuntimeHomeEnvVar } from "../../utils/runtime-homes.js";
|
|
17
|
+
import { codexSessionCodec } from "./codec.js";
|
|
18
|
+
import {
|
|
19
|
+
getCodexTranscriptPath,
|
|
20
|
+
peekCodexTranscript,
|
|
21
|
+
readCodexCwd,
|
|
22
|
+
readCodexTranscript,
|
|
23
|
+
} from "./transcript.js";
|
|
24
|
+
import { codexLineToStreamEvents } from "./transcript-normalize.js";
|
|
25
|
+
// Heavy-on-heavy behind the lazy `attachSession` boundary (spec §5.3 / §9.6).
|
|
26
|
+
import { createCodexSession } from "./session.js";
|
|
27
|
+
|
|
28
|
+
/** Home-dir override derived from `opts.env` (same var the transcript helpers honor). */
|
|
29
|
+
function homeOverride(opts?: AttachOptions): string | undefined {
|
|
30
|
+
const key = getRuntimeHomeEnvVar("codex");
|
|
31
|
+
return key ? opts?.env?.[key] : undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const EMPTY: AsyncIterable<CatchUpYield> = {
|
|
35
|
+
async *[Symbol.asyncIterator]() {
|
|
36
|
+
/* no transcript → nothing to replay */
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Read-only reattachment to a durable Codex session. Same skeleton as Claude,
|
|
42
|
+
* with two deltas: classify via the rollout's last line, and replay through
|
|
43
|
+
* `codexLineToStreamEvents` (Codex has no wire ids, so `eventId` is always null
|
|
44
|
+
* — hosts gate replay dedup on their own running flag, per spec §9.7).
|
|
45
|
+
*/
|
|
46
|
+
export async function attachCodexSession(
|
|
47
|
+
record: SessionRecord,
|
|
48
|
+
opts?: AttachOptions,
|
|
49
|
+
): Promise<SessionAttachment> {
|
|
50
|
+
assertSessionRecord(record);
|
|
51
|
+
|
|
52
|
+
// 1. Normalize params through the codec.
|
|
53
|
+
const params = codexSessionCodec.deserialize(record.params);
|
|
54
|
+
if (!params) {
|
|
55
|
+
throw new MalformedSessionRecordError(
|
|
56
|
+
"codex session record params carry no usable sessionId",
|
|
57
|
+
"params",
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
const sessionId = params["sessionId"] as string;
|
|
61
|
+
const cwd =
|
|
62
|
+
(typeof params["cwd"] === "string" ? (params["cwd"] as string) : null) ?? record.cwd ?? null;
|
|
63
|
+
|
|
64
|
+
// 2. Locate the rollout (honoring opts.env home override). Codex indexes by
|
|
65
|
+
// date, not cwd, so cwd is not a lookup key here.
|
|
66
|
+
const codexHome = homeOverride(opts);
|
|
67
|
+
const loc = await getCodexTranscriptPath({
|
|
68
|
+
sessionId,
|
|
69
|
+
...(codexHome ? { codexHome } : {}),
|
|
70
|
+
});
|
|
71
|
+
let transcript: FoundTranscript | null = null;
|
|
72
|
+
if (loc) {
|
|
73
|
+
transcript = { filePath: loc.filePath, cwd: await readCodexCwd(loc.filePath) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Preserve the codec/record cwd on the normalized record (the transcript's
|
|
77
|
+
// own recovered cwd is exposed separately on `.transcript.cwd`).
|
|
78
|
+
const normalized = createSessionRecord({
|
|
79
|
+
providerType: "codex",
|
|
80
|
+
params,
|
|
81
|
+
cwd,
|
|
82
|
+
displayId: codexSessionCodec.getDisplayId?.(params) ?? null,
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// 3. Classify how the last persisted turn ended.
|
|
86
|
+
let lastTurn: LastTurnStatus = "unknown";
|
|
87
|
+
if (transcript) {
|
|
88
|
+
const { lastEvent } = await peekCodexTranscript(transcript.filePath);
|
|
89
|
+
if (lastEvent === null) lastTurn = "unknown";
|
|
90
|
+
else if (lastEvent.type === "event_msg" && lastEvent.payload?.["type"] === "task_complete")
|
|
91
|
+
lastTurn = "completed";
|
|
92
|
+
else lastTurn = "interrupted";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
record: normalized,
|
|
97
|
+
transcript,
|
|
98
|
+
lastTurn,
|
|
99
|
+
// 4. Replay: map each rollout line through the normalizer; one yield per
|
|
100
|
+
// produced event, all sharing the line's offset, eventId always null.
|
|
101
|
+
catchUp(catchOpts?: CatchUpOptions): AsyncIterable<CatchUpYield> {
|
|
102
|
+
if (!transcript) return EMPTY;
|
|
103
|
+
const filePath = transcript.filePath;
|
|
104
|
+
const sid = sessionId;
|
|
105
|
+
return {
|
|
106
|
+
async *[Symbol.asyncIterator]() {
|
|
107
|
+
for await (const { event: line, offset } of readCodexTranscript({
|
|
108
|
+
filePath,
|
|
109
|
+
...(catchOpts?.fromOffset !== undefined ? { fromOffset: catchOpts.fromOffset } : {}),
|
|
110
|
+
})) {
|
|
111
|
+
for (const event of codexLineToStreamEvents(line, { sessionId: sid })) {
|
|
112
|
+
yield { event, offset, eventId: null };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
},
|
|
118
|
+
// 5. Continue live — exactly `createSession` with the record's params.
|
|
119
|
+
resume(ctx?: SessionContext) {
|
|
120
|
+
return createCodexSession({ ...ctx, sessionParams: params });
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|