@deepagents/trajectory 0.0.0-stage → 7.53.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/README.md CHANGED
@@ -1,3 +1,247 @@
1
- # Temporary Holding Version
1
+ # @deepagents/trajectory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Status:** the Claude Code adapter ships first. `ClaudeCodeStore` and the
4
+ > Codex store and adapter follow (#6107). Each decision is in
5
+ > [docs/adr](./docs/adr).
6
+
7
+ Read a coding agent's stored sessions (Claude Code transcripts, Codex rollouts)
8
+ as [ATIF](https://github.com/harbor-framework/harbor/blob/main/rfcs/0001-trajectory-format.md)
9
+ v1.8 trajectories: one ordered list of user, agent and system steps per session,
10
+ with tool calls, their results, metrics and the subagents nested inside.
11
+
12
+ Each agent is an `Adapter`. This package ships one for Claude Code and one for
13
+ Codex. An agent it does not cover gets an adapter of your own that returns the
14
+ same `Trajectory`, so every consumer reads every agent the same way.
15
+
16
+ The package only reads. It owns no store, index or schedule, and it has no
17
+ policy. Rules such as "the housekeeping is due" belong to the host; this package
18
+ gives the host the steps to decide from.
19
+
20
+ ## Read the transcript a hook was given
21
+
22
+ ```ts
23
+ import {
24
+ ClaudeCodeAdapter,
25
+ ClaudeCodeSession,
26
+ ClaudeCodeSubagent,
27
+ } from '@deepagents/trajectory';
28
+
29
+ // SubagentStop reads the subagent's own transcript, never the parent's.
30
+ const session = input.agent_transcript_path
31
+ ? ClaudeCodeSubagent.fromTranscriptPath(input.agent_transcript_path)
32
+ : ClaudeCodeSession.fromTranscriptPath(input.transcript_path);
33
+ const { trajectory } = await new ClaudeCodeAdapter().read(session, {
34
+ subagents: false,
35
+ });
36
+
37
+ const written = trajectory.steps
38
+ .flatMap((step) => (step.source === 'agent' ? (step.tool_calls ?? []) : []))
39
+ .filter((call) =>
40
+ ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'].includes(call.function_name),
41
+ )
42
+ .map((call) => call.arguments.file_path ?? call.arguments.notebook_path);
43
+ ```
44
+
45
+ ## Find what the user typed
46
+
47
+ ```ts
48
+ const typed = trajectory.steps.filter(
49
+ (step) =>
50
+ step.source === 'user' && step.extra?.claude_code?.origin === 'human',
51
+ );
52
+ ```
53
+
54
+ A prompt typed while the agent works (a `queued_command` attachment) is a user
55
+ step too. Task notifications, peer messages and hand-backs are user steps with
56
+ their own `origin`. Skill bodies, command expansions and other `isMeta` entries
57
+ are system steps. See [ADR 0004](./docs/adr/0004-every-claude-code-entry-becomes-a-step-or-a-counted-diagnostic.md).
58
+
59
+ ## Read a whole session after a /clear
60
+
61
+ ```ts
62
+ const store = new ClaudeCodeStore({ root: join(homedir(), '.claude') });
63
+ const session = await store.session(process.env.CLAUDE_CODE_SESSION_ID);
64
+ const { sessions, missing } = await store.chain(session); // oldest first, linked by derived-from entries
65
+ ```
66
+
67
+ `missing` names each id the chain points to whose transcript is no longer in the
68
+ store. Each segment reads as its own trajectory. All segments share one `session_id`
69
+ (the first id of the chain), and each one names the next in
70
+ `continued_trajectory_ref`. See [ADR 0007](./docs/adr/0007-a-clear-chain-is-separate-trajectories-that-share-session-id-and-link-by-continued-trajectory-ref.md).
71
+
72
+ ## Mine every session since a date
73
+
74
+ ```ts
75
+ const store = new ClaudeCodeStore({ root: join(homedir(), '.claude') });
76
+ const adapter = new ClaudeCodeAdapter();
77
+ for await (const session of store.sessions({ since: new Date('2026-11-20') })) {
78
+ const { trajectory, diagnostics } = await adapter.read(session);
79
+ // …
80
+ }
81
+ ```
82
+
83
+ ## Read Codex history
84
+
85
+ ```ts
86
+ const store = new CodexStore({ root: join(homedir(), '.codex') });
87
+ const adapter = new CodexAdapter();
88
+ for await (const thread of store.threads({ since })) {
89
+ const { trajectory } = await adapter.read(thread); // .jsonl and .jsonl.zst
90
+ }
91
+ ```
92
+
93
+ ## Write your own adapter
94
+
95
+ ```ts
96
+ import type { Adapter, ReadResult } from '@deepagents/trajectory';
97
+
98
+ class GooseAdapter implements Adapter<GooseSession> {
99
+ readonly agent = 'goose';
100
+ async read(session: GooseSession): Promise<ReadResult> {
101
+ // Read the store, then return { trajectory, diagnostics } in ATIF v1.8.
102
+ }
103
+ }
104
+ ```
105
+
106
+ ## Signatures
107
+
108
+ ```ts
109
+ // The port.
110
+ export interface Adapter<Session> {
111
+ readonly agent: string; // ATIF agent.name: 'claude-code', 'codex', …
112
+ read(session: Session, options?: ReadOptions): Promise<ReadResult>;
113
+ }
114
+ export interface ReadOptions { subagents?: boolean } // default true
115
+ export interface ReadResult { trajectory: Trajectory; diagnostics: Diagnostic[] }
116
+ export interface Diagnostic { code: DiagnosticCode; path: string; line?: number; count?: number; entryType?: string; message: string }
117
+ export type DiagnosticCode =
118
+ | 'invalid_json_line' // a line that does not parse
119
+ | 'partial_last_line' // the agent is still writing it
120
+ | 'unmapped_entry' // bookkeeping that has no step (counted by type)
121
+ | 'sidechain_entry' // an isSidechain row inside a main transcript
122
+ | 'orphan_tool_result' // a result whose call is not in the transcript
123
+ | 'unlinked_subagent' // a subagent whose spawning call is not found
124
+ | 'unreadable_subagent'; // a subagent transcript that cannot be read
125
+
126
+ // Claude Code.
127
+ export class ClaudeCodeStore {
128
+ constructor(options: { root: string }); // the folder that holds projects/
129
+ sessions(options: { since: Date }): AsyncIterable<ClaudeCodeSession>;
130
+ session(sessionId: string): Promise<ClaudeCodeSession | undefined>;
131
+ chain(session: ClaudeCodeSession): Promise<ClaudeCodeChain>;
132
+ }
133
+ export interface ClaudeCodeChain {
134
+ readonly sessions: readonly ClaudeCodeSession[]; // oldest first
135
+ readonly missing: readonly string[]; // ids the chain names whose transcript is gone
136
+ }
137
+ export class ClaudeCodeSession {
138
+ static fromTranscriptPath(path: string): ClaudeCodeSession; // a main transcript; touches no disk
139
+ readonly sessionId: string;
140
+ readonly transcriptPath: string;
141
+ readonly runId: string; // the chain's first id; its own id when read alone
142
+ readonly continuedBy: string | undefined; // the next segment's transcript, from chain()
143
+ }
144
+ export class ClaudeCodeSubagent {
145
+ static fromTranscriptPath(path: string): ClaudeCodeSubagent; // <session>/subagents/agent-<id>.jsonl
146
+ readonly agentId: string;
147
+ readonly sessionId: string; // the session that started it
148
+ readonly transcriptPath: string;
149
+ }
150
+ export class ClaudeCodeAdapter implements Adapter<ClaudeCodeSession | ClaudeCodeSubagent> { readonly agent = 'claude-code' }
151
+
152
+ // Codex.
153
+ export class CodexStore {
154
+ constructor(options: { root: string }); // the folder that holds sessions/ and archived_sessions/
155
+ threads(options: { since: Date }): AsyncIterable<CodexThread>;
156
+ }
157
+ export class CodexThread { readonly threadId: string; readonly rolloutPaths: readonly string[] }
158
+ export class CodexAdapter implements Adapter<CodexThread> { readonly agent = 'codex' }
159
+
160
+ // ATIF v1.8, ported from Harbor's models (docs/ported-from-harbor-atif.md).
161
+ export const ATIF_SCHEMA_VERSION = 'ATIF-v1.8';
162
+ export type Trajectory, Step, UserStep, AgentStep, SystemStep, ToolCall, Observation,
163
+ ObservationResult, Metrics, FinalMetrics, Agent, ContentPart, SubagentTrajectoryRef;
164
+
165
+ // Errors.
166
+ export class SessionReadError extends Error { readonly path: string } // missing or unreadable; cause attached
167
+ ```
168
+
169
+ ## What each call does underneath
170
+
171
+ | Call | Underneath |
172
+ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
173
+ | `ClaudeCodeSession.fromTranscriptPath(p)` | Takes the id from the file name; touches no disk. |
174
+ | `ClaudeCodeStore.sessions({ since })` | Walks `projects/*/*.jsonl` and yields each main transcript changed since `since`, newest first. Subagent files are not sessions. |
175
+ | `ClaudeCodeStore.session(id)` | Looks for `projects/*/<id>.jsonl`. |
176
+ | `ClaudeCodeStore.chain(s)` | Reads each transcript's `derived-from` entry back to the first segment. It follows every `claude_code_session` it names (any `via`), skips ids already in the chain, looks beside the current transcript first, then in every project. |
177
+ | `ClaudeCodeAdapter.read(s)` | Streams the transcript line by line. It maps every entry by the [mapping table](#claude-code-entry--atif), pairs each `tool_use` with its `tool_result` by id, and reads `<id>/subagents/agent-*.jsonl` plus `.meta.json` into `subagent_trajectories`. |
178
+ | `CodexStore.threads({ since })` | Walks `sessions/` and `archived_sessions/` (`.jsonl`, `.jsonl.zst`) and groups rollouts by the parent ids in each `session_meta`. |
179
+ | `CodexAdapter.read(t)` | Decodes `.zst` with `node:zlib` `zstdDecompressSync`, then calls meticulous's `convertCodexSession`, and writes `schema_version: ATIF-v1.8`. |
180
+
181
+ Speed, measured on this Mac on 2026-11-27 (a measurement, not a test: the
182
+ repo's `no-wall-clock-bound` rule forbids timing bounds in tests):
183
+
184
+ - meticulous converts 3 MB plus 6 subagents in 34 ms;
185
+ - a whole-file read of 24 h of transcripts (835 files, 311k entries) takes 3.7 s warm.
186
+
187
+ ## Claude Code entry → ATIF
188
+
189
+ | Entry | Becomes |
190
+ | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
191
+ | `user` with an `origin` (typed prompts, peer messages, task notifications; `isMeta` or not) | `UserStep`; `extra.claude_code.origin` = `origin.kind` (`human`, `peer`, `task-notification`, …) |
192
+ | `user`, `isMeta`, no `origin` (skill bodies, command expansions) | `SystemStep`, `extra.claude_code.is_meta: true` |
193
+ | `user`, text content, no `origin`, not `isMeta` (Claude Code builds before `origin`) | `UserStep` with no `extra.claude_code.origin`: its author is unknown, so it never counts as typed |
194
+ | `user` with `tool_result` blocks | `ObservationResult` on the agent step that made the call; `toolUseResult` goes in `result.extra.claude_code.tool_use_result` |
195
+ | `assistant` (entries with one `message.id` merge into one step) | `AgentStep`: text → `message`, `thinking` → `reasoning_content`, `tool_use` → `tool_calls`, `usage` → `metrics` |
196
+ | `attachment` `queued_command` | `UserStep` with that attachment's `origin` (a prompt typed mid-turn, or a peer message) |
197
+ | any other `attachment` (`hook_additional_context`, `hook_success`, …) | `SystemStep`, the attachment in `extra.claude_code.attachment` |
198
+ | `system` (`stop_hook_summary`, `turn_duration`, `compact_boundary`, …) | `SystemStep`, the entry in `extra.claude_code.system` |
199
+ | `derived-from` | `Trajectory.extra.claude_code.derived_from`; `chain()` follows it |
200
+ | `ai-title`, `custom-title`, `summary`, `pr-link` | `Trajectory.extra.claude_code` |
201
+ | `isSidechain` row in a main transcript | skipped, counted as `sidechain_entry` |
202
+ | bookkeeping (`api-request`, `data-flow-records`, `permission-mode`, `queue-operation`, `file-history-snapshot`, …) | skipped, counted by type as `unmapped_entry` |
203
+
204
+ Every step keeps `extra.claude_code` with `uuid`, `parent_uuid`, `timestamp`,
205
+ `cwd`, `entrypoint` and `prompt_id`, so a consumer can join back to the raw line.
206
+
207
+ ## Errors
208
+
209
+ - `SessionReadError`: the transcript or rollout is missing or cannot be read or
210
+ decoded. It has one class because the caller's next step is the same either
211
+ way: a hook does not fire, and a miner logs and skips.
212
+ - A bad line never throws; it becomes a `Diagnostic`. The last line is often
213
+ half-written while the agent runs.
214
+
215
+ ## The same concepts in other systems
216
+
217
+ | System | Their word | Ours |
218
+ | -------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
219
+ | Harbor ATIF v1.8 | `Trajectory`, `Step`, `subagent_trajectories`, `continued_trajectory_ref` | same (the port) |
220
+ | Google ADK (Go) | `session.Session` holds `Event`s | `ClaudeCodeSession` is the stored session; the trajectory is what is read back |
221
+ | Microsoft Agent Framework (.NET) | `AgentSession` + `ChatHistoryProvider` | the same split |
222
+ | Claude Agent SDK | `listSessions`, `getSessionMessages`, `listSubagents` | `ClaudeCodeStore.sessions`, `ClaudeCodeAdapter.read` |
223
+ | Codex app-server | thread → turn → item; rollout files | `CodexThread` → `Trajectory` |
224
+ | `@letta-ai/trajectory` | `listTrajectories`, `normalizeTranscript` | `Store.sessions`, `Adapter.read` |
225
+ | franken-agent-detection (Rust) | `Connector` trait, `NormalizedConversation` | `Adapter`, `Trajectory` |
226
+
227
+ ## Why not an npm package
228
+
229
+ | Package | Why it fails |
230
+ | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
231
+ | `@alwaysmeticulous/agent-traces` 3.2.0 | Used here for Codex only. Its Claude converter reads only `user` and `assistant` lines: it drops `queued_command` prompts, system rows, attachments, `toolUseResult` and `/clear` chains, with no extension points. Its output is ATIF v1.7. |
232
+ | `@letta-ai/trajectory` 0.4.4 | Closed set of sources, a closed schema with no extra slot, and its own format rather than ATIF. |
233
+ | `atifact` 0.16.0 | Reads `claude -p` stream-json only, not stored sessions. |
234
+ | `@kontourai/thread` 0.7.0 | Its own format, and young. |
235
+ | `@anthropic-ai/claude-agent-sdk` | Claude only; one reader per agent was rejected. Its messages drop attachments and system rows; its raw store API is alpha. |
236
+ | franken-agent-detection (crate) | Rust only, and it also drops attachments, system rows and `toolUseResult`. |
237
+
238
+ ## Who uses what
239
+
240
+ | Consumer | Uses |
241
+ | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
242
+ | agent-plugin `hooks/compile-guard` | `fromTranscriptPath`, `read({ subagents: false })`, agent `tool_calls` |
243
+ | agent-plugin `hooks/ezzs-way-of-coding` stop and verification rules | `read`, user steps by origin, system steps (`stop_hook_summary`), last agent message, subagent transcript |
244
+ | deepagents `experimental/coding-agent-reminders` | `read`, user steps by origin, `hook_additional_context` system steps |
245
+ | agent-plugin housekeeping `close-check` / `records-check` | `ClaudeCodeStore.chain`, tool calls with results and `tool_use_result` |
246
+ | agent-plugin update-docs evidence | `sessions({ since })`, typed prompts, agent text and tool calls, `cwd` |
247
+ | later: context-compiler sessions connector (#2400), rollover resume (#6075), night-run miners | `sessions({ since })`, `read` |
@@ -0,0 +1,47 @@
1
+ import type { Trajectory } from './atif.ts';
2
+ /**
3
+ * The port: turns one located session of one agent into one ATIF trajectory
4
+ * (ADR 0006). Each agent has its own `Session` type, so an adapter cannot be
5
+ * handed another agent's session.
6
+ */
7
+ export interface Adapter<Session> {
8
+ /** ATIF `agent.name`: `claude-code`, `codex`, … */
9
+ readonly agent: string;
10
+ read(session: Session, options?: ReadOptions): Promise<ReadResult>;
11
+ }
12
+ export interface ReadOptions {
13
+ /** Read the session's subagents into `subagent_trajectories`. Default true. */
14
+ subagents?: boolean;
15
+ }
16
+ export interface ReadResult {
17
+ trajectory: Trajectory;
18
+ diagnostics: Diagnostic[];
19
+ }
20
+ export type DiagnosticCode =
21
+ /** A line that does not parse as a JSON object. */
22
+ 'invalid_json_line'
23
+ /** The last line, still being written by the agent. */
24
+ | 'partial_last_line'
25
+ /** Bookkeeping with no step, counted by entry type. */
26
+ | 'unmapped_entry'
27
+ /** An `isSidechain` row inside a main transcript. */
28
+ | 'sidechain_entry'
29
+ /** A tool result whose call is not in the transcript. */
30
+ | 'orphan_tool_result'
31
+ /** A subagent whose spawning call could not be found. */
32
+ | 'unlinked_subagent'
33
+ /** A subagent transcript that could not be read. */
34
+ | 'unreadable_subagent';
35
+ export interface Diagnostic {
36
+ code: DiagnosticCode;
37
+ /** The file the diagnostic is about. */
38
+ path: string;
39
+ /** 1-based line, for a diagnostic about one line. */
40
+ line?: number;
41
+ /** How many entries it covers, for a counted diagnostic. */
42
+ count?: number;
43
+ /** The entry type an `unmapped_entry` diagnostic counts. */
44
+ entryType?: string;
45
+ message: string;
46
+ }
47
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE5C;;;;GAIG;AACH,MAAM,WAAW,OAAO,CAAC,OAAO;IAC9B,mDAAmD;IACnD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CACpE;AAED,MAAM,WAAW,WAAW;IAC1B,+EAA+E;IAC/E,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IACzB,UAAU,EAAE,UAAU,CAAC;IACvB,WAAW,EAAE,UAAU,EAAE,CAAC;CAC3B;AAED,MAAM,MAAM,cAAc;AACxB,mDAAmD;AACjD,mBAAmB;AACrB,uDAAuD;GACrD,mBAAmB;AACrB,uDAAuD;GACrD,gBAAgB;AAClB,qDAAqD;GACnD,iBAAiB;AACnB,yDAAyD;GACvD,oBAAoB;AACtB,yDAAyD;GACvD,mBAAmB;AACrB,oDAAoD;GAClD,qBAAqB,CAAC;AAE1B,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,cAAc,CAAC;IACrB,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,qDAAqD;IACrD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,4DAA4D;IAC5D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CACjB"}
package/dist/atif.d.ts ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * ATIF v1.8, the Agent Trajectory Interchange Format, ported from Harbor's
3
+ * Pydantic models (harbor-framework/harbor src/harbor/models/trajectories,
4
+ * RFC 0001). Names, fields and optionality follow Harbor exactly; the two
5
+ * divergences are unions that turn Harbor's runtime validators into types
6
+ * (docs/ported-from-harbor-atif.md, ADR 0002).
7
+ */
8
+ export declare const ATIF_SCHEMA_VERSION = "ATIF-v1.8";
9
+ export type SchemaVersion = 'ATIF-v1.0' | 'ATIF-v1.1' | 'ATIF-v1.2' | 'ATIF-v1.3' | 'ATIF-v1.4' | 'ATIF-v1.5' | 'ATIF-v1.6' | 'ATIF-v1.7' | 'ATIF-v1.8';
10
+ export type Extra = Record<string, unknown>;
11
+ export interface ImageSource {
12
+ media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
13
+ path: string;
14
+ }
15
+ export interface AudioSource {
16
+ media_type: 'audio/wav' | 'audio/mpeg' | 'audio/mp4' | 'audio/aac' | 'audio/ogg' | 'audio/flac' | 'audio/webm' | 'audio/aiff';
17
+ path: string;
18
+ duration_sec?: number | null;
19
+ }
20
+ /** Harbor's `ContentPart`, whose `validate_content_type` becomes this union. */
21
+ export type ContentPart = {
22
+ type: 'text';
23
+ text: string;
24
+ } | {
25
+ type: 'image';
26
+ source: ImageSource;
27
+ } | {
28
+ type: 'audio';
29
+ source: AudioSource;
30
+ };
31
+ export interface ToolCall {
32
+ tool_call_id: string;
33
+ function_name: string;
34
+ arguments: Record<string, unknown>;
35
+ extra?: Extra | null;
36
+ }
37
+ export interface SubagentTrajectoryRef {
38
+ trajectory_id?: string | null;
39
+ session_id?: string | null;
40
+ trajectory_path?: string | null;
41
+ extra?: Extra | null;
42
+ }
43
+ export interface ObservationResult {
44
+ /** A `tool_call_id` of the same step's `tool_calls` (Harbor's `validate_tool_call_references`). */
45
+ source_call_id?: string | null;
46
+ content?: string | ContentPart[] | null;
47
+ subagent_trajectory_ref?: SubagentTrajectoryRef[] | null;
48
+ extra?: Extra | null;
49
+ }
50
+ export interface Observation {
51
+ results: ObservationResult[];
52
+ }
53
+ export interface Metrics {
54
+ prompt_tokens?: number | null;
55
+ completion_tokens?: number | null;
56
+ cached_tokens?: number | null;
57
+ cost_usd?: number | null;
58
+ prompt_token_ids?: number[] | null;
59
+ completion_token_ids?: number[] | null;
60
+ logprobs?: number[] | null;
61
+ extra?: Extra | null;
62
+ }
63
+ export interface FinalMetrics {
64
+ total_prompt_tokens?: number | null;
65
+ total_completion_tokens?: number | null;
66
+ total_cached_tokens?: number | null;
67
+ total_cost_usd?: number | null;
68
+ total_steps?: number | null;
69
+ extra?: Extra | null;
70
+ }
71
+ export interface Agent {
72
+ name: string;
73
+ version: string;
74
+ model_name?: string | null;
75
+ tool_definitions?: Record<string, unknown>[] | null;
76
+ extra?: Extra | null;
77
+ }
78
+ interface StepBase {
79
+ /** Sequential from 1 within one trajectory (Harbor's `validate_step_ids`). */
80
+ step_id: number;
81
+ /** ISO 8601. */
82
+ timestamp?: string | null;
83
+ message: string | ContentPart[];
84
+ observation?: Observation | null;
85
+ is_copied_context?: boolean | null;
86
+ /** 0 on an agent step marks a deterministic dispatch with no model call. */
87
+ llm_call_count?: number | null;
88
+ extra?: Extra | null;
89
+ }
90
+ export interface UserStep extends StepBase {
91
+ source: 'user';
92
+ }
93
+ export interface SystemStep extends StepBase {
94
+ source: 'system';
95
+ }
96
+ /** The only step that may carry a model, reasoning, tool calls and metrics (Harbor's `validate_agent_only_fields`). */
97
+ export interface AgentStep extends StepBase {
98
+ source: 'agent';
99
+ model_name?: string | null;
100
+ reasoning_effort?: string | number | null;
101
+ reasoning_content?: string | null;
102
+ tool_calls?: ToolCall[] | null;
103
+ metrics?: Metrics | null;
104
+ }
105
+ export type Step = UserStep | AgentStep | SystemStep;
106
+ export interface Trajectory {
107
+ schema_version: SchemaVersion;
108
+ /** Run-scoped: segments of one run (a /clear chain, embedded subagents) may share it. */
109
+ session_id?: string | null;
110
+ /** Unique per document; required on every embedded subagent trajectory. */
111
+ trajectory_id?: string | null;
112
+ agent: Agent;
113
+ /** At least one step. */
114
+ steps: [Step, ...Step[]];
115
+ notes?: string | null;
116
+ final_metrics?: FinalMetrics | null;
117
+ continued_trajectory_ref?: string | null;
118
+ extra?: Extra | null;
119
+ subagent_trajectories?: Trajectory[] | null;
120
+ }
121
+ export {};
122
+ //# sourceMappingURL=atif.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"atif.d.ts","sources":["../src/atif.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,eAAO,MAAM,mBAAmB,cAAc,CAAC;AAE/C,MAAM,MAAM,aAAa,GACrB,WAAW,GACX,WAAW,GACX,WAAW,GACX,WAAW,GACX,WAAW,GACX,WAAW,GACX,WAAW,GACX,WAAW,GACX,WAAW,CAAC;AAEhB,MAAM,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE5C,MAAM,WAAW,WAAW;IA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IACtB,aAAa,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;IACpC,wBAAwB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzC,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;IACrB,qBAAqB,CAAC,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;CAC7C"}
@@ -0,0 +1,9 @@
1
+ import type { Adapter, ReadOptions, ReadResult } from '../adapter.ts';
2
+ import { ClaudeCodeSession, ClaudeCodeSubagent } from './session.ts';
3
+ /** Reads a Claude Code transcript into an ATIF v1.8 trajectory, as ADR 0004 maps each entry. */
4
+ export declare class ClaudeCodeAdapter implements Adapter<ClaudeCodeSession | ClaudeCodeSubagent> {
5
+ #private;
6
+ readonly agent = "claude-code";
7
+ read(session: ClaudeCodeSession | ClaudeCodeSubagent, options?: ReadOptions): Promise<ReadResult>;
8
+ }
9
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sources":["../../src/claude-code/adapter.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,OAAO,EAEP,WAAW,EACX,UAAU,EACX,MAAM,eAAe,CAAC;AAYvB,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAIrE,gGAAgG;AAChG,qBAAa,iBAAkB,YAAW,OAAO,CAC/C,iBAAiB,GAAG,kBAAkB,CACvC;;IACC,QAAQ,CAAC,KAAK,iBAAiB;IAEzB,IAAI,CACR,OAAO,EAAE,iBAAiB,GAAG,kBAAkB,EAC/C,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,UAAU,CAAC,CAiHrB;CAoFF"}
@@ -0,0 +1,40 @@
1
+ /** Only the store places a session in a chain; the package index does not export this key. */
2
+ export declare const placeInChain: unique symbol;
3
+ /**
4
+ * One Claude Code session: `<root>/projects/<project>/<session-id>.jsonl` and
5
+ * its `<session-id>/subagents/` folder. Building one touches no disk.
6
+ */
7
+ export declare class ClaudeCodeSession {
8
+ readonly sessionId: string;
9
+ readonly transcriptPath: string;
10
+ /** The run this segment belongs to: the first session id of its /clear chain (ADR 0007). */
11
+ readonly runId: string;
12
+ /** The next segment's transcript, when the chain continues after this one. */
13
+ readonly continuedBy: string | undefined;
14
+ private constructor();
15
+ /** The session of a main transcript path, such as a hook's `transcript_path`. */
16
+ static fromTranscriptPath(path: string): ClaudeCodeSession;
17
+ /** The chain gives each segment its run and its successor. */
18
+ static [placeInChain](session: ClaudeCodeSession, runId: string, continuedBy: string | undefined): ClaudeCodeSession;
19
+ /** The folder that holds this session's subagent transcripts. */
20
+ get subagentsPath(): string;
21
+ }
22
+ /**
23
+ * One subagent's transcript: `<session-id>/subagents/agent-<agent-id>.jsonl`,
24
+ * with its `.meta.json` beside it. A SubagentStop hook reads it from
25
+ * `agent_transcript_path`. Building one touches no disk.
26
+ */
27
+ export declare class ClaudeCodeSubagent {
28
+ readonly agentId: string;
29
+ /** The session that started this subagent. */
30
+ readonly sessionId: string;
31
+ readonly transcriptPath: string;
32
+ private constructor();
33
+ /** The subagent of a subagent transcript path, such as a hook's `agent_transcript_path`. */
34
+ static fromTranscriptPath(path: string): ClaudeCodeSubagent;
35
+ /** The `.meta.json` file beside the transcript, which names the call that spawned it. */
36
+ get metaPath(): string;
37
+ /** ATIF's per-document id of this subagent's trajectory. */
38
+ get trajectoryId(): string;
39
+ }
40
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sources":["../../src/claude-code/session.ts"],"names":[],"mappings":"AAIA,8FAA8F;AAC9F,eAAO,MAAM,YAAY,eAAyB,CAAC;AAEnD;;;GAGG;AACH,qBAAa,iBAAiB;IAC5B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,4FAA4F;IAC5F,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,8EAA8E;IAC9E,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAEzC,OAAO,eAUN;IAED,iFAAiF;IACjF,MAAM,CAAC,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,CASzD;IAED,8DAA8D;IAC9D,MAAM,CAAC,CAAC,YAAY,CAAC,CACnB,OAAO,EAAE,iBAAiB,EAC1B,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,MAAM,GAAG,SAAS,GAC9B,iBAAiB,CAOnB;IAED,iEAAiE;IACjE,IAAI,aAAa,IAAI,MAAM,CAE1B;CACF;AAED;;;;GAIG;AACH,qBAAa,kBAAkB;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,8CAA8C;IAC9C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAEhC,OAAO,eAQN;IAED,4FAA4F;IAC5F,MAAM,CAAC,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,CAS1D;IAED,yFAAyF;IACzF,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED,4DAA4D;IAC5D,IAAI,YAAY,IAAI,MAAM,CAEzB;CACF"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The one class a read throws: the session's file is missing, cannot be read
3
+ * or decoded, or holds no step. The caller's next step is the same for each
4
+ * (a hook does not fire, a miner logs and skips), so they share a class and
5
+ * differ only in `cause` (ADR 0009).
6
+ */
7
+ export declare class SessionReadError extends Error {
8
+ readonly name = "SessionReadError";
9
+ readonly path: string;
10
+ constructor(path: string, message: string, options?: {
11
+ cause?: unknown;
12
+ });
13
+ }
14
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,SAAkB,IAAI,sBAAsB;IAC5C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,YAAY,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAGvE;CACF"}
@@ -0,0 +1,6 @@
1
+ export type { Adapter, Diagnostic, DiagnosticCode, ReadOptions, ReadResult, } from './adapter.ts';
2
+ export { ATIF_SCHEMA_VERSION, type Agent, type AgentStep, type AudioSource, type ContentPart, type Extra, type FinalMetrics, type ImageSource, type Metrics, type Observation, type ObservationResult, type SchemaVersion, type Step, type SubagentTrajectoryRef, type SystemStep, type ToolCall, type Trajectory, type UserStep, } from './atif.ts';
3
+ export { ClaudeCodeAdapter } from './claude-code/adapter.ts';
4
+ export { ClaudeCodeSession, ClaudeCodeSubagent, } from './claude-code/session.ts';
5
+ export { SessionReadError } from './errors.ts';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,OAAO,EACP,UAAU,EACV,cAAc,EACd,WAAW,EACX,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,mBAAmB,EACnB,KAAK,KAAK,EACV,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,KAAK,EACV,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,OAAO,EACZ,KAAK,WAAW,EAChB,KAAK,iBAAiB,EACtB,KAAK,aAAa,EAClB,KAAK,IAAI,EACT,KAAK,qBAAqB,EAC1B,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,UAAU,EACf,KAAK,QAAQ,GACd,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EACL,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,545 @@
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
+ export {
539
+ ATIF_SCHEMA_VERSION,
540
+ ClaudeCodeAdapter,
541
+ ClaudeCodeSession,
542
+ ClaudeCodeSubagent,
543
+ SessionReadError
544
+ };
545
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/atif.ts", "../src/claude-code/adapter.ts", "../src/errors.ts", "../src/claude-code/session.ts"],
4
+ "sourcesContent": ["/**\n * ATIF v1.8, the Agent Trajectory Interchange Format, ported from Harbor's\n * Pydantic models (harbor-framework/harbor src/harbor/models/trajectories,\n * RFC 0001). Names, fields and optionality follow Harbor exactly; the two\n * divergences are unions that turn Harbor's runtime validators into types\n * (docs/ported-from-harbor-atif.md, ADR 0002).\n */\n\nexport const ATIF_SCHEMA_VERSION = 'ATIF-v1.8';\n\nexport type SchemaVersion =\n | 'ATIF-v1.0'\n | 'ATIF-v1.1'\n | 'ATIF-v1.2'\n | 'ATIF-v1.3'\n | 'ATIF-v1.4'\n | 'ATIF-v1.5'\n | 'ATIF-v1.6'\n | 'ATIF-v1.7'\n | 'ATIF-v1.8';\n\nexport type Extra = Record<string, unknown>;\n\nexport interface ImageSource {\n media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';\n path: string;\n}\n\nexport interface AudioSource {\n media_type:\n | 'audio/wav'\n | 'audio/mpeg'\n | 'audio/mp4'\n | 'audio/aac'\n | 'audio/ogg'\n | 'audio/flac'\n | 'audio/webm'\n | 'audio/aiff';\n path: string;\n duration_sec?: number | null;\n}\n\n/** Harbor's `ContentPart`, whose `validate_content_type` becomes this union. */\nexport type ContentPart =\n | { type: 'text'; text: string }\n | { type: 'image'; source: ImageSource }\n | { type: 'audio'; source: AudioSource };\n\nexport interface ToolCall {\n tool_call_id: string;\n function_name: string;\n arguments: Record<string, unknown>;\n extra?: Extra | null;\n}\n\nexport interface SubagentTrajectoryRef {\n trajectory_id?: string | null;\n session_id?: string | null;\n trajectory_path?: string | null;\n extra?: Extra | null;\n}\n\nexport interface ObservationResult {\n /** A `tool_call_id` of the same step's `tool_calls` (Harbor's `validate_tool_call_references`). */\n source_call_id?: string | null;\n content?: string | ContentPart[] | null;\n subagent_trajectory_ref?: SubagentTrajectoryRef[] | null;\n extra?: Extra | null;\n}\n\nexport interface Observation {\n results: ObservationResult[];\n}\n\nexport interface Metrics {\n prompt_tokens?: number | null;\n completion_tokens?: number | null;\n cached_tokens?: number | null;\n cost_usd?: number | null;\n prompt_token_ids?: number[] | null;\n completion_token_ids?: number[] | null;\n logprobs?: number[] | null;\n extra?: Extra | null;\n}\n\nexport interface FinalMetrics {\n total_prompt_tokens?: number | null;\n total_completion_tokens?: number | null;\n total_cached_tokens?: number | null;\n total_cost_usd?: number | null;\n total_steps?: number | null;\n extra?: Extra | null;\n}\n\nexport interface Agent {\n name: string;\n version: string;\n model_name?: string | null;\n tool_definitions?: Record<string, unknown>[] | null;\n extra?: Extra | null;\n}\n\ninterface StepBase {\n /** Sequential from 1 within one trajectory (Harbor's `validate_step_ids`). */\n step_id: number;\n /** ISO 8601. */\n timestamp?: string | null;\n message: string | ContentPart[];\n observation?: Observation | null;\n is_copied_context?: boolean | null;\n /** 0 on an agent step marks a deterministic dispatch with no model call. */\n llm_call_count?: number | null;\n extra?: Extra | null;\n}\n\nexport interface UserStep extends StepBase {\n source: 'user';\n}\n\nexport interface SystemStep extends StepBase {\n source: 'system';\n}\n\n/** The only step that may carry a model, reasoning, tool calls and metrics (Harbor's `validate_agent_only_fields`). */\nexport interface AgentStep extends StepBase {\n source: 'agent';\n model_name?: string | null;\n reasoning_effort?: string | number | null;\n reasoning_content?: string | null;\n tool_calls?: ToolCall[] | null;\n metrics?: Metrics | null;\n}\n\nexport type Step = UserStep | AgentStep | SystemStep;\n\nexport interface Trajectory {\n schema_version: SchemaVersion;\n /** Run-scoped: segments of one run (a /clear chain, embedded subagents) may share it. */\n session_id?: string | null;\n /** Unique per document; required on every embedded subagent trajectory. */\n trajectory_id?: string | null;\n agent: Agent;\n /** At least one step. */\n steps: [Step, ...Step[]];\n notes?: string | null;\n final_metrics?: FinalMetrics | null;\n continued_trajectory_ref?: string | null;\n extra?: Extra | null;\n subagent_trajectories?: Trajectory[] | null;\n}\n", "import { readFile, readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport type {\n Adapter,\n Diagnostic,\n ReadOptions,\n ReadResult,\n} from '../adapter.ts';\nimport {\n ATIF_SCHEMA_VERSION,\n type AgentStep,\n type ContentPart,\n type FinalMetrics,\n type Metrics,\n type ObservationResult,\n type Step,\n type Trajectory,\n} from '../atif.ts';\nimport { SessionReadError } from '../errors.ts';\nimport { ClaudeCodeSession, ClaudeCodeSubagent } from './session.ts';\n\ntype Entry = Record<string, unknown>;\n\n/** Reads a Claude Code transcript into an ATIF v1.8 trajectory, as ADR 0004 maps each entry. */\nexport class ClaudeCodeAdapter implements Adapter<\n ClaudeCodeSession | ClaudeCodeSubagent\n> {\n readonly agent = 'claude-code';\n\n async read(\n session: ClaudeCodeSession | ClaudeCodeSubagent,\n options: ReadOptions = {},\n ): Promise<ReadResult> {\n const path = session.transcriptPath;\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (cause) {\n throw new SessionReadError(path, 'could not read the transcript', {\n cause,\n });\n }\n\n const diagnostics: Diagnostic[] = [];\n const steps: Step[] = [];\n const messages = new Map<string, { step: AgentStep; claudeCode: Entry }>();\n const calls = new Map<string, AgentStep>();\n const meta: Entry = {};\n const unmapped = new Map<string, number>();\n let version: string | undefined;\n const isMain = session instanceof ClaudeCodeSession;\n for (const { entry, line } of entries(text, path, diagnostics)) {\n version ??= stringOr(entry.version);\n if (isMain && entry.isSidechain === true) {\n diagnostics.push({\n code: 'sidechain_entry',\n path,\n line,\n message:\n 'an isSidechain row inside a main transcript belongs to a subagent',\n });\n continue;\n }\n if (entry.type === 'assistant') {\n const step = agentStep(entry, messages, steps.length + 1);\n if (step.step_id === steps.length + 1) steps.push(step);\n for (const call of step.tool_calls ?? [])\n calls.set(call.tool_call_id, step);\n } else if (entry.type === 'user' && toolResults(entry).length > 0) {\n for (const block of toolResults(entry)) {\n const id = stringOr(block.tool_use_id) ?? '';\n const caller = calls.get(id);\n if (!caller) {\n diagnostics.push({\n code: 'orphan_tool_result',\n path,\n line,\n message: `no call ${id} in the transcript for this tool result`,\n });\n continue;\n }\n caller.observation ??= { results: [] };\n caller.observation.results.push(observationResult(entry, block));\n }\n } else if (entry.type === 'user') {\n steps.push(personStep(entry, steps.length + 1));\n } else if (\n entry.type === 'attachment' &&\n record(entry.attachment)?.type === 'queued_command'\n ) {\n steps.push(queuedStep(entry, steps.length + 1));\n } else if (entry.type === 'attachment') {\n steps.push(attachmentStep(entry, steps.length + 1));\n } else if (entry.type === 'system') {\n steps.push(systemRowStep(entry, steps.length + 1));\n } else if (!collectSessionEntry(entry, meta)) {\n const type = stringOr(entry.type) ?? '(no type)';\n unmapped.set(type, (unmapped.get(type) ?? 0) + 1);\n }\n }\n for (const [entryType, count] of unmapped) {\n diagnostics.push({\n code: 'unmapped_entry',\n path,\n entryType,\n count,\n message: `${count} ${entryType} entries are bookkeeping with no step`,\n });\n }\n\n const [first, ...rest] = steps;\n if (!first) {\n throw new SessionReadError(path, 'the transcript holds no step');\n }\n const model = steps.find(\n (step): step is AgentStep =>\n step.source === 'agent' && step.model_name != null,\n )?.model_name;\n const trajectory: Trajectory = {\n schema_version: ATIF_SCHEMA_VERSION,\n ...(isMain\n ? {\n session_id: session.runId,\n ...(session.continuedBy\n ? { continued_trajectory_ref: session.continuedBy }\n : {}),\n }\n : {\n session_id: session.sessionId,\n trajectory_id: session.trajectoryId,\n }),\n agent: {\n name: this.agent,\n version: version ?? 'unknown',\n ...(model ? { model_name: model } : {}),\n },\n steps: [first, ...rest],\n final_metrics: finalMetrics(steps),\n ...(Object.keys(meta).length > 0 ? { extra: { claude_code: meta } } : {}),\n };\n if (isMain && options.subagents !== false) {\n const embedded = await this.#subagents(session, trajectory, diagnostics);\n if (embedded.length > 0) trajectory.subagent_trajectories = embedded;\n }\n return { trajectory, diagnostics };\n }\n\n /**\n * Each `<session>/subagents/agent-*.jsonl`, in name order, as an embedded\n * trajectory. The spawning call's result refers to it through the meta\n * file's `toolUseId`, searched in the root and in every other subagent, so a\n * subagent that another subagent started links too.\n */\n async #subagents(\n session: ClaudeCodeSession,\n root: Trajectory,\n diagnostics: Diagnostic[],\n ): Promise<Trajectory[]> {\n let names: string[];\n try {\n names = await readdir(session.subagentsPath);\n } catch (error) {\n if (errnoCode(error) === 'ENOENT') return [];\n throw new SessionReadError(\n session.subagentsPath,\n 'could not list the subagents',\n {\n cause: error,\n },\n );\n }\n const embedded: { subagent: ClaudeCodeSubagent; trajectory: Trajectory }[] =\n [];\n for (const name of names\n .filter((file) => /^agent-.+\\.jsonl$/.test(file))\n .toSorted()) {\n const subagent = ClaudeCodeSubagent.fromTranscriptPath(\n join(session.subagentsPath, name),\n );\n try {\n const result = await this.read(subagent, { subagents: false });\n diagnostics.push(...result.diagnostics);\n embedded.push({ subagent, trajectory: result.trajectory });\n } catch (error) {\n if (!(error instanceof SessionReadError)) throw error;\n diagnostics.push({\n code: 'unreadable_subagent',\n path: subagent.transcriptPath,\n message: error.message,\n });\n }\n }\n\n const results = new Map<string, ObservationResult>();\n for (const trajectory of [\n root,\n ...embedded.map((entry) => entry.trajectory),\n ]) {\n for (const step of trajectory.steps) {\n for (const result of step.observation?.results ?? []) {\n if (result.source_call_id) results.set(result.source_call_id, result);\n }\n }\n }\n for (const { subagent, trajectory } of embedded) {\n const spawnedBy = stringOr(\n record(await readJson(subagent.metaPath))?.toolUseId,\n );\n const result = spawnedBy ? results.get(spawnedBy) : undefined;\n if (!result) {\n diagnostics.push({\n code: 'unlinked_subagent',\n path: subagent.transcriptPath,\n message: spawnedBy\n ? `no result of call ${spawnedBy} spawned this subagent`\n : 'no meta file names the call that spawned this subagent',\n });\n continue;\n }\n result.subagent_trajectory_ref = [\n ...(result.subagent_trajectory_ref ?? []),\n {\n trajectory_id: trajectory.trajectory_id,\n session_id: trajectory.session_id,\n },\n ];\n }\n return embedded.map((entry) => entry.trajectory);\n }\n}\n\n/**\n * A `user` entry that carries words, not tool results. An explicit `origin`\n * makes it a user step with that origin, `isMeta` or not (peer messages are\n * stored with both). `isMeta` with no origin is injected context (a skill\n * body, a command expansion): a system step. A text entry with neither comes\n * from a build before `origin`: a user step with no origin, so it never counts\n * as typed (ADR 0004 and its amendment).\n */\nfunction personStep(entry: Entry, stepId: number): Step {\n const origin = record(entry.origin)?.kind;\n const isMeta = entry.isMeta === true;\n const message = textOf(record(entry.message)?.content);\n const claudeCode = {\n ...identity(entry),\n ...(typeof origin === 'string' ? { origin } : {}),\n ...(isMeta ? { is_meta: true } : {}),\n };\n const source = typeof origin === 'string' || !isMeta ? 'user' : 'system';\n return {\n step_id: stepId,\n source,\n timestamp: stringOr(entry.timestamp),\n message,\n extra: { claude_code: claudeCode },\n };\n}\n\n/**\n * Claude Code writes each content block of one assistant message as its own\n * entry, repeating the message id and its usage. They merge into one agent\n * step: text and thinking accumulate, each `tool_use` becomes a tool call,\n * and the latest usage becomes the metrics, summed as meticulous's\n * `usageToMetrics` does (ATIF's `prompt_tokens` counts every input token).\n */\nfunction agentStep(\n entry: Entry,\n messages: Map<string, { step: AgentStep; claudeCode: Entry }>,\n nextStepId: number,\n): AgentStep {\n const message = record(entry.message) ?? {};\n const id = stringOr(message.id) ?? stringOr(entry.uuid) ?? String(nextStepId);\n let known = messages.get(id);\n if (!known) {\n const claudeCode: Entry = { ...identity(entry), message_id: id };\n known = {\n claudeCode,\n step: {\n step_id: nextStepId,\n source: 'agent',\n timestamp: stringOr(entry.timestamp),\n message: '',\n extra: { claude_code: claudeCode },\n },\n };\n messages.set(id, known);\n }\n const { step, claudeCode } = known;\n const model = stringOr(message.model);\n if (model && model !== SYNTHETIC_MODEL) step.model_name = model;\n const requestId = stringOr(entry.requestId);\n if (requestId) claudeCode.request_id = requestId;\n const stopReason = stringOr(message.stop_reason);\n if (stopReason) claudeCode.stop_reason = stopReason;\n const usage = record(message.usage);\n if (usage) step.metrics = metricsOf(usage);\n\n for (const block of Array.isArray(message.content) ? message.content : []) {\n const part = record(block);\n if (part?.type === 'text' && typeof part.text === 'string') {\n step.message =\n step.message === ''\n ? part.text\n : `${String(step.message)}\\n${part.text}`;\n } else if (part?.type === 'thinking' && typeof part.thinking === 'string') {\n step.reasoning_content =\n step.reasoning_content == null\n ? part.thinking\n : `${step.reasoning_content}\\n${part.thinking}`;\n } else if (part?.type === 'tool_use') {\n step.tool_calls ??= [];\n step.tool_calls.push({\n tool_call_id: stringOr(part.id) ?? '',\n function_name: stringOr(part.name) ?? '',\n arguments: record(part.input) ?? {},\n });\n }\n }\n return step;\n}\n\n/** Claude Code's placeholder model for messages it writes itself (meticulous's `SYNTHETIC_MODEL`). */\nconst SYNTHETIC_MODEL = '<synthetic>';\n\nfunction metricsOf(usage: Entry): Metrics {\n const input = numberOr(usage.input_tokens);\n const cacheCreation = numberOr(usage.cache_creation_input_tokens);\n const cacheRead = numberOr(usage.cache_read_input_tokens);\n return {\n prompt_tokens: input + cacheCreation + cacheRead,\n completion_tokens: numberOr(usage.output_tokens),\n cached_tokens: cacheRead,\n extra: {\n input_tokens: input,\n cache_creation_input_tokens: cacheCreation,\n cache_read_input_tokens: cacheRead,\n },\n };\n}\n\nfunction toolResults(entry: Entry): Entry[] {\n const content = record(entry.message)?.content;\n return Array.isArray(content)\n ? content.flatMap((block) =>\n isRecord(block) && block.type === 'tool_result' ? [block] : [],\n )\n : [];\n}\n\n/** One tool's result, with Claude Code's structured `toolUseResult` kept in `extra`. */\nfunction observationResult(entry: Entry, block: Entry): ObservationResult {\n const content =\n typeof block.content === 'string'\n ? block.content\n : textParts(block.content);\n return {\n source_call_id: stringOr(block.tool_use_id),\n content,\n extra: {\n claude_code: {\n ...identity(entry),\n is_error: block.is_error === true,\n ...(entry.toolUseResult === undefined\n ? {}\n : { tool_use_result: entry.toolUseResult }),\n },\n },\n };\n}\n\nfunction textParts(content: unknown): ContentPart[] {\n if (!Array.isArray(content)) return [];\n return content.flatMap((block): ContentPart[] =>\n isRecord(block) && block.type === 'text' && typeof block.text === 'string'\n ? [{ type: 'text', text: block.text }]\n : [],\n );\n}\n\nfunction numberOr(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\n/** Any attachment but a queued prompt: a system step that carries it (hook output, snapshots, \u2026). */\nfunction attachmentStep(entry: Entry, stepId: number): Step {\n const attachment = record(entry.attachment) ?? {};\n const content = attachment.content;\n let message = '';\n if (Array.isArray(content)) {\n message = content.filter((part) => typeof part === 'string').join('\\n');\n } else if (typeof content === 'string') {\n message = content;\n }\n return {\n step_id: stepId,\n source: 'system',\n timestamp: stringOr(entry.timestamp),\n message,\n extra: { claude_code: { ...identity(entry), attachment } },\n };\n}\n\n/** A `system` row (stop_hook_summary, turn_duration, compact_boundary, \u2026): a system step that carries it. */\nfunction systemRowStep(entry: Entry, stepId: number): Step {\n return {\n step_id: stepId,\n source: 'system',\n timestamp: stringOr(entry.timestamp),\n message: typeof entry.content === 'string' ? entry.content : '',\n extra: { claude_code: { ...identity(entry), system: entry } },\n };\n}\n\n/** Session-level entries go to the trajectory's extra; returns false for any other entry. */\nfunction collectSessionEntry(entry: Entry, meta: Entry): boolean {\n switch (entry.type) {\n case 'derived-from':\n meta.derived_from = Array.isArray(entry.sessions) ? entry.sessions : [];\n return true;\n case 'ai-title':\n if (typeof entry.aiTitle === 'string') meta.ai_title = entry.aiTitle;\n return true;\n case 'custom-title':\n if (typeof entry.customTitle === 'string')\n meta.custom_title = entry.customTitle;\n return true;\n case 'summary':\n if (typeof entry.summary === 'string') {\n const summaries = Array.isArray(meta.summaries) ? meta.summaries : [];\n meta.summaries = [...summaries, entry.summary];\n }\n return true;\n case 'pr-link': {\n const links = Array.isArray(meta.pr_links) ? meta.pr_links : [];\n meta.pr_links = [...links, entry];\n return true;\n }\n default:\n return false;\n }\n}\n\nfunction finalMetrics(steps: Step[]): FinalMetrics {\n let prompt = 0;\n let completion = 0;\n let cached = 0;\n for (const step of steps) {\n if (step.source !== 'agent' || !step.metrics) continue;\n prompt += step.metrics.prompt_tokens ?? 0;\n completion += step.metrics.completion_tokens ?? 0;\n cached += step.metrics.cached_tokens ?? 0;\n }\n return {\n total_prompt_tokens: prompt,\n total_completion_tokens: completion,\n total_cached_tokens: cached,\n total_steps: steps.length,\n };\n}\n\n/** A prompt delivered while the agent works: a user step with the attachment's own origin. */\nfunction queuedStep(entry: Entry, stepId: number): Step {\n const attachment = record(entry.attachment) ?? {};\n const origin = record(attachment.origin)?.kind;\n return {\n step_id: stepId,\n source: 'user',\n timestamp: stringOr(entry.timestamp),\n message: typeof attachment.prompt === 'string' ? attachment.prompt : '',\n extra: {\n claude_code: {\n ...identity(entry),\n ...(typeof origin === 'string' ? { origin } : {}),\n queued: true,\n },\n },\n };\n}\n\n/** The keys that join a step back to its raw line (ADR 0004). */\nfunction identity(entry: Entry): Entry {\n const keys = {\n uuid: entry.uuid,\n parent_uuid: entry.parentUuid,\n timestamp: entry.timestamp,\n cwd: entry.cwd,\n entrypoint: entry.entrypoint,\n prompt_id: entry.promptId,\n };\n return Object.fromEntries(\n Object.entries(keys).filter(([, value]) => value !== undefined),\n );\n}\n\n/** A message's words: the string itself, or its text blocks joined by newlines. */\nfunction textOf(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content\n .flatMap((block) =>\n isRecord(block) && block.type === 'text' && typeof block.text === 'string'\n ? [block.text]\n : [],\n )\n .join('\\n');\n}\n\nfunction isRecord(value: unknown): value is Entry {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction record(value: unknown): Entry | undefined {\n return isRecord(value) ? value : undefined;\n}\n\nfunction errnoCode(error: unknown): unknown {\n return isRecord(error) ? error.code : undefined;\n}\n\nfunction stringOr(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Each line that parses as a JSON object, with its 1-based line number. A\n * line that does not is a diagnostic: `partial_last_line` when it is the last\n * line and no newline ends it (the agent is still writing it), else\n * `invalid_json_line`.\n */\nfunction* entries(\n text: string,\n path: string,\n diagnostics: Diagnostic[],\n): Generator<{ entry: Entry; line: number }> {\n const lines = text.split('\\n');\n for (const [index, raw] of lines.entries()) {\n if (raw.trim() === '') continue;\n const line = index + 1;\n const entry = parseObject(raw);\n if (entry) {\n yield { entry, line };\n } else if (index === lines.length - 1) {\n diagnostics.push({\n code: 'partial_last_line',\n path,\n line,\n message:\n 'the last line is not yet complete JSON; the agent may still be writing it',\n });\n } else {\n diagnostics.push({\n code: 'invalid_json_line',\n path,\n line,\n message: 'the line is not a JSON object',\n });\n }\n }\n}\n\nfunction parseObject(raw: string): Entry | undefined {\n try {\n const value: unknown = JSON.parse(raw);\n return record(value);\n } catch {\n return undefined;\n }\n}\n\n/** A JSON file's value, or undefined when it is missing or does not parse. */\nasync function readJson(path: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(path, 'utf8'));\n } catch {\n return undefined;\n }\n}\n", "/**\n * The one class a read throws: the session's file is missing, cannot be read\n * or decoded, or holds no step. The caller's next step is the same for each\n * (a hook does not fire, a miner logs and skips), so they share a class and\n * differ only in `cause` (ADR 0009).\n */\nexport class SessionReadError extends Error {\n override readonly name = 'SessionReadError';\n readonly path: string;\n\n constructor(path: string, message: string, options?: { cause?: unknown }) {\n super(`${message}: ${path}`, options);\n this.path = path;\n }\n}\n", "import { basename, dirname, join } from 'node:path';\n\nconst SUBAGENT_FILE = /^agent-(.+)\\.jsonl$/;\n\n/** Only the store places a session in a chain; the package index does not export this key. */\nexport const placeInChain = Symbol('placeInChain');\n\n/**\n * One Claude Code session: `<root>/projects/<project>/<session-id>.jsonl` and\n * its `<session-id>/subagents/` folder. Building one touches no disk.\n */\nexport class ClaudeCodeSession {\n readonly sessionId: string;\n readonly transcriptPath: string;\n /** The run this segment belongs to: the first session id of its /clear chain (ADR 0007). */\n readonly runId: string;\n /** The next segment's transcript, when the chain continues after this one. */\n readonly continuedBy: string | undefined;\n\n private constructor(\n sessionId: string,\n transcriptPath: string,\n runId: string,\n continuedBy: string | undefined,\n ) {\n this.sessionId = sessionId;\n this.transcriptPath = transcriptPath;\n this.runId = runId;\n this.continuedBy = continuedBy;\n }\n\n /** The session of a main transcript path, such as a hook's `transcript_path`. */\n static fromTranscriptPath(path: string): ClaudeCodeSession {\n const name = basename(path);\n if (!name.endsWith('.jsonl') || basename(dirname(path)) === 'subagents') {\n throw new TypeError(\n `not a Claude Code main transcript (expected <session-id>.jsonl; a subagent file is a ClaudeCodeSubagent): ${path}`,\n );\n }\n const sessionId = name.slice(0, -'.jsonl'.length);\n return new ClaudeCodeSession(sessionId, path, sessionId, undefined);\n }\n\n /** The chain gives each segment its run and its successor. */\n static [placeInChain](\n session: ClaudeCodeSession,\n runId: string,\n continuedBy: string | undefined,\n ): ClaudeCodeSession {\n return new ClaudeCodeSession(\n session.sessionId,\n session.transcriptPath,\n runId,\n continuedBy,\n );\n }\n\n /** The folder that holds this session's subagent transcripts. */\n get subagentsPath(): string {\n return join(dirname(this.transcriptPath), this.sessionId, 'subagents');\n }\n}\n\n/**\n * One subagent's transcript: `<session-id>/subagents/agent-<agent-id>.jsonl`,\n * with its `.meta.json` beside it. A SubagentStop hook reads it from\n * `agent_transcript_path`. Building one touches no disk.\n */\nexport class ClaudeCodeSubagent {\n readonly agentId: string;\n /** The session that started this subagent. */\n readonly sessionId: string;\n readonly transcriptPath: string;\n\n private constructor(\n agentId: string,\n sessionId: string,\n transcriptPath: string,\n ) {\n this.agentId = agentId;\n this.sessionId = sessionId;\n this.transcriptPath = transcriptPath;\n }\n\n /** The subagent of a subagent transcript path, such as a hook's `agent_transcript_path`. */\n static fromTranscriptPath(path: string): ClaudeCodeSubagent {\n const match = SUBAGENT_FILE.exec(basename(path));\n const subagents = dirname(path);\n if (!match || basename(subagents) !== 'subagents') {\n throw new TypeError(\n `not a Claude Code subagent transcript (expected <session-id>/subagents/agent-<id>.jsonl): ${path}`,\n );\n }\n return new ClaudeCodeSubagent(match[1], basename(dirname(subagents)), path);\n }\n\n /** The `.meta.json` file beside the transcript, which names the call that spawned it. */\n get metaPath(): string {\n return this.transcriptPath.replace(/\\.jsonl$/, '.meta.json');\n }\n\n /** ATIF's per-document id of this subagent's trajectory. */\n get trajectoryId(): string {\n return `agent-${this.agentId}`;\n }\n}\n"],
5
+ "mappings": ";AAQO,IAAM,sBAAsB;;;ACRnC,SAAS,UAAU,eAAe;AAClC,SAAS,QAAAA,aAAY;;;ACKd,IAAM,mBAAN,cAA+B,MAAM;AA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;AACL,kBAAY,KAAK;AAAA,QACf,MAAM;AAAA,QACN;AAAA,QACA;AAAA,QACA,SAAS;AAAA,MACX,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,SAAS,YAAY,KAAgC;AACnD,MAAI;AACF,UAAM,QAAiB,KAAK,MAAM,GAAG;AACrC,WAAO,OAAO,KAAK;AAAA,EACrB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,eAAe,SAAS,MAAgC;AACtD,MAAI;AACF,WAAO,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;AAAA,EAChD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
6
+ "names": ["join", "join", "claudeCode"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@deepagents/trajectory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "7.53.0",
4
+ "license": "MIT",
5
+ "description": "Read coding-agent sessions (Claude Code transcripts, Codex rollouts) as ATIF v1.8 trajectories.",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/JanuaryLabs/deepagents",
9
+ "directory": "packages/trajectory"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "module": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ "./package.json": "./package.json",
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "default": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "!dist/spec/**",
26
+ "!**/*.tsbuildinfo",
27
+ "!**/*.test.*"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@alwaysmeticulous/agent-traces": "3.2.0"
34
+ },
35
+ "devDependencies": {
36
+ "@zukhruf/fs": "^0.8.144",
37
+ "@zukhruf/parameterized-test": "^0.8.144"
38
+ }
39
+ }