@parcha/agentrun-import 0.0.0-stage → 0.1.0-beta.56

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/read.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { Stats } from "node:fs";
2
+ import type { Env, Locator, Reader, ReadOptions } from "./reader.js";
3
+ import { type Source } from "./readers/index.js";
4
+ import type { SessionOf } from "./types.js";
5
+ export type Session = SessionOf<Source>;
6
+ /** The readers a call reads with: the registry's, or one a caller hands in (a test's, a source not yet registered). */
7
+ export type Readers = Readonly<Record<string, Reader<string, any>>>;
8
+ /** The reader of `source` among `readers`; one that is not there throws. */
9
+ export declare function readerOf(source: string, readers?: Readers): Reader<string, unknown>;
10
+ /** The locators of `source` under `home`, by path, never through a link (a file that is not a regular file is dropped). */
11
+ export declare function sessionLocators(home: string, source: string, { env, readers }?: {
12
+ env?: Env;
13
+ readers?: Readers;
14
+ }): Promise<Locator[]>;
15
+ /** The locators of `source`, each with its file's stats (one gone since it was listed is passed over), in the import's
16
+ * order: the reader's (Claude Code's by project folder, oldest written first: the first file holding a copied record
17
+ * keeps it), else as they were listed. */
18
+ export declare function inOrder(locators: readonly Locator[], source: string, readers?: Readers): Promise<{
19
+ locator: Locator;
20
+ stats: Stats;
21
+ }[]>;
22
+ /** The subagents' sessions of `source` under `home` that name no parent themselves, each with the session it ran under
23
+ * (Claude Code's <session id>/subagents/). */
24
+ export declare function childrenOf(home: string, source: string, { env, readers }?: {
25
+ env?: Env;
26
+ readers?: Readers;
27
+ }): Promise<{
28
+ locator: Locator;
29
+ of: Locator;
30
+ }[]>;
31
+ /** The one session at `locator` (a file alone is its first session), read whole; `turns: false` keeps only what a
32
+ * listing shows. A locator whose session is not there throws. */
33
+ export declare function readSession(locator: Locator | string, source: string, { readers, ...options }?: ReadOptions & {
34
+ readers?: Readers;
35
+ }): Promise<Session>;
36
+ /** Where a session read by readSession is: its file, and its id there when the file holds many. */
37
+ export declare const locatorOf: ({ file, within }: Pick<Session, "file" | "within">) => Locator;
package/dist/read.js ADDED
@@ -0,0 +1,54 @@
1
+ import { lstat, stat } from "node:fs/promises";
2
+ import { READERS } from "./readers/index.js";
3
+ /** The reader of `source` among `readers`; one that is not there throws. */
4
+ export function readerOf(source, readers = READERS) {
5
+ const reader = readers[source];
6
+ if (!reader)
7
+ throw new Error(`no reader for the source ${source}`);
8
+ return reader;
9
+ }
10
+ /** The locators of `source` under `home`, by path, never through a link (a file that is not a regular file is dropped). */
11
+ export async function sessionLocators(home, source, { env, readers } = {}) {
12
+ // A home whose source directory is itself a link is read as found (the person's own), but no file is a link.
13
+ const out = [];
14
+ const found = (await readerOf(source, readers).discover(home, env)).sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : (a.id ?? "").localeCompare(b.id ?? "")));
15
+ for (const locator of found)
16
+ if ((await lstat(locator.file).catch(() => null))?.isFile())
17
+ out.push(locator);
18
+ return out;
19
+ }
20
+ /** The locators of `source`, each with its file's stats (one gone since it was listed is passed over), in the import's
21
+ * order: the reader's (Claude Code's by project folder, oldest written first: the first file holding a copied record
22
+ * keeps it), else as they were listed. */
23
+ export async function inOrder(locators, source, readers) {
24
+ const out = [];
25
+ for (const locator of locators) {
26
+ const stats = await stat(locator.file).catch(() => null);
27
+ if (stats)
28
+ out.push({ locator, stats });
29
+ }
30
+ const order = readerOf(source, readers).order;
31
+ if (order)
32
+ out.sort((a, b) => order({ file: a.locator.file, mtimeMs: a.stats.mtimeMs }, { file: b.locator.file, mtimeMs: b.stats.mtimeMs }));
33
+ return out;
34
+ }
35
+ /** The subagents' sessions of `source` under `home` that name no parent themselves, each with the session it ran under
36
+ * (Claude Code's <session id>/subagents/). */
37
+ export async function childrenOf(home, source, { env, readers } = {}) {
38
+ return (await readerOf(source, readers).children?.(home, env)) ?? [];
39
+ }
40
+ /** The one session at `locator` (a file alone is its first session), read whole; `turns: false` keeps only what a
41
+ * listing shows. A locator whose session is not there throws. */
42
+ export async function readSession(locator, source, { readers, ...options } = {}) {
43
+ const at = typeof locator === "string" ? { file: locator } : locator;
44
+ const { sessions } = await readerOf(source, readers).read(at, undefined, { ...options, keepsCursor: false });
45
+ const found = at.id === undefined ? sessions[0] : sessions.find(({ locator }) => locator.id === at.id);
46
+ if (!found)
47
+ throw new Error(`no session ${at.id ?? ""} in ${at.file}`);
48
+ const session = found.session;
49
+ if (found.locator.id !== undefined)
50
+ session.within = found.locator.id;
51
+ return session;
52
+ }
53
+ /** Where a session read by readSession is: its file, and its id there when the file holds many. */
54
+ export const locatorOf = ({ file, within }) => (within === undefined ? { file } : { file, id: within });
@@ -0,0 +1,69 @@
1
+ import type { Dirent } from "node:fs";
2
+ import type { Answer, SessionOf, Turn } from "./types.js";
3
+ /** The environment a reader may look in for its source's own directories (CLAUDE_CONFIG_DIR, CODEX_HOME). */
4
+ export type Env = Readonly<Record<string, string | undefined>>;
5
+ /** A session's identity: the file it is in, and its id in that file where one file holds many (OpenCode's database). */
6
+ export type Locator = {
7
+ file: string;
8
+ id?: string;
9
+ };
10
+ /** A locator as one string: the file, with `#id` after it when it names one. */
11
+ export declare const locatorKey: ({ file, id }: Locator) => string;
12
+ /** One session a read found: where it is, what it is, and every request read (each counted once), whether turns are kept
13
+ * or not: what a total counts. */
14
+ export type SessionRead<S extends string = string> = {
15
+ locator: Locator;
16
+ session: SessionOf<S>;
17
+ requests: Answer[];
18
+ };
19
+ export type ReadResult<S extends string = string, C = unknown> = {
20
+ /** The locator's sessions: one for a file of one session; each in the file, or the one its id names, for a file of
21
+ * many. */
22
+ sessions: SessionRead<S>[];
23
+ /** Where a later read goes on from. The reader's own: hand it back to the same reader's read, nothing else. */
24
+ cursor: C;
25
+ /** The bytes this read took. */
26
+ read: number;
27
+ /** Whether it went on from the cursor it was handed (false: it read the locator from its start). */
28
+ resumed: boolean;
29
+ };
30
+ export type ReadOptions = {
31
+ /** false keeps only what a listing shows: no turns, nor a request's text or call arguments. */
32
+ turns?: boolean;
33
+ /** The records and requests an import has read already, across its files: a record in it (a copy a resumed session's
34
+ * file carries) adds nothing, and this read's are added to it. A cursor read with one is resumed with the same one. */
35
+ seen?: Set<string>;
36
+ /** false when the caller keeps no cursor from this read (readSession): a last line still being written then adds to
37
+ * `seen` like any other, as no later read takes it again. Default true: it is left out of `seen` until a read from
38
+ * the cursor takes it whole. */
39
+ keepsCursor?: boolean;
40
+ };
41
+ export type Reader<S extends string = string, C = unknown> = {
42
+ source: S;
43
+ /** The source's name as a person reads it. */
44
+ name: string;
45
+ /** The harness of serve that runs what the source ran. */
46
+ harness: string;
47
+ /** The candidate locators of the source under `home`, any order (`env`: where the source's own directory is named). */
48
+ discover: (home: string, env?: Env) => Promise<Locator[]>;
49
+ /** One locator read, from its start or from `cursor` (one this reader returned for the same locator). A cursor that no
50
+ * longer fits (the file replaced, truncated, rewritten) is read from the start, `resumed` false. */
51
+ read: (locator: Locator, cursor?: C, options?: ReadOptions) => Promise<ReadResult<S, C>>;
52
+ /** The import's order of the listed locators, when not their path's (a record copied into two files is the first's). */
53
+ order?: (a: {
54
+ file: string;
55
+ mtimeMs: number;
56
+ }, b: {
57
+ file: string;
58
+ mtimeMs: number;
59
+ }) => number;
60
+ /** Subagents' sessions that name no parent themselves, each with the session it ran under (`of`). */
61
+ children?: (home: string, env?: Env) => Promise<{
62
+ locator: Locator;
63
+ of: Locator;
64
+ }[]>;
65
+ };
66
+ /** A directory's entries, none when it cannot be read. */
67
+ export declare const entries: (dir: string) => Promise<Dirent[]>;
68
+ /** A user turn counted in `session`: its users, its first prompt, and the person's first words. */
69
+ export declare function rememberUser(session: SessionOf, turn: Turn): void;
package/dist/reader.js ADDED
@@ -0,0 +1,14 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { personsWords } from "./text.js";
3
+ /** A locator as one string: the file, with `#id` after it when it names one. */
4
+ export const locatorKey = ({ file, id }) => (id === undefined ? file : `${file}#${id}`);
5
+ /** A directory's entries, none when it cannot be read. */
6
+ export const entries = async (dir) => readdir(dir, { withFileTypes: true }).catch(() => []);
7
+ /** A user turn counted in `session`: its users, its first prompt, and the person's first words. */
8
+ export function rememberUser(session, turn) {
9
+ if (turn.role !== "user")
10
+ return;
11
+ session.users += 1;
12
+ session.firstPrompt ??= turn.text;
13
+ session.titleText ??= personsWords(turn.text);
14
+ }
@@ -0,0 +1,10 @@
1
+ import { type Env } from "../reader.js";
2
+ /** Claude Code's subagents' session files under `home`, in <session id>/subagents/ (a workflow's a folder deeper), each
3
+ * with the session file it ran under (`of`): the one beside the folder it sits in. A session moved to another project
4
+ * folder keeps its id there, with copies of its subagents' files: each folder's are its own file's. Never through a
5
+ * link. */
6
+ export declare function childFiles(home: string, env?: Env): Promise<{
7
+ file: string;
8
+ of: string;
9
+ }[]>;
10
+ export declare const claudeCode: import("../reader.js").Reader<"claude-code", import("../lines.js").FileCursor>;
@@ -0,0 +1,239 @@
1
+ // Claude Code: ~/.claude/projects/<cwd slug>/<session id>.jsonl, its subagents' in <session id>/subagents/ (children).
2
+ import { lstat } from "node:fs/promises";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { lineReader } from "../lines.js";
5
+ import { entries } from "../reader.js";
6
+ import { argsOf, effortOf, INTERRUPTED, isObject, str, textOf } from "../text.js";
7
+ import { normalizeUsage } from "../usage.js";
8
+ // The titles Claude Code writes into a session's file, each again as it changes, and the field each holds it in.
9
+ const TITLES = new Map([
10
+ ["custom-title", "customTitle"],
11
+ ["ai-title", "aiTitle"],
12
+ ["summary", "summary"],
13
+ ]);
14
+ /** One of Claude Code's title records: kept by kind, the latest of each. A summary names the last message of the
15
+ * conversation it titles (leafUuid), which can be another session's: held until the file's end. */
16
+ function titleRecord(value, session, titles) {
17
+ // As written: the cut matches a key or a passphrase as the source wrote it, so the title is put on one line after it.
18
+ const title = str(value[TITLES.get(value.type)])?.trim();
19
+ if (!title || (str(value.sessionId) && value.sessionId !== session.id))
20
+ return;
21
+ if (value.type === "custom-title")
22
+ titles.custom = title;
23
+ else if (value.type === "ai-title")
24
+ titles.ai = title;
25
+ else
26
+ titles.summaries.push({ title, ...(str(value.leafUuid) ? { leaf: value.leafUuid } : {}) });
27
+ }
28
+ /** A request's key: its message id with the request id it was sent as (ccusage's pair). Claude Code writes one line per
29
+ * content block of a response, each with both. */
30
+ const keyOf = (message, value) => {
31
+ const id = str(message.id);
32
+ const request = str(value.requestId);
33
+ return id && request ? `${id}:${request}` : id;
34
+ };
35
+ /** Claude Code's record; false for one read already (the import's earlier file, or this file's own repeat). */
36
+ function record(value, at, { state, seen, keep, add }) {
37
+ const { session, names, own } = state;
38
+ // Claude Code names a session's file for its id (<id>.jsonl): the file's own, whatever a record in it says. A resumed
39
+ // session's file can open with records copied from the session it resumed, each still naming that one.
40
+ if (!session.id)
41
+ session.id = basename(session.file, ".jsonl");
42
+ if (!session.cwd && str(value.cwd))
43
+ session.cwd = value.cwd;
44
+ if (value.isSidechain === true)
45
+ session.child = true;
46
+ if (TITLES.has(value.type))
47
+ return titleRecord(value, session, own.titles);
48
+ if (str(value.uuid))
49
+ own.titles.uuids.add(value.uuid);
50
+ if (value.type === "cost-state") {
51
+ // The last one is the session's: unknown when the CLI could not price a model it used.
52
+ session.costUsd = typeof value.totalCostUSD === "number" && Number.isFinite(value.totalCostUSD) && value.totalCostUSD >= 0 && value.hasUnknownModelCost !== true ? value.totalCostUSD : undefined;
53
+ return;
54
+ }
55
+ // A record written twice (a session carried on in its own file, or copied into a resumed one's) is read once, and moves
56
+ // no time a second time, whatever its type.
57
+ const uuid = str(value.uuid);
58
+ if (uuid && seen.has(`u:${uuid}`))
59
+ return false;
60
+ if (uuid)
61
+ seen.add(`u:${uuid}`);
62
+ if ((value.type !== "user" && value.type !== "assistant") || !isObject(value.message))
63
+ return;
64
+ if (value.isMeta === true || value.isCompactSummary === true || value.isVisibleInTranscriptOnly === true)
65
+ return;
66
+ const mark = uuid ? { uuids: [uuid] } : {};
67
+ const message = value.message;
68
+ if (value.type === "assistant") {
69
+ const model = str(message.model);
70
+ const synthetic = model === "<synthetic>";
71
+ if (model && !synthetic)
72
+ session.model = `anthropic/${model}`;
73
+ const blocks = Array.isArray(message.content) ? message.content : [{ type: "text", text: textOf(message.content) }];
74
+ const text = blocks
75
+ .filter((b) => isObject(b) && b.type === "text")
76
+ .map((b) => b.text)
77
+ .join("\n");
78
+ const calls = blocks
79
+ .filter((b) => isObject(b) && b.type === "tool_use")
80
+ .map((b) => ({
81
+ type: "toolCall",
82
+ id: String(b.id ?? ""),
83
+ name: String(b.name ?? ""),
84
+ arguments: keep ? argsOf(b.input) : {},
85
+ }));
86
+ for (const call of calls)
87
+ names.set(call.id, call.name);
88
+ // The CLI's own turns (model <synthetic>): one marked an API error is a request that failed; any other ("No response
89
+ // requested.") is no request, kept as the CLI's note.
90
+ const failed = value.isApiErrorMessage === true;
91
+ if (synthetic && !failed) {
92
+ if (text)
93
+ add({ role: "note", author: "Claude Code", text, at, ...mark });
94
+ return;
95
+ }
96
+ session.state = failed ? "failed" : "completed";
97
+ // One request's blocks come as lines of one key, a parallel call's result between two of them: one turn. Each line
98
+ // repeats the request's usage, and the last one written holds its final counts (an earlier one may hold only the
99
+ // stream's start): the last line's usage is the request's.
100
+ const key = keyOf(message, value);
101
+ const usage = normalizeUsage("anthropic", message.usage);
102
+ const held = key ? own.keyed.get(key) : undefined;
103
+ if (held) {
104
+ if (keep)
105
+ held.text = [held.text, text].filter(Boolean).join("\n");
106
+ held.calls.push(...calls);
107
+ if (uuid)
108
+ held.uuids = [...(held.uuids ?? []), uuid];
109
+ if (usage)
110
+ held.usage = usage;
111
+ return;
112
+ }
113
+ // A request an earlier file of the import holds: counted there, never again; its calls' results are copies too. A
114
+ // store imported before requests were keyed by message and request id holds the bare message id ("l:", serve's).
115
+ if (key && (seen.has(`m:${key}`) || (str(message.id) && seen.has(`l:${message.id}`)))) {
116
+ for (const call of calls)
117
+ own.copied.add(call.id);
118
+ return false;
119
+ }
120
+ if (!key && !text && calls.length === 0)
121
+ return;
122
+ const effort = effortOf(value.perTurnEffort) ?? effortOf(value.effort);
123
+ // Without turns, no answer text: the request is kept for its counts, in the result and the cursor alike.
124
+ const turn = { role: "assistant", text: keep ? text : "", calls, at, ...(key ? { key } : {}), ...(session.model ? { model: session.model } : {}), ...(effort ? { effort } : {}), ...(usage ? { usage } : {}), ...(failed ? { error: text || "API error" } : {}), ...mark };
125
+ if (key) {
126
+ own.keyed.set(key, turn);
127
+ seen.add(`m:${key}`);
128
+ }
129
+ add(turn);
130
+ return;
131
+ }
132
+ if (typeof message.content === "string") {
133
+ if (INTERRUPTED.test(message.content))
134
+ session.state = "stopped";
135
+ else
136
+ session.state = "completed";
137
+ return add({ role: "user", text: message.content, at, ...mark });
138
+ }
139
+ if (!Array.isArray(message.content))
140
+ return;
141
+ const said = [];
142
+ let results = 0;
143
+ let copies = 0;
144
+ for (const block of message.content) {
145
+ if (!isObject(block))
146
+ continue;
147
+ if (block.type === "text" && typeof block.text === "string")
148
+ said.push(block.text);
149
+ else if (block.type === "tool_result") {
150
+ const id = String(block.tool_use_id ?? "");
151
+ results += 1;
152
+ if (own.copied.has(id)) {
153
+ copies += 1;
154
+ continue;
155
+ }
156
+ add({
157
+ role: "toolResult",
158
+ callId: id,
159
+ name: names.get(id) ?? "",
160
+ text: textOf(block.content),
161
+ isError: block.is_error === true,
162
+ at,
163
+ ...mark,
164
+ });
165
+ }
166
+ }
167
+ if (said.length) {
168
+ const text = said.join("\n");
169
+ session.state = INTERRUPTED.test(text) ? "stopped" : "completed";
170
+ add({ role: "user", text, at, ...mark });
171
+ }
172
+ // Results of copied calls alone: a copy, which moves no time either.
173
+ if (results > 0 && copies === results && !said.length)
174
+ return false;
175
+ }
176
+ /** Claude Code's subagents' session files under `home`, in <session id>/subagents/ (a workflow's a folder deeper), each
177
+ * with the session file it ran under (`of`): the one beside the folder it sits in. A session moved to another project
178
+ * folder keeps its id there, with copies of its subagents' files: each folder's are its own file's. Never through a
179
+ * link. */
180
+ export async function childFiles(home, env) {
181
+ const root = join(configDir(home, env), "projects");
182
+ const out = [];
183
+ for (const project of await entries(root)) {
184
+ if (!project.isDirectory())
185
+ continue;
186
+ for (const session of await entries(join(root, project.name))) {
187
+ if (!session.isDirectory())
188
+ continue;
189
+ const walk = async (dir, depth) => {
190
+ for (const entry of await entries(dir)) {
191
+ if (entry.isDirectory() && depth < 3)
192
+ await walk(join(dir, entry.name), depth + 1);
193
+ else if (entry.isFile() && entry.name.endsWith(".jsonl"))
194
+ out.push({ file: join(dir, entry.name), of: join(root, project.name, `${session.name}.jsonl`) });
195
+ }
196
+ };
197
+ // The folder itself is no link: one that points elsewhere holds no subagent of this session's.
198
+ const subagents = join(root, project.name, session.name, "subagents");
199
+ if ((await lstat(subagents).catch(() => null))?.isDirectory())
200
+ await walk(subagents, 0);
201
+ }
202
+ }
203
+ return out.sort((a, b) => a.file.localeCompare(b.file));
204
+ }
205
+ /** Claude Code's own directory: CLAUDE_CONFIG_DIR where the environment names it, else ~/.claude. */
206
+ const configDir = (home, env) => env?.CLAUDE_CONFIG_DIR || join(home, ".claude");
207
+ const spec = {
208
+ source: "claude-code",
209
+ name: "Claude Code",
210
+ harness: "claude-agent",
211
+ async files(home, env) {
212
+ const root = join(configDir(home, env), "projects");
213
+ const out = [];
214
+ for (const project of await entries(root)) {
215
+ if (!project.isDirectory())
216
+ continue;
217
+ for (const file of await entries(join(root, project.name)))
218
+ if (file.isFile() && file.name.endsWith(".jsonl"))
219
+ out.push(join(root, project.name, file.name));
220
+ }
221
+ return out;
222
+ },
223
+ // By project folder, oldest written first: the first file holding a copied record keeps it.
224
+ order: (a, b) => dirname(a.file).localeCompare(dirname(b.file)) || a.mtimeMs - b.mtimeMs || a.file.localeCompare(b.file),
225
+ children: childFiles,
226
+ start: () => ({ keyed: new Map(), copied: new Set(), titles: { summaries: [], uuids: new Set() } }),
227
+ record,
228
+ finish(out, turns, { state: { own } }) {
229
+ const { titles } = own;
230
+ const sourceTitle = titles.custom ?? titles.ai ?? titles.summaries.findLast(({ leaf }) => leaf === undefined || titles.uuids.has(leaf))?.title;
231
+ if (sourceTitle)
232
+ out.sourceTitle = sourceTitle;
233
+ return turns;
234
+ },
235
+ idOf: (file) => basename(file, ".jsonl"),
236
+ // A turns: false cursor keeps no title: a read resumed from it gives none.
237
+ forget: (own) => ({ ...own, titles: { summaries: [], uuids: new Set() } }),
238
+ };
239
+ export const claudeCode = lineReader(spec);
@@ -0,0 +1 @@
1
+ export declare const codex: import("../reader.js").Reader<"codex", import("../lines.js").FileCursor>;