@parcha/agentrun-import 0.0.0-bootstrap.0 → 0.1.0-beta.55

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.
@@ -0,0 +1 @@
1
+ export declare const pi: import("../reader.js").Reader<"pi", import("../lines.js").FileCursor>;
@@ -0,0 +1,99 @@
1
+ // pi: ~/.pi/agent/sessions/--<cwd>--/<time>_<session id>.jsonl. pi prices each request itself.
2
+ import { basename, join } from "node:path";
3
+ import { lineReader } from "../lines.js";
4
+ import { entries } from "../reader.js";
5
+ import { argsOf, effortOf, isObject, str, textOf, timeOf } from "../text.js";
6
+ import { normalizeUsage } from "../usage.js";
7
+ function record(value, at, { state, keep, add }) {
8
+ const { session, priced } = state;
9
+ if (value.type === "session") {
10
+ if (str(value.id))
11
+ session.id = value.id;
12
+ if (str(value.cwd))
13
+ session.cwd = value.cwd;
14
+ return;
15
+ }
16
+ if (value.type === "model_change") {
17
+ if (str(value.provider) && str(value.modelId))
18
+ session.model = `${value.provider}/${value.modelId}`;
19
+ return;
20
+ }
21
+ if (value.type === "thinking_level_change") {
22
+ state.effort = effortOf(value.thinkingLevel);
23
+ return;
24
+ }
25
+ if (value.type !== "message" || !isObject(value.message))
26
+ return;
27
+ const message = value.message;
28
+ const when = timeOf(message.timestamp) ?? at;
29
+ if (message.role === "user")
30
+ add({ role: "user", text: textOf(message.content), at: when });
31
+ else if (message.role === "toolResult")
32
+ add({
33
+ role: "toolResult",
34
+ callId: String(message.toolCallId ?? ""),
35
+ name: String(message.toolName ?? ""),
36
+ text: textOf(message.content),
37
+ isError: message.isError === true,
38
+ at: when,
39
+ });
40
+ else if (message.role === "assistant") {
41
+ if (str(message.provider) && str(message.model))
42
+ session.model = `${message.provider}/${message.model}`;
43
+ const blocks = Array.isArray(message.content) ? message.content : [];
44
+ const text = blocks
45
+ .filter((b) => isObject(b) && b.type === "text")
46
+ .map((b) => b.text)
47
+ .join("\n");
48
+ const calls = blocks
49
+ .filter((b) => isObject(b) && b.type === "toolCall")
50
+ .map((b) => ({
51
+ type: "toolCall",
52
+ id: String(b.id ?? ""),
53
+ name: String(b.name ?? ""),
54
+ arguments: keep ? argsOf(b.arguments) : {},
55
+ }));
56
+ const usage = isObject(message.usage) && isObject(message.usage.cost) ? message.usage.cost : undefined;
57
+ const cost = typeof usage?.total === "number" && Number.isFinite(usage.total) && usage.total >= 0 ? usage.total : undefined;
58
+ // pi prices each request: the session's cost is their sum, unknown once one is not priced.
59
+ priced.sum += cost ?? 0;
60
+ priced.unknown ||= cost === undefined;
61
+ session.costUsd = priced.unknown ? undefined : priced.sum;
62
+ session.state = message.stopReason === "error" ? "failed" : message.stopReason === "aborted" ? "stopped" : "completed";
63
+ // A request cut before its end has only the start of its counts: unknown, as a live run's.
64
+ const tokens = message.stopReason === "aborted" ? undefined : normalizeUsage("pi", message.usage);
65
+ // Without turns, no answer text: the request is kept for its counts, in the result and the cursor alike.
66
+ add({
67
+ role: "assistant",
68
+ text: keep ? text : "",
69
+ calls,
70
+ at: when,
71
+ ...(cost !== undefined ? { costUsd: cost } : {}),
72
+ ...(session.model ? { model: session.model } : {}),
73
+ ...(state.effort ? { effort: state.effort } : {}),
74
+ ...(tokens ? { usage: tokens } : {}),
75
+ ...(message.stopReason === "error" ? { error: str(message.errorMessage) ?? "unknown error" } : {}),
76
+ });
77
+ }
78
+ }
79
+ const spec = {
80
+ source: "pi",
81
+ name: "pi",
82
+ harness: "pi",
83
+ async files(home) {
84
+ const root = join(home, ".pi", "agent", "sessions");
85
+ const out = [];
86
+ for (const project of await entries(root)) {
87
+ if (!project.isDirectory())
88
+ continue;
89
+ for (const file of await entries(join(root, project.name)))
90
+ if (file.isFile() && file.name.endsWith(".jsonl"))
91
+ out.push(join(root, project.name, file.name));
92
+ }
93
+ return out;
94
+ },
95
+ start: () => undefined,
96
+ record,
97
+ idOf: (file) => basename(file, ".jsonl").split("_").pop(),
98
+ };
99
+ export const pi = lineReader(spec);
@@ -0,0 +1,43 @@
1
+ import { type Packed } from "./record-key.js";
2
+ /** One kind of key's entries, in the order added, and the open-addressing slots (linear probing) that find them:
3
+ * 0 an empty slot, else an entry's index + 1. */
4
+ type Table = {
5
+ count: number;
6
+ slots: Int32Array;
7
+ owners: Int32Array;
8
+ };
9
+ /** A uuid's keys: four 32-bit words an entry. */
10
+ type Uuids = Table & {
11
+ words: Int32Array;
12
+ };
13
+ /** Any other key's: entry i's bytes are bytes[ends[i - 1] (0 for the first), ends[i]). */
14
+ type Others = Table & {
15
+ ends: Float64Array;
16
+ bytes: Uint8Array;
17
+ used: number;
18
+ };
19
+ export type RecordIndex = {
20
+ uuids: Uuids;
21
+ others: Others;
22
+ /** The locators the owners number, by number, and their numbers. */
23
+ locators: string[];
24
+ numbers: Map<string, number>;
25
+ };
26
+ /** An empty index, its slots `slots` (a power of 2) to start with. */
27
+ export declare const recordIndex: (slots?: number) => RecordIndex;
28
+ /** Whether `value` is a RecordIndex: a HomeState kept by an earlier version holds its records in a Map instead. */
29
+ export declare function isRecordIndex(value: unknown): value is RecordIndex;
30
+ /** The number of `locator` in `index`, given one when it has none. */
31
+ export declare function locatorNumber(index: RecordIndex, locator: string): number;
32
+ /** How many records `index` holds. */
33
+ export declare const recordCount: (index: RecordIndex) => number;
34
+ /** The owner (its number) of the record packed as `key`, else -1. */
35
+ export declare function ownerOf(index: RecordIndex, { bytes, length }: Packed): number;
36
+ /** The record packed as `key` added, owned by `owner` (a number of the index the owners refer to); one held already is
37
+ * left as it is. */
38
+ export declare function addRecord(index: RecordIndex, key: Packed, owner: number): void;
39
+ /** Every record of `from` added to `into`, in the order `from` took them, each with its owner. */
40
+ export declare function addAll(into: RecordIndex, from: RecordIndex): void;
41
+ /** `index` without the records `owner` owns: the rest kept in their order. */
42
+ export declare function dropOwner(index: RecordIndex, owner: number): void;
43
+ export {};
@@ -0,0 +1,192 @@
1
+ // The records a source's import has read, each with the locator it counts in: an exact hash index on typed arrays. A
2
+ // uuid's key is held in 16 bytes, any other's packed bytes (record-key.ts) in one arena, the locator as a number. A Map
3
+ // holds at most 2^24 entries, at about 100 bytes each with its key's string; this holds as many as the arrays can, at
4
+ // about 35 bytes a uuid's. Its keys are whole, never a hash of them: no two records are ever taken for one.
5
+ // Plain data (typed arrays, an array, a Map of strings): structuredClone and v8.serialize keep it, as HomeState asks.
6
+ import { UUID } from "./record-key.js";
7
+ const LOAD = 0.75;
8
+ const table = (slots) => ({ count: 0, slots: new Int32Array(slots), owners: new Int32Array(slots >> 1) });
9
+ /** An empty index, its slots `slots` (a power of 2) to start with. */
10
+ export const recordIndex = (slots = 1024) => ({
11
+ uuids: { ...table(slots), words: new Int32Array((slots >> 1) * 4) },
12
+ others: { ...table(slots), ends: new Float64Array(slots >> 1), bytes: new Uint8Array(slots * 8), used: 0 },
13
+ locators: [],
14
+ numbers: new Map(),
15
+ });
16
+ /** Whether `value` is a RecordIndex: a HomeState kept by an earlier version holds its records in a Map instead. */
17
+ export function isRecordIndex(value) {
18
+ const index = value;
19
+ return typeof index === "object" && index !== null && index.uuids?.slots instanceof Int32Array && index.others?.bytes instanceof Uint8Array && Array.isArray(index.locators) && index.numbers instanceof Map;
20
+ }
21
+ /** The number of `locator` in `index`, given one when it has none. */
22
+ export function locatorNumber(index, locator) {
23
+ let n = index.numbers.get(locator);
24
+ if (n === undefined)
25
+ index.numbers.set(locator, (n = index.locators.push(locator) - 1));
26
+ return n;
27
+ }
28
+ /** How many records `index` holds. */
29
+ export const recordCount = (index) => index.uuids.count + index.others.count;
30
+ // murmur3's finalizer: every bit of the input moves the slot.
31
+ const mix = (h) => {
32
+ h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
33
+ h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
34
+ return (h ^ (h >>> 16)) >>> 0;
35
+ };
36
+ const word = (b, at) => b[at] | (b[at + 1] << 8) | (b[at + 2] << 16) | (b[at + 3] << 24);
37
+ const uuidHash = (w0, w1, w2, w3) => mix(w0 ^ mix(w1 ^ mix(w2 ^ mix(w3))));
38
+ function bytesHash(b, from, to) {
39
+ let h = 0x811c9dc5;
40
+ for (let i = from; i < to; i += 1)
41
+ h = Math.imul(h ^ b[i], 0x01000193);
42
+ return mix(h ^ (to - from));
43
+ }
44
+ /** The entry of `t` with these words, else -1. */
45
+ function findUuid(t, w0, w1, w2, w3, h) {
46
+ const mask = t.slots.length - 1;
47
+ for (let s = h & mask;; s = (s + 1) & mask) {
48
+ const e = t.slots[s];
49
+ if (e === 0)
50
+ return -1;
51
+ const at = (e - 1) * 4;
52
+ if (t.words[at] === w0 && t.words[at + 1] === w1 && t.words[at + 2] === w2 && t.words[at + 3] === w3)
53
+ return e - 1;
54
+ }
55
+ }
56
+ /** The entry of `t` whose key is b[from, to), else -1. */
57
+ function findOther(t, b, from, to, h) {
58
+ const mask = t.slots.length - 1;
59
+ const n = to - from;
60
+ for (let s = h & mask;; s = (s + 1) & mask) {
61
+ const e = t.slots[s];
62
+ if (e === 0)
63
+ return -1;
64
+ const end = t.ends[e - 1];
65
+ const start = e === 1 ? 0 : t.ends[e - 2];
66
+ if (end - start !== n)
67
+ continue;
68
+ let i = 0;
69
+ while (i < n && t.bytes[start + i] === b[from + i])
70
+ i += 1;
71
+ if (i === n)
72
+ return e - 1;
73
+ }
74
+ }
75
+ /** A free slot of `t` for a key hashed `h`. */
76
+ function freeSlot(t, h) {
77
+ const mask = t.slots.length - 1;
78
+ let s = h & mask;
79
+ while (t.slots[s] !== 0)
80
+ s = (s + 1) & mask;
81
+ return s;
82
+ }
83
+ /** Room in `t` for one more entry: its entries' arrays and its slots doubled when full. */
84
+ function roomUuid(t) {
85
+ if (t.count === t.owners.length) {
86
+ t.owners = grown(t.owners, t.owners.length * 2);
87
+ t.words = grown(t.words, t.words.length * 2);
88
+ }
89
+ if (t.count + 1 > t.slots.length * LOAD) {
90
+ t.slots = new Int32Array(t.slots.length * 2);
91
+ for (let i = 0; i < t.count; i += 1)
92
+ t.slots[freeSlot(t, uuidHash(t.words[i * 4], t.words[i * 4 + 1], t.words[i * 4 + 2], t.words[i * 4 + 3]))] = i + 1;
93
+ }
94
+ }
95
+ function roomOther(t, n) {
96
+ if (t.count === t.owners.length) {
97
+ t.owners = grown(t.owners, t.owners.length * 2);
98
+ t.ends = grown(t.ends, t.ends.length * 2);
99
+ }
100
+ if (t.used + n > t.bytes.length)
101
+ t.bytes = grown(t.bytes, Math.max(t.bytes.length * 2, t.used + n));
102
+ if (t.count + 1 > t.slots.length * LOAD) {
103
+ t.slots = new Int32Array(t.slots.length * 2);
104
+ for (let i = 0; i < t.count; i += 1) {
105
+ const start = i === 0 ? 0 : t.ends[i - 1];
106
+ t.slots[freeSlot(t, bytesHash(t.bytes, start, t.ends[i]))] = i + 1;
107
+ }
108
+ }
109
+ }
110
+ function grown(from, length) {
111
+ const to = new from.constructor(length);
112
+ to.set(from);
113
+ return to;
114
+ }
115
+ function addUuid(t, w0, w1, w2, w3, owner) {
116
+ roomUuid(t);
117
+ const i = t.count++;
118
+ t.words[i * 4] = w0;
119
+ t.words[i * 4 + 1] = w1;
120
+ t.words[i * 4 + 2] = w2;
121
+ t.words[i * 4 + 3] = w3;
122
+ t.owners[i] = owner;
123
+ t.slots[freeSlot(t, uuidHash(w0, w1, w2, w3))] = i + 1;
124
+ }
125
+ function addOther(t, b, from, to, owner) {
126
+ roomOther(t, to - from);
127
+ const i = t.count++;
128
+ t.bytes.set(b.subarray(from, to), t.used);
129
+ t.used += to - from;
130
+ t.ends[i] = t.used;
131
+ t.owners[i] = owner;
132
+ t.slots[freeSlot(t, bytesHash(b, from, to))] = i + 1;
133
+ }
134
+ /** The owner (its number) of the record packed as `key`, else -1. */
135
+ export function ownerOf(index, { bytes, length }) {
136
+ if (bytes[0] === UUID && length === 17) {
137
+ const w0 = word(bytes, 1);
138
+ const w1 = word(bytes, 5);
139
+ const w2 = word(bytes, 9);
140
+ const w3 = word(bytes, 13);
141
+ const e = findUuid(index.uuids, w0, w1, w2, w3, uuidHash(w0, w1, w2, w3));
142
+ return e === -1 ? -1 : index.uuids.owners[e];
143
+ }
144
+ const e = findOther(index.others, bytes, 0, length, bytesHash(bytes, 0, length));
145
+ return e === -1 ? -1 : index.others.owners[e];
146
+ }
147
+ /** The record packed as `key` added, owned by `owner` (a number of the index the owners refer to); one held already is
148
+ * left as it is. */
149
+ export function addRecord(index, key, owner) {
150
+ if (ownerOf(index, key) !== -1)
151
+ return;
152
+ const { bytes, length } = key;
153
+ if (bytes[0] === UUID && length === 17)
154
+ addUuid(index.uuids, word(bytes, 1), word(bytes, 5), word(bytes, 9), word(bytes, 13), owner);
155
+ else
156
+ addOther(index.others, bytes, 0, length, owner);
157
+ }
158
+ /** Every record of `from` added to `into`, in the order `from` took them, each with its owner. */
159
+ export function addAll(into, from) {
160
+ const u = from.uuids;
161
+ for (let i = 0; i < u.count; i += 1) {
162
+ const w0 = u.words[i * 4];
163
+ const w1 = u.words[i * 4 + 1];
164
+ const w2 = u.words[i * 4 + 2];
165
+ const w3 = u.words[i * 4 + 3];
166
+ if (findUuid(into.uuids, w0, w1, w2, w3, uuidHash(w0, w1, w2, w3)) === -1)
167
+ addUuid(into.uuids, w0, w1, w2, w3, u.owners[i]);
168
+ }
169
+ const o = from.others;
170
+ for (let i = 0; i < o.count; i += 1) {
171
+ const start = i === 0 ? 0 : o.ends[i - 1];
172
+ const end = o.ends[i];
173
+ if (findOther(into.others, o.bytes, start, end, bytesHash(o.bytes, start, end)) === -1)
174
+ addOther(into.others, o.bytes, start, end, o.owners[i]);
175
+ }
176
+ }
177
+ /** `index` without the records `owner` owns: the rest kept in their order. */
178
+ export function dropOwner(index, owner) {
179
+ const u = index.uuids;
180
+ const o = index.others;
181
+ const kept = recordIndex();
182
+ kept.locators = index.locators;
183
+ kept.numbers = index.numbers;
184
+ for (let i = 0; i < u.count; i += 1)
185
+ if (u.owners[i] !== owner)
186
+ addUuid(kept.uuids, u.words[i * 4], u.words[i * 4 + 1], u.words[i * 4 + 2], u.words[i * 4 + 3], u.owners[i]);
187
+ for (let i = 0; i < o.count; i += 1)
188
+ if (o.owners[i] !== owner)
189
+ addOther(kept.others, o.bytes, i === 0 ? 0 : o.ends[i - 1], o.ends[i], o.owners[i]);
190
+ index.uuids = kept.uuids;
191
+ index.others = kept.others;
192
+ }
@@ -0,0 +1,11 @@
1
+ export declare const UUID = 1;
2
+ /** A key packed: `bytes[0, length)`. The buffer is reused by the next packInto with the same Packed. */
3
+ export type Packed = {
4
+ bytes: Uint8Array;
5
+ length: number;
6
+ };
7
+ export declare const packed: () => Packed;
8
+ /** `key` packed into `out`, its buffer grown when the key needs more. */
9
+ export declare function packInto(key: string, out: Packed): Packed;
10
+ /** `key` packed, as bytes of its own. */
11
+ export declare const packKey: (key: string) => Uint8Array;
@@ -0,0 +1,98 @@
1
+ // The keys of the records an import has read (a reader's "u:<uuid>", "m:<message id>:<request id>", "l:<message id>"),
2
+ // packed into bytes for the index that holds one per record across a source (RecordIndex): a large home has tens of
3
+ // millions. One-to-one: two keys pack the same only when they are the same, so no record is taken for a copy that is not
4
+ // one. Packed keys are the index's alone; nothing reads them back. The first byte says how the rest is packed:
5
+ // 1 "u:" and a uuid as Claude Code writes it (lowercase hex, 8-4-4-4-12): its 16 bytes
6
+ // 2-5 any other key made only of [0-9A-Za-z_:]: six bits a char; the byte is 2 + its length mod 4
7
+ // 0 anything else: its UTF-16 code units, two bytes each, low byte first
8
+ export const UUID = 1;
9
+ const SIXES = 2;
10
+ const AS_IS = 0;
11
+ // Each char code's value: a lowercase hex digit's (else -1), and its place among the 64 letters (else -1).
12
+ const HEX = new Int8Array(128).fill(-1);
13
+ for (let i = 0; i < 16; i += 1)
14
+ HEX["0123456789abcdef".charCodeAt(i)] = i;
15
+ const LETTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_:";
16
+ const SIX = new Int8Array(128).fill(-1);
17
+ for (let i = 0; i < 64; i += 1)
18
+ SIX[LETTERS.charCodeAt(i)] = i;
19
+ export const packed = () => ({ bytes: new Uint8Array(64), length: 0 });
20
+ /** "u:<uuid>" into `out` as its 16 bytes; false (out unset) for any other key. */
21
+ function uuidInto(key, out) {
22
+ if (key.length !== 38 || key.charCodeAt(0) !== 117 || key.charCodeAt(1) !== 58)
23
+ return false;
24
+ out[0] = UUID;
25
+ let at = 1;
26
+ let high = -1;
27
+ for (let i = 2; i < 38; i += 1) {
28
+ const code = key.charCodeAt(i);
29
+ // The hyphens at 8, 13, 18 and 23 of the uuid.
30
+ if (i === 10 || i === 15 || i === 20 || i === 25) {
31
+ if (code !== 45)
32
+ return false;
33
+ continue;
34
+ }
35
+ const digit = code < 128 ? HEX[code] : -1;
36
+ if (digit === -1)
37
+ return false;
38
+ if (high === -1)
39
+ high = digit;
40
+ else {
41
+ out[at++] = (high << 4) | digit;
42
+ high = -1;
43
+ }
44
+ }
45
+ return true;
46
+ }
47
+ /** A key of the 64 letters into `out`, six bits a char: its packed length, -1 for any other key. */
48
+ function sixesInto(key, out) {
49
+ const n = key.length;
50
+ out[0] = SIXES + (n % 4);
51
+ let at = 1;
52
+ let bits = 0;
53
+ let held = 0;
54
+ for (let i = 0; i < n; i += 1) {
55
+ const code = key.charCodeAt(i);
56
+ const six = code < 128 ? SIX[code] : -1;
57
+ if (six === -1)
58
+ return -1;
59
+ held = (held << 6) | six;
60
+ bits += 6;
61
+ if (bits >= 8) {
62
+ bits -= 8;
63
+ out[at++] = (held >> bits) & 0xff;
64
+ held &= (1 << bits) - 1;
65
+ }
66
+ }
67
+ if (bits > 0)
68
+ out[at++] = (held << (8 - bits)) & 0xff;
69
+ return at;
70
+ }
71
+ /** `key` packed into `out`, its buffer grown when the key needs more. */
72
+ export function packInto(key, out) {
73
+ if (out.bytes.length < 1 + key.length * 2)
74
+ out.bytes = new Uint8Array(Math.max(1 + key.length * 2, out.bytes.length * 2));
75
+ const bytes = out.bytes;
76
+ if (uuidInto(key, bytes)) {
77
+ out.length = 17;
78
+ return out;
79
+ }
80
+ const six = sixesInto(key, bytes);
81
+ if (six !== -1) {
82
+ out.length = six;
83
+ return out;
84
+ }
85
+ bytes[0] = AS_IS;
86
+ for (let i = 0; i < key.length; i += 1) {
87
+ const code = key.charCodeAt(i);
88
+ bytes[1 + i * 2] = code & 0xff;
89
+ bytes[2 + i * 2] = code >> 8;
90
+ }
91
+ out.length = 1 + key.length * 2;
92
+ return out;
93
+ }
94
+ /** `key` packed, as bytes of its own. */
95
+ export const packKey = (key) => {
96
+ const { bytes, length } = packInto(key, packed());
97
+ return bytes.slice(0, length);
98
+ };
package/dist/text.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { Turn } from "./types.js";
2
+ export declare const isObject: (value: unknown) => value is Record<string, unknown>;
3
+ export declare const str: (value: unknown) => string | undefined;
4
+ export declare const timeOf: (value: unknown) => number | undefined;
5
+ /** Text from a string or a list of blocks; a block that is not text says what it was. */
6
+ export declare const textOf: (value: unknown) => string;
7
+ export declare const effortOf: (value: unknown) => string | undefined;
8
+ export declare const argsOf: (value: unknown) => Record<string, unknown>;
9
+ export declare const INTERRUPTED: RegExp;
10
+ /** The person's own words in a user message's text, as they wrote them (spaces and lines kept, so a cut still matches
11
+ * a secret in them): none when the CLI wrote all of it (a slash command, its output, its preamble), or when there are
12
+ * no words at all. */
13
+ export declare function personsWords(text: string): string | undefined;
14
+ /** The effort most of `turns`' requests ran at, as the model of most requests is a run's model: the first seen of a tie. */
15
+ export declare function mostEffortOf(turns: readonly Turn[]): string | undefined;
package/dist/text.js ADDED
@@ -0,0 +1,60 @@
1
+ export const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
+ export const str = (value) => (typeof value === "string" && value !== "" ? value : undefined);
3
+ export const timeOf = (value) => {
4
+ const at = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
5
+ return Number.isFinite(at) ? at : undefined;
6
+ };
7
+ /** Text from a string or a list of blocks; a block that is not text says what it was. */
8
+ export const textOf = (value) => {
9
+ if (typeof value === "string")
10
+ return value;
11
+ if (!Array.isArray(value))
12
+ return isObject(value) && typeof value.text === "string" ? value.text : "";
13
+ return value
14
+ .map((block) => (typeof block === "string" ? block : isObject(block) ? (typeof block.text === "string" ? block.text : block.type === "image" || block.type === "input_image" ? "[image]" : textOf(block.content)) : ""))
15
+ .filter(Boolean)
16
+ .join("\n");
17
+ };
18
+ export const effortOf = (value) => (typeof value === "string" && /^[\w-]{1,32}$/.test(value) ? value : undefined);
19
+ export const argsOf = (value) => {
20
+ if (isObject(value))
21
+ return value;
22
+ if (typeof value === "string") {
23
+ try {
24
+ const parsed = JSON.parse(value);
25
+ if (isObject(parsed))
26
+ return parsed;
27
+ }
28
+ catch {
29
+ // Not JSON: kept as the tool's one input.
30
+ }
31
+ return { input: value };
32
+ }
33
+ return {};
34
+ };
35
+ export const INTERRUPTED = /^\[Request interrupted by user/;
36
+ // What Claude Code writes into a user message for the person's slash command (/clear, /model, /init, /resume …): the
37
+ // command's name, message and arguments, each in its own element, then its output and the preamble it puts before a
38
+ // local command's output. Only these elements, whole: a prompt the person wrote around them is theirs.
39
+ const CLI_ELEMENT = /<(command-name|command-message|command-args|local-command-stdout|local-command-stderr)>[\s\S]*?<\/\1>/g;
40
+ const CLI_PREAMBLE = /^Caveat: The messages below were generated by the user while running local commands\b/;
41
+ /** The person's own words in a user message's text, as they wrote them (spaces and lines kept, so a cut still matches
42
+ * a secret in them): none when the CLI wrote all of it (a slash command, its output, its preamble), or when there are
43
+ * no words at all. */
44
+ export function personsWords(text) {
45
+ const words = text.replace(CLI_ELEMENT, " ").trim();
46
+ const line = words.replace(/\s+/g, " ");
47
+ return line && !CLI_PREAMBLE.test(line) && !INTERRUPTED.test(line) ? words : undefined;
48
+ }
49
+ /** The effort most of `turns`' requests ran at, as the model of most requests is a run's model: the first seen of a tie. */
50
+ export function mostEffortOf(turns) {
51
+ const efforts = new Map();
52
+ for (const turn of turns)
53
+ if (turn.role === "assistant" && turn.effort)
54
+ efforts.set(turn.effort, (efforts.get(turn.effort) ?? 0) + 1);
55
+ let most;
56
+ for (const [effort, n] of efforts)
57
+ if (most === undefined || n > efforts.get(most))
58
+ most = effort;
59
+ return most;
60
+ }
@@ -0,0 +1,95 @@
1
+ export type ToolCall = {
2
+ type: "toolCall";
3
+ id: string;
4
+ name: string;
5
+ arguments: Record<string, unknown>;
6
+ };
7
+ /** A request's tokens, the same for every source (normalizeUsage): `input` is the input neither read from nor written to
8
+ * the cache; `cacheWrite1h`, the part of `cacheWrite` kept for an hour, which Anthropic prices higher; `reasoning`, the
9
+ * part of `output` the model spent reasoning, where the source says (OpenAI's). */
10
+ export type Usage = {
11
+ input: number;
12
+ output: number;
13
+ cacheRead: number;
14
+ cacheWrite: number;
15
+ cacheWrite1h?: number;
16
+ reasoning?: number;
17
+ };
18
+ /** An assistant turn is one model request: `model` the one it ran on ("provider/model"), `effort` the effort or
19
+ * thinking level it ran at, `usage` its tokens, each absent when the source does not say; `key`, the source's own id of
20
+ * the request (Claude Code's message id with its request id, Codex's response id); `error`, why it failed. A note is a
21
+ * line the harness itself wrote in the conversation: no request, nor the person's. */
22
+ export type Turn = ({
23
+ role: "user";
24
+ text: string;
25
+ at: number;
26
+ } | {
27
+ role: "note";
28
+ author: string;
29
+ text: string;
30
+ at: number;
31
+ } | {
32
+ role: "assistant";
33
+ text: string;
34
+ calls: ToolCall[];
35
+ at: number;
36
+ costUsd?: number;
37
+ key?: string;
38
+ model?: string;
39
+ effort?: string;
40
+ usage?: Usage;
41
+ error?: string;
42
+ } | {
43
+ role: "toolResult";
44
+ callId: string;
45
+ name: string;
46
+ text: string;
47
+ isError: boolean;
48
+ at: number;
49
+ }) & {
50
+ /** The source's own ids of the records the turn was read from (Claude Code's uuids): a later import counts them once. */
51
+ uuids?: string[];
52
+ };
53
+ export type Answer = Extract<Turn, {
54
+ role: "assistant";
55
+ }>;
56
+ export type Ended = "completed" | "failed" | "stopped";
57
+ /** The longest gap between two records counted as time at work, as WakaTime counts it: a longer gap is a session left
58
+ * open and counts nothing. Claude Code's Bash tool runs a call for up to 10 minutes with nothing written. */
59
+ export declare const ACTIVE_GAP_MS: number;
60
+ export type SessionOf<S extends string = string> = {
61
+ source: S;
62
+ /** The source's own id for the session. */
63
+ id: string;
64
+ file: string;
65
+ /** Its id in `file`, where the file holds many sessions (its locator's id): absent for a file of one session. */
66
+ within?: string;
67
+ cwd?: string;
68
+ /** "provider/model", from the session's latest model. */
69
+ model?: string;
70
+ startedAt?: string;
71
+ endedAt?: string;
72
+ state: Ended;
73
+ /** The whole session's cost, when the source records it; absent is unknown. */
74
+ costUsd?: number;
75
+ firstPrompt?: string;
76
+ /** The source's own title for the session, as Claude Code shows it: the person's (/rename's custom-title), else the one
77
+ * it wrote itself (ai-title; summary in older files, the one whose last message this session holds), the latest. */
78
+ sourceTitle?: string;
79
+ /** The first of the person's own words (personsWords): the first user text that is not a CLI's command, its output or
80
+ * its preamble. The run's title when the source wrote none. */
81
+ titleText?: string;
82
+ /** A subagent's or another session's child: not imported as a run; its usage is its parent's. */
83
+ child: boolean;
84
+ /** A child's parent session, when its file names it (Codex's parent thread). */
85
+ parent?: string;
86
+ /** Read only when asked for: a dry run reads none. */
87
+ turns: Turn[];
88
+ users: number;
89
+ /** Time at work: the gaps between its records of at most ACTIVE_GAP_MS each. */
90
+ activeMs: number;
91
+ /** Records it holds that were read already (in an earlier file of the import, or earlier in this one): copies. */
92
+ copies: number;
93
+ /** The effort or thinking level most of its requests ran at, as the source names it; with its turns only. */
94
+ effort?: string;
95
+ };
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ // The one shape every source's sessions are read into.
2
+ /** The longest gap between two records counted as time at work, as WakaTime counts it: a longer gap is a session left
3
+ * open and counts nothing. Claude Code's Bash tool runs a call for up to 10 minutes with nothing written. */
4
+ export const ACTIVE_GAP_MS = 15 * 60_000;
@@ -0,0 +1,16 @@
1
+ import type { Usage } from "./types.js";
2
+ export type UsageFormat = "anthropic" | "openai" | "pi";
3
+ /** A request's usage as `format` writes it, as Usage; undefined unless input and output are counts (an absent cache
4
+ * count is 0) and the input left is not negative. The 1h part of the cache write, or the reasoning part of the output,
5
+ * is kept only when it is a count of at most the whole. */
6
+ export declare function normalizeUsage(format: UsageFormat, raw: unknown): Usage | undefined;
7
+ /** The buckets a total of requests keeps, each a sum; cacheWrite1h is 0 when no request named one. */
8
+ export type Tokens = {
9
+ input: number;
10
+ output: number;
11
+ cacheRead: number;
12
+ cacheWrite: number;
13
+ cacheWrite1h: number;
14
+ };
15
+ export declare const noTokens: () => Tokens;
16
+ export declare function addTokens(into: Tokens, usage: Usage): Tokens;