@deepagents/trajectory 0.0.0-stage → 7.54.0

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/dist/index.js ADDED
@@ -0,0 +1,977 @@
1
+ // packages/trajectory/src/atif.ts
2
+ var ATIF_SCHEMA_VERSION = "ATIF-v1.8";
3
+
4
+ // packages/trajectory/src/claude-code/adapter.ts
5
+ import { readFile, readdir } from "node:fs/promises";
6
+ import { join as join2 } from "node:path";
7
+
8
+ // packages/trajectory/src/errors.ts
9
+ var SessionReadError = class extends Error {
10
+ name = "SessionReadError";
11
+ path;
12
+ constructor(path, message, options) {
13
+ super(`${message}: ${path}`, options);
14
+ this.path = path;
15
+ }
16
+ };
17
+
18
+ // packages/trajectory/src/claude-code/session.ts
19
+ import { basename, dirname, join } from "node:path";
20
+ var SUBAGENT_FILE = /^agent-(.+)\.jsonl$/;
21
+ var placeInChain = /* @__PURE__ */ Symbol("placeInChain");
22
+ var ClaudeCodeSession = class _ClaudeCodeSession {
23
+ sessionId;
24
+ transcriptPath;
25
+ /** The run this segment belongs to: the first session id of its /clear chain (ADR 0007). */
26
+ runId;
27
+ /** The next segment's transcript, when the chain continues after this one. */
28
+ continuedBy;
29
+ constructor(sessionId, transcriptPath, runId, continuedBy) {
30
+ this.sessionId = sessionId;
31
+ this.transcriptPath = transcriptPath;
32
+ this.runId = runId;
33
+ this.continuedBy = continuedBy;
34
+ }
35
+ /** The session of a main transcript path, such as a hook's `transcript_path`. */
36
+ static fromTranscriptPath(path) {
37
+ const name = basename(path);
38
+ if (!name.endsWith(".jsonl") || basename(dirname(path)) === "subagents") {
39
+ throw new TypeError(
40
+ `not a Claude Code main transcript (expected <session-id>.jsonl; a subagent file is a ClaudeCodeSubagent): ${path}`
41
+ );
42
+ }
43
+ const sessionId = name.slice(0, -".jsonl".length);
44
+ return new _ClaudeCodeSession(sessionId, path, sessionId, void 0);
45
+ }
46
+ /** The chain gives each segment its run and its successor. */
47
+ static [placeInChain](session, runId, continuedBy) {
48
+ return new _ClaudeCodeSession(
49
+ session.sessionId,
50
+ session.transcriptPath,
51
+ runId,
52
+ continuedBy
53
+ );
54
+ }
55
+ /** The folder that holds this session's subagent transcripts. */
56
+ get subagentsPath() {
57
+ return join(dirname(this.transcriptPath), this.sessionId, "subagents");
58
+ }
59
+ };
60
+ var ClaudeCodeSubagent = class _ClaudeCodeSubagent {
61
+ agentId;
62
+ /** The session that started this subagent. */
63
+ sessionId;
64
+ transcriptPath;
65
+ constructor(agentId, sessionId, transcriptPath) {
66
+ this.agentId = agentId;
67
+ this.sessionId = sessionId;
68
+ this.transcriptPath = transcriptPath;
69
+ }
70
+ /** The subagent of a subagent transcript path, such as a hook's `agent_transcript_path`. */
71
+ static fromTranscriptPath(path) {
72
+ const match = SUBAGENT_FILE.exec(basename(path));
73
+ const subagents = dirname(path);
74
+ if (!match || basename(subagents) !== "subagents") {
75
+ throw new TypeError(
76
+ `not a Claude Code subagent transcript (expected <session-id>/subagents/agent-<id>.jsonl): ${path}`
77
+ );
78
+ }
79
+ return new _ClaudeCodeSubagent(match[1], basename(dirname(subagents)), path);
80
+ }
81
+ /** The `.meta.json` file beside the transcript, which names the call that spawned it. */
82
+ get metaPath() {
83
+ return this.transcriptPath.replace(/\.jsonl$/, ".meta.json");
84
+ }
85
+ /** ATIF's per-document id of this subagent's trajectory. */
86
+ get trajectoryId() {
87
+ return `agent-${this.agentId}`;
88
+ }
89
+ };
90
+
91
+ // packages/trajectory/src/claude-code/adapter.ts
92
+ var ClaudeCodeAdapter = class {
93
+ agent = "claude-code";
94
+ async read(session, options = {}) {
95
+ const path = session.transcriptPath;
96
+ let text;
97
+ try {
98
+ text = await readFile(path, "utf8");
99
+ } catch (cause) {
100
+ throw new SessionReadError(path, "could not read the transcript", {
101
+ cause
102
+ });
103
+ }
104
+ const diagnostics = [];
105
+ const steps = [];
106
+ const messages = /* @__PURE__ */ new Map();
107
+ const calls = /* @__PURE__ */ new Map();
108
+ const meta = {};
109
+ const unmapped = /* @__PURE__ */ new Map();
110
+ let version;
111
+ const isMain = session instanceof ClaudeCodeSession;
112
+ for (const { entry, line } of entries(text, path, diagnostics)) {
113
+ version ??= stringOr(entry.version);
114
+ if (isMain && entry.isSidechain === true) {
115
+ diagnostics.push({
116
+ code: "sidechain_entry",
117
+ path,
118
+ line,
119
+ message: "an isSidechain row inside a main transcript belongs to a subagent"
120
+ });
121
+ continue;
122
+ }
123
+ if (entry.type === "assistant") {
124
+ const step = agentStep(entry, messages, steps.length + 1);
125
+ if (step.step_id === steps.length + 1) steps.push(step);
126
+ for (const call of step.tool_calls ?? [])
127
+ calls.set(call.tool_call_id, step);
128
+ } else if (entry.type === "user" && toolResults(entry).length > 0) {
129
+ for (const block of toolResults(entry)) {
130
+ const id = stringOr(block.tool_use_id) ?? "";
131
+ const caller = calls.get(id);
132
+ if (!caller) {
133
+ diagnostics.push({
134
+ code: "orphan_tool_result",
135
+ path,
136
+ line,
137
+ message: `no call ${id} in the transcript for this tool result`
138
+ });
139
+ continue;
140
+ }
141
+ caller.observation ??= { results: [] };
142
+ caller.observation.results.push(observationResult(entry, block));
143
+ }
144
+ } else if (entry.type === "user") {
145
+ steps.push(personStep(entry, steps.length + 1));
146
+ } else if (entry.type === "attachment" && record(entry.attachment)?.type === "queued_command") {
147
+ steps.push(queuedStep(entry, steps.length + 1));
148
+ } else if (entry.type === "attachment") {
149
+ steps.push(attachmentStep(entry, steps.length + 1));
150
+ } else if (entry.type === "system") {
151
+ steps.push(systemRowStep(entry, steps.length + 1));
152
+ } else if (!collectSessionEntry(entry, meta)) {
153
+ const type = stringOr(entry.type) ?? "(no type)";
154
+ unmapped.set(type, (unmapped.get(type) ?? 0) + 1);
155
+ }
156
+ }
157
+ for (const [entryType, count] of unmapped) {
158
+ diagnostics.push({
159
+ code: "unmapped_entry",
160
+ path,
161
+ entryType,
162
+ count,
163
+ message: `${count} ${entryType} entries are bookkeeping with no step`
164
+ });
165
+ }
166
+ const [first, ...rest] = steps;
167
+ if (!first) {
168
+ throw new SessionReadError(path, "the transcript holds no step");
169
+ }
170
+ const model = steps.find(
171
+ (step) => step.source === "agent" && step.model_name != null
172
+ )?.model_name;
173
+ const trajectory = {
174
+ schema_version: ATIF_SCHEMA_VERSION,
175
+ ...isMain ? {
176
+ session_id: session.runId,
177
+ ...session.continuedBy ? { continued_trajectory_ref: session.continuedBy } : {}
178
+ } : {
179
+ session_id: session.sessionId,
180
+ trajectory_id: session.trajectoryId
181
+ },
182
+ agent: {
183
+ name: this.agent,
184
+ version: version ?? "unknown",
185
+ ...model ? { model_name: model } : {}
186
+ },
187
+ steps: [first, ...rest],
188
+ final_metrics: finalMetrics(steps),
189
+ ...Object.keys(meta).length > 0 ? { extra: { claude_code: meta } } : {}
190
+ };
191
+ if (isMain && options.subagents !== false) {
192
+ const embedded = await this.#subagents(session, trajectory, diagnostics);
193
+ if (embedded.length > 0) trajectory.subagent_trajectories = embedded;
194
+ }
195
+ return { trajectory, diagnostics };
196
+ }
197
+ /**
198
+ * Each `<session>/subagents/agent-*.jsonl`, in name order, as an embedded
199
+ * trajectory. The spawning call's result refers to it through the meta
200
+ * file's `toolUseId`, searched in the root and in every other subagent, so a
201
+ * subagent that another subagent started links too.
202
+ */
203
+ async #subagents(session, root, diagnostics) {
204
+ let names;
205
+ try {
206
+ names = await readdir(session.subagentsPath);
207
+ } catch (error) {
208
+ if (errnoCode(error) === "ENOENT") return [];
209
+ throw new SessionReadError(
210
+ session.subagentsPath,
211
+ "could not list the subagents",
212
+ {
213
+ cause: error
214
+ }
215
+ );
216
+ }
217
+ const embedded = [];
218
+ for (const name of names.filter((file) => /^agent-.+\.jsonl$/.test(file)).toSorted()) {
219
+ const subagent = ClaudeCodeSubagent.fromTranscriptPath(
220
+ join2(session.subagentsPath, name)
221
+ );
222
+ try {
223
+ const result = await this.read(subagent, { subagents: false });
224
+ diagnostics.push(...result.diagnostics);
225
+ embedded.push({ subagent, trajectory: result.trajectory });
226
+ } catch (error) {
227
+ if (!(error instanceof SessionReadError)) throw error;
228
+ diagnostics.push({
229
+ code: "unreadable_subagent",
230
+ path: subagent.transcriptPath,
231
+ message: error.message
232
+ });
233
+ }
234
+ }
235
+ const results = /* @__PURE__ */ new Map();
236
+ for (const trajectory of [
237
+ root,
238
+ ...embedded.map((entry) => entry.trajectory)
239
+ ]) {
240
+ for (const step of trajectory.steps) {
241
+ for (const result of step.observation?.results ?? []) {
242
+ if (result.source_call_id) results.set(result.source_call_id, result);
243
+ }
244
+ }
245
+ }
246
+ for (const { subagent, trajectory } of embedded) {
247
+ const spawnedBy = stringOr(
248
+ record(await readJson(subagent.metaPath))?.toolUseId
249
+ );
250
+ const result = spawnedBy ? results.get(spawnedBy) : void 0;
251
+ if (!result) {
252
+ diagnostics.push({
253
+ code: "unlinked_subagent",
254
+ path: subagent.transcriptPath,
255
+ message: spawnedBy ? `no result of call ${spawnedBy} spawned this subagent` : "no meta file names the call that spawned this subagent"
256
+ });
257
+ continue;
258
+ }
259
+ result.subagent_trajectory_ref = [
260
+ ...result.subagent_trajectory_ref ?? [],
261
+ {
262
+ trajectory_id: trajectory.trajectory_id,
263
+ session_id: trajectory.session_id
264
+ }
265
+ ];
266
+ }
267
+ return embedded.map((entry) => entry.trajectory);
268
+ }
269
+ };
270
+ function personStep(entry, stepId) {
271
+ const origin = record(entry.origin)?.kind;
272
+ const isMeta = entry.isMeta === true;
273
+ const message = textOf(record(entry.message)?.content);
274
+ const claudeCode = {
275
+ ...identity(entry),
276
+ ...typeof origin === "string" ? { origin } : {},
277
+ ...isMeta ? { is_meta: true } : {}
278
+ };
279
+ const source = typeof origin === "string" || !isMeta ? "user" : "system";
280
+ return {
281
+ step_id: stepId,
282
+ source,
283
+ timestamp: stringOr(entry.timestamp),
284
+ message,
285
+ extra: { claude_code: claudeCode }
286
+ };
287
+ }
288
+ function agentStep(entry, messages, nextStepId) {
289
+ const message = record(entry.message) ?? {};
290
+ const id = stringOr(message.id) ?? stringOr(entry.uuid) ?? String(nextStepId);
291
+ let known = messages.get(id);
292
+ if (!known) {
293
+ const claudeCode2 = { ...identity(entry), message_id: id };
294
+ known = {
295
+ claudeCode: claudeCode2,
296
+ step: {
297
+ step_id: nextStepId,
298
+ source: "agent",
299
+ timestamp: stringOr(entry.timestamp),
300
+ message: "",
301
+ extra: { claude_code: claudeCode2 }
302
+ }
303
+ };
304
+ messages.set(id, known);
305
+ }
306
+ const { step, claudeCode } = known;
307
+ const model = stringOr(message.model);
308
+ if (model && model !== SYNTHETIC_MODEL) step.model_name = model;
309
+ const requestId = stringOr(entry.requestId);
310
+ if (requestId) claudeCode.request_id = requestId;
311
+ const stopReason = stringOr(message.stop_reason);
312
+ if (stopReason) claudeCode.stop_reason = stopReason;
313
+ const usage = record(message.usage);
314
+ if (usage) step.metrics = metricsOf(usage);
315
+ for (const block of Array.isArray(message.content) ? message.content : []) {
316
+ const part = record(block);
317
+ if (part?.type === "text" && typeof part.text === "string") {
318
+ step.message = step.message === "" ? part.text : `${String(step.message)}
319
+ ${part.text}`;
320
+ } else if (part?.type === "thinking" && typeof part.thinking === "string") {
321
+ step.reasoning_content = step.reasoning_content == null ? part.thinking : `${step.reasoning_content}
322
+ ${part.thinking}`;
323
+ } else if (part?.type === "tool_use") {
324
+ step.tool_calls ??= [];
325
+ step.tool_calls.push({
326
+ tool_call_id: stringOr(part.id) ?? "",
327
+ function_name: stringOr(part.name) ?? "",
328
+ arguments: record(part.input) ?? {}
329
+ });
330
+ }
331
+ }
332
+ return step;
333
+ }
334
+ var SYNTHETIC_MODEL = "<synthetic>";
335
+ function metricsOf(usage) {
336
+ const input = numberOr(usage.input_tokens);
337
+ const cacheCreation = numberOr(usage.cache_creation_input_tokens);
338
+ const cacheRead = numberOr(usage.cache_read_input_tokens);
339
+ return {
340
+ prompt_tokens: input + cacheCreation + cacheRead,
341
+ completion_tokens: numberOr(usage.output_tokens),
342
+ cached_tokens: cacheRead,
343
+ extra: {
344
+ input_tokens: input,
345
+ cache_creation_input_tokens: cacheCreation,
346
+ cache_read_input_tokens: cacheRead
347
+ }
348
+ };
349
+ }
350
+ function toolResults(entry) {
351
+ const content = record(entry.message)?.content;
352
+ return Array.isArray(content) ? content.flatMap(
353
+ (block) => isRecord(block) && block.type === "tool_result" ? [block] : []
354
+ ) : [];
355
+ }
356
+ function observationResult(entry, block) {
357
+ const content = typeof block.content === "string" ? block.content : textParts(block.content);
358
+ return {
359
+ source_call_id: stringOr(block.tool_use_id),
360
+ content,
361
+ extra: {
362
+ claude_code: {
363
+ ...identity(entry),
364
+ is_error: block.is_error === true,
365
+ ...entry.toolUseResult === void 0 ? {} : { tool_use_result: entry.toolUseResult }
366
+ }
367
+ }
368
+ };
369
+ }
370
+ function textParts(content) {
371
+ if (!Array.isArray(content)) return [];
372
+ return content.flatMap(
373
+ (block) => isRecord(block) && block.type === "text" && typeof block.text === "string" ? [{ type: "text", text: block.text }] : []
374
+ );
375
+ }
376
+ function numberOr(value) {
377
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
378
+ }
379
+ function attachmentStep(entry, stepId) {
380
+ const attachment = record(entry.attachment) ?? {};
381
+ const content = attachment.content;
382
+ let message = "";
383
+ if (Array.isArray(content)) {
384
+ message = content.filter((part) => typeof part === "string").join("\n");
385
+ } else if (typeof content === "string") {
386
+ message = content;
387
+ }
388
+ return {
389
+ step_id: stepId,
390
+ source: "system",
391
+ timestamp: stringOr(entry.timestamp),
392
+ message,
393
+ extra: { claude_code: { ...identity(entry), attachment } }
394
+ };
395
+ }
396
+ function systemRowStep(entry, stepId) {
397
+ return {
398
+ step_id: stepId,
399
+ source: "system",
400
+ timestamp: stringOr(entry.timestamp),
401
+ message: typeof entry.content === "string" ? entry.content : "",
402
+ extra: { claude_code: { ...identity(entry), system: entry } }
403
+ };
404
+ }
405
+ function collectSessionEntry(entry, meta) {
406
+ switch (entry.type) {
407
+ case "derived-from":
408
+ meta.derived_from = Array.isArray(entry.sessions) ? entry.sessions : [];
409
+ return true;
410
+ case "ai-title":
411
+ if (typeof entry.aiTitle === "string") meta.ai_title = entry.aiTitle;
412
+ return true;
413
+ case "custom-title":
414
+ if (typeof entry.customTitle === "string")
415
+ meta.custom_title = entry.customTitle;
416
+ return true;
417
+ case "summary":
418
+ if (typeof entry.summary === "string") {
419
+ const summaries = Array.isArray(meta.summaries) ? meta.summaries : [];
420
+ meta.summaries = [...summaries, entry.summary];
421
+ }
422
+ return true;
423
+ case "pr-link": {
424
+ const links = Array.isArray(meta.pr_links) ? meta.pr_links : [];
425
+ meta.pr_links = [...links, entry];
426
+ return true;
427
+ }
428
+ default:
429
+ return false;
430
+ }
431
+ }
432
+ function finalMetrics(steps) {
433
+ let prompt = 0;
434
+ let completion = 0;
435
+ let cached = 0;
436
+ for (const step of steps) {
437
+ if (step.source !== "agent" || !step.metrics) continue;
438
+ prompt += step.metrics.prompt_tokens ?? 0;
439
+ completion += step.metrics.completion_tokens ?? 0;
440
+ cached += step.metrics.cached_tokens ?? 0;
441
+ }
442
+ return {
443
+ total_prompt_tokens: prompt,
444
+ total_completion_tokens: completion,
445
+ total_cached_tokens: cached,
446
+ total_steps: steps.length
447
+ };
448
+ }
449
+ function queuedStep(entry, stepId) {
450
+ const attachment = record(entry.attachment) ?? {};
451
+ const origin = record(attachment.origin)?.kind;
452
+ return {
453
+ step_id: stepId,
454
+ source: "user",
455
+ timestamp: stringOr(entry.timestamp),
456
+ message: typeof attachment.prompt === "string" ? attachment.prompt : "",
457
+ extra: {
458
+ claude_code: {
459
+ ...identity(entry),
460
+ ...typeof origin === "string" ? { origin } : {},
461
+ queued: true
462
+ }
463
+ }
464
+ };
465
+ }
466
+ function identity(entry) {
467
+ const keys = {
468
+ uuid: entry.uuid,
469
+ parent_uuid: entry.parentUuid,
470
+ timestamp: entry.timestamp,
471
+ cwd: entry.cwd,
472
+ entrypoint: entry.entrypoint,
473
+ prompt_id: entry.promptId
474
+ };
475
+ return Object.fromEntries(
476
+ Object.entries(keys).filter(([, value]) => value !== void 0)
477
+ );
478
+ }
479
+ function textOf(content) {
480
+ if (typeof content === "string") return content;
481
+ if (!Array.isArray(content)) return "";
482
+ return content.flatMap(
483
+ (block) => isRecord(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []
484
+ ).join("\n");
485
+ }
486
+ function isRecord(value) {
487
+ return typeof value === "object" && value !== null && !Array.isArray(value);
488
+ }
489
+ function record(value) {
490
+ return isRecord(value) ? value : void 0;
491
+ }
492
+ function errnoCode(error) {
493
+ return isRecord(error) ? error.code : void 0;
494
+ }
495
+ function stringOr(value) {
496
+ return typeof value === "string" ? value : void 0;
497
+ }
498
+ function* entries(text, path, diagnostics) {
499
+ const lines = text.split("\n");
500
+ for (const [index, raw] of lines.entries()) {
501
+ if (raw.trim() === "") continue;
502
+ const line = index + 1;
503
+ const entry = parseObject(raw);
504
+ if (entry) {
505
+ yield { entry, line };
506
+ } else if (index === lines.length - 1) {
507
+ diagnostics.push({
508
+ code: "partial_last_line",
509
+ path,
510
+ line,
511
+ message: "the last line is not yet complete JSON; the agent may still be writing it"
512
+ });
513
+ } else {
514
+ diagnostics.push({
515
+ code: "invalid_json_line",
516
+ path,
517
+ line,
518
+ message: "the line is not a JSON object"
519
+ });
520
+ }
521
+ }
522
+ }
523
+ function parseObject(raw) {
524
+ try {
525
+ const value = JSON.parse(raw);
526
+ return record(value);
527
+ } catch {
528
+ return void 0;
529
+ }
530
+ }
531
+ async function readJson(path) {
532
+ try {
533
+ return JSON.parse(await readFile(path, "utf8"));
534
+ } catch {
535
+ return void 0;
536
+ }
537
+ }
538
+
539
+ // packages/trajectory/src/claude-code/store.ts
540
+ import { readFile as readFile2, readdir as readdir2, stat } from "node:fs/promises";
541
+ import { dirname as dirname2, join as join3 } from "node:path";
542
+ var ClaudeCodeStore = class {
543
+ root;
544
+ constructor(options) {
545
+ this.root = options.root;
546
+ }
547
+ /**
548
+ * Each main transcript (`projects/<project>/<id>.jsonl`) changed at or after
549
+ * `since`, newest first. It reads file times only, never their content, and
550
+ * subagent transcripts are not sessions.
551
+ */
552
+ async *sessions(options) {
553
+ const since = options.since.getTime();
554
+ const found = [];
555
+ for (const project of await this.#projects()) {
556
+ for (const name of await listOrEmpty(project)) {
557
+ if (!name.endsWith(".jsonl")) continue;
558
+ const path = join3(project, name);
559
+ const changed = (await stat(path)).mtimeMs;
560
+ if (changed >= since) found.push({ path, changed });
561
+ }
562
+ }
563
+ for (const { path } of found.toSorted((a, b) => b.changed - a.changed)) {
564
+ yield ClaudeCodeSession.fromTranscriptPath(path);
565
+ }
566
+ }
567
+ /** The session whose transcript a project holds, or undefined when none does. */
568
+ async session(sessionId) {
569
+ if (!isSessionId(sessionId)) return void 0;
570
+ for (const project of await this.#projects()) {
571
+ const path = join3(project, `${sessionId}.jsonl`);
572
+ if (await isFile(path)) return ClaudeCodeSession.fromTranscriptPath(path);
573
+ }
574
+ return void 0;
575
+ }
576
+ /**
577
+ * The segments of the session's /clear chain, oldest first (ADR 0007, as
578
+ * agent-plugin housekeeping's `lib/session.mjs` walks it). It follows every
579
+ * `claude_code_session` a `derived-from` entry names, whatever its `via`,
580
+ * skips ids already in the chain (a resume names its own session), and looks
581
+ * beside the current transcript before every project. Each segment carries
582
+ * the chain's first id as its run and the next segment's transcript.
583
+ */
584
+ async chain(session) {
585
+ const seen = /* @__PURE__ */ new Set();
586
+ const found = [];
587
+ const missing = [];
588
+ const queue = [
589
+ { id: session.sessionId, segment: session }
590
+ ];
591
+ for (let next = queue.shift(); next; next = queue.shift()) {
592
+ if (seen.has(next.id)) continue;
593
+ seen.add(next.id);
594
+ if (!next.segment) {
595
+ missing.push(next.id);
596
+ continue;
597
+ }
598
+ found.push(next.segment);
599
+ for (const id of await derivedFrom(next.segment.transcriptPath)) {
600
+ if (seen.has(id)) continue;
601
+ const beside = join3(
602
+ dirname2(next.segment.transcriptPath),
603
+ `${id}.jsonl`
604
+ );
605
+ const segment = isSessionId(id) && await isFile(beside) ? ClaudeCodeSession.fromTranscriptPath(beside) : await this.session(id);
606
+ queue.push({ id, segment });
607
+ }
608
+ }
609
+ const oldestFirst = found.toReversed();
610
+ const runId = oldestFirst[0]?.sessionId ?? session.sessionId;
611
+ return {
612
+ sessions: oldestFirst.map(
613
+ (segment, index) => ClaudeCodeSession[placeInChain](
614
+ segment,
615
+ runId,
616
+ oldestFirst[index + 1]?.transcriptPath
617
+ )
618
+ ),
619
+ missing
620
+ };
621
+ }
622
+ async #projects() {
623
+ const projects = join3(this.root, "projects");
624
+ const names = await listOrEmpty(projects);
625
+ return names.map((name) => join3(projects, name));
626
+ }
627
+ };
628
+ async function derivedFrom(path) {
629
+ let text;
630
+ try {
631
+ text = await readFile2(path, "utf8");
632
+ } catch (cause) {
633
+ throw new SessionReadError(path, "could not read the transcript", {
634
+ cause
635
+ });
636
+ }
637
+ const ids = [];
638
+ for (const line of text.split("\n")) {
639
+ if (!line.includes('"derived-from"')) continue;
640
+ let entry;
641
+ try {
642
+ entry = JSON.parse(line);
643
+ } catch {
644
+ continue;
645
+ }
646
+ if (!isRecord2(entry) || entry.type !== "derived-from" || !Array.isArray(entry.sessions)) {
647
+ continue;
648
+ }
649
+ for (const from of entry.sessions) {
650
+ if (isRecord2(from) && from.type === "claude_code_session" && typeof from.id === "string") {
651
+ ids.push(from.id);
652
+ }
653
+ }
654
+ }
655
+ return ids;
656
+ }
657
+ async function listOrEmpty(path) {
658
+ try {
659
+ return await readdir2(path);
660
+ } catch (error) {
661
+ const code = isRecord2(error) ? error.code : void 0;
662
+ if (code === "ENOENT" || code === "ENOTDIR") return [];
663
+ throw error;
664
+ }
665
+ }
666
+ async function isFile(path) {
667
+ try {
668
+ return (await stat(path)).isFile();
669
+ } catch (error) {
670
+ if (isRecord2(error) && error.code === "ENOENT") return false;
671
+ throw error;
672
+ }
673
+ }
674
+ function isSessionId(id) {
675
+ return id !== "" && id !== "." && id !== ".." && !/[/\\]/.test(id);
676
+ }
677
+ function isRecord2(value) {
678
+ return typeof value === "object" && value !== null && !Array.isArray(value);
679
+ }
680
+
681
+ // packages/trajectory/src/codex/adapter.ts
682
+ import {
683
+ convertCodexSession,
684
+ parseRolloutFileName
685
+ } from "@alwaysmeticulous/agent-traces";
686
+ import { readFile as readFile3 } from "node:fs/promises";
687
+ import { basename as basename2 } from "node:path";
688
+ import { zstdDecompressSync } from "node:zlib";
689
+ var CONVERTER = "@deepagents/trajectory";
690
+ var CodexAdapter = class {
691
+ agent = "codex";
692
+ async read(thread, options = {}) {
693
+ const root = await Promise.all(thread.rolloutPaths.map(rolloutText));
694
+ const subagents = options.subagents === false ? [] : await Promise.all(
695
+ thread.subagents.map(async (subagent) => ({
696
+ threadId: subagent.threadId,
697
+ files: await Promise.all(subagent.rolloutPaths.map(rolloutText))
698
+ }))
699
+ );
700
+ const { trajectory } = convertCodexSession(
701
+ {
702
+ sessionId: thread.threadId,
703
+ root,
704
+ subagents,
705
+ threadName: null,
706
+ readFallbackGitBranch: () => null
707
+ },
708
+ CONVERTER
709
+ );
710
+ const converted = toTrajectory(trajectory);
711
+ if (!converted) {
712
+ throw new SessionReadError(
713
+ thread.rolloutPaths[0] ?? thread.threadId,
714
+ "the rollout holds no step"
715
+ );
716
+ }
717
+ return { trajectory: converted, diagnostics: [] };
718
+ }
719
+ };
720
+ async function rolloutText(path) {
721
+ let text;
722
+ try {
723
+ const bytes = await readFile3(path);
724
+ text = (path.endsWith(".zst") ? zstdDecompressSync(bytes) : bytes).toString(
725
+ "utf8"
726
+ );
727
+ } catch (cause) {
728
+ throw new SessionReadError(path, "could not read or decode the rollout", {
729
+ cause
730
+ });
731
+ }
732
+ const name = basename2(path).replace(/\.zst$/, "");
733
+ return { rolloutId: parseRolloutFileName(name)?.rolloutId ?? name, text };
734
+ }
735
+ function toTrajectory(source) {
736
+ const [first, ...rest] = source.steps.map(toStep);
737
+ if (!first) return void 0;
738
+ const subagents = (source.subagent_trajectories ?? []).flatMap((sub) => {
739
+ const converted = toTrajectory(sub);
740
+ return converted ? [converted] : [];
741
+ });
742
+ return {
743
+ schema_version: ATIF_SCHEMA_VERSION,
744
+ session_id: source.session_id,
745
+ trajectory_id: source.trajectory_id,
746
+ agent: {
747
+ name: source.agent.name,
748
+ version: source.agent.version,
749
+ model_name: source.agent.model_name,
750
+ tool_definitions: source.agent.tool_definitions?.flatMap(
751
+ (tool) => isRecord3(tool) ? [tool] : []
752
+ ),
753
+ extra: source.agent.extra
754
+ },
755
+ steps: [first, ...rest],
756
+ notes: source.notes,
757
+ final_metrics: source.final_metrics,
758
+ continued_trajectory_ref: source.continued_trajectory_ref,
759
+ extra: source.extra,
760
+ ...subagents.length > 0 ? { subagent_trajectories: subagents } : {}
761
+ };
762
+ }
763
+ function toStep(step) {
764
+ const base = {
765
+ step_id: step.step_id,
766
+ timestamp: step.timestamp,
767
+ message: toMessage(step.message),
768
+ observation: toObservation(step.observation),
769
+ is_copied_context: step.is_copied_context,
770
+ llm_call_count: step.llm_call_count,
771
+ extra: step.extra
772
+ };
773
+ switch (step.source) {
774
+ case "agent":
775
+ return {
776
+ ...base,
777
+ source: "agent",
778
+ model_name: step.model_name,
779
+ reasoning_effort: step.reasoning_effort,
780
+ reasoning_content: step.reasoning_content,
781
+ tool_calls: step.tool_calls,
782
+ metrics: step.metrics
783
+ };
784
+ case "user":
785
+ return { ...base, source: "user" };
786
+ case "system":
787
+ return { ...base, source: "system" };
788
+ }
789
+ }
790
+ function toObservation(observation) {
791
+ if (!observation) return void 0;
792
+ return {
793
+ results: observation.results.map((result) => ({
794
+ source_call_id: result.source_call_id,
795
+ content: result.content === void 0 ? void 0 : toMessage(result.content),
796
+ subagent_trajectory_ref: result.subagent_trajectory_ref,
797
+ extra: result.extra
798
+ }))
799
+ };
800
+ }
801
+ function toMessage(message) {
802
+ if (typeof message === "string") return message;
803
+ return message.map((part) => {
804
+ if (part.type === "text") return { type: "text", text: part.text };
805
+ const source = imageSource(part.source.media_type, part.source.path);
806
+ return source ? { type: "image", source } : {
807
+ type: "text",
808
+ text: `[image ${part.source.media_type}: ${part.source.path}]`
809
+ };
810
+ });
811
+ }
812
+ function imageSource(mediaType, path) {
813
+ switch (mediaType) {
814
+ case "image/jpeg":
815
+ case "image/png":
816
+ case "image/gif":
817
+ case "image/webp":
818
+ return { media_type: mediaType, path };
819
+ default:
820
+ return void 0;
821
+ }
822
+ }
823
+ function isRecord3(value) {
824
+ return typeof value === "object" && value !== null && !Array.isArray(value);
825
+ }
826
+
827
+ // packages/trajectory/src/codex/store.ts
828
+ import {
829
+ CODEX_ROLLOUT_DIRS,
830
+ parseRolloutFileName as parseRolloutFileName2,
831
+ parseSessionMetaLine
832
+ } from "@alwaysmeticulous/agent-traces";
833
+ import { createReadStream } from "node:fs";
834
+ import { readdir as readdir3, stat as stat2 } from "node:fs/promises";
835
+ import { basename as basename3, join as join4 } from "node:path";
836
+ import { createInterface } from "node:readline";
837
+ import { createZstdDecompress } from "node:zlib";
838
+
839
+ // packages/trajectory/src/codex/thread.ts
840
+ var CodexThread = class {
841
+ threadId;
842
+ /** The thread's rollout files, the original first, then any a revert wrote. */
843
+ rolloutPaths;
844
+ /** Every thread under this one (subagents of subagents too), flat. */
845
+ subagents;
846
+ constructor(threadId, rolloutPaths, subagents = []) {
847
+ this.threadId = threadId;
848
+ this.rolloutPaths = rolloutPaths;
849
+ this.subagents = subagents;
850
+ }
851
+ };
852
+
853
+ // packages/trajectory/src/codex/store.ts
854
+ var CodexStore = class {
855
+ root;
856
+ constructor(options) {
857
+ this.root = options.root;
858
+ }
859
+ /**
860
+ * Each root thread with a rollout changed at or after `since`, newest first.
861
+ * A rollout is `.jsonl` or `.jsonl.zst`. It reads each rollout's first line
862
+ * (`session_meta`) to group a subagent thread under its parent, as
863
+ * meticulous does: the parent is the meta's `session_id` when it differs
864
+ * from the thread id, else its `parent_thread_id`, followed while the parent
865
+ * is among the files, so an orphan is its own root.
866
+ */
867
+ async *threads(options) {
868
+ const since = options.since.getTime();
869
+ const threads = /* @__PURE__ */ new Map();
870
+ for (const folder of CODEX_ROLLOUT_DIRS) {
871
+ for (const path of await rolloutFiles(join4(this.root, folder))) {
872
+ const changed = (await stat2(path)).mtimeMs;
873
+ if (changed < since) continue;
874
+ const named = parseRolloutFileName2(
875
+ basename3(path).replace(/\.zst$/, "")
876
+ );
877
+ const meta = parseSessionMetaLine(await firstLine(path));
878
+ const threadId = meta?.threadId ?? named?.threadId ?? basename3(path);
879
+ const thread = threads.get(threadId) ?? {
880
+ threadId,
881
+ parentId: null,
882
+ rollouts: []
883
+ };
884
+ thread.rollouts.push({
885
+ path,
886
+ rolloutId: named?.rolloutId ?? threadId,
887
+ timestamp: named?.timestamp ?? "",
888
+ changed
889
+ });
890
+ thread.parentId ??= meta?.sessionId && meta.sessionId !== threadId ? meta.sessionId : meta?.parentThreadId ?? null;
891
+ threads.set(threadId, thread);
892
+ }
893
+ }
894
+ const groups = /* @__PURE__ */ new Map();
895
+ for (const thread of threads.values()) {
896
+ const rootId = rootOf(thread.threadId, threads);
897
+ groups.set(rootId, [...groups.get(rootId) ?? [], thread]);
898
+ }
899
+ const roots = [...groups].map(([rootId, members]) => ({
900
+ rootId,
901
+ members,
902
+ changed: Math.max(
903
+ ...members.flatMap((member) => member.rollouts.map((r) => r.changed))
904
+ )
905
+ }));
906
+ for (const { rootId, members } of roots.toSorted(
907
+ (a, b) => b.changed - a.changed
908
+ )) {
909
+ const root = members.find((member) => member.threadId === rootId);
910
+ if (!root) continue;
911
+ yield new CodexThread(
912
+ rootId,
913
+ ordered(root),
914
+ members.filter((member) => member !== root).map((member) => ({
915
+ threadId: member.threadId,
916
+ rolloutPaths: ordered(member)
917
+ }))
918
+ );
919
+ }
920
+ }
921
+ };
922
+ function ordered(thread) {
923
+ return thread.rollouts.toSorted(
924
+ (a, b) => a.timestamp.localeCompare(b.timestamp) || Number(a.rolloutId !== thread.threadId) - Number(b.rolloutId !== thread.threadId) || a.rolloutId.localeCompare(b.rolloutId)
925
+ ).map((rollout) => rollout.path);
926
+ }
927
+ function rootOf(threadId, threads) {
928
+ const seen = /* @__PURE__ */ new Set([threadId]);
929
+ let current = threadId;
930
+ for (; ; ) {
931
+ const parentId = threads.get(current)?.parentId;
932
+ if (!parentId || !threads.has(parentId) || seen.has(parentId))
933
+ return current;
934
+ seen.add(parentId);
935
+ current = parentId;
936
+ }
937
+ }
938
+ async function rolloutFiles(folder) {
939
+ let names;
940
+ try {
941
+ names = await readdir3(folder, { recursive: true });
942
+ } catch (error) {
943
+ if (isRecord4(error) && error.code === "ENOENT") return [];
944
+ throw error;
945
+ }
946
+ return names.filter((name) => /^rollout-.+\.jsonl(\.zst)?$/.test(basename3(name))).map((name) => join4(folder, name));
947
+ }
948
+ async function firstLine(path) {
949
+ const file = createReadStream(path);
950
+ const input = path.endsWith(".zst") ? file.pipe(createZstdDecompress()) : file;
951
+ const lines = createInterface({ input, crlfDelay: Infinity });
952
+ try {
953
+ for await (const line of lines) return line;
954
+ return null;
955
+ } catch {
956
+ return null;
957
+ } finally {
958
+ lines.close();
959
+ file.destroy();
960
+ input.destroy();
961
+ }
962
+ }
963
+ function isRecord4(value) {
964
+ return typeof value === "object" && value !== null && !Array.isArray(value);
965
+ }
966
+ export {
967
+ ATIF_SCHEMA_VERSION,
968
+ ClaudeCodeAdapter,
969
+ ClaudeCodeSession,
970
+ ClaudeCodeStore,
971
+ ClaudeCodeSubagent,
972
+ CodexAdapter,
973
+ CodexStore,
974
+ CodexThread,
975
+ SessionReadError
976
+ };
977
+ //# sourceMappingURL=index.js.map