@parcha/agentrun-import 0.1.0-beta.58 → 0.1.0-beta.60

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.
Files changed (46) hide show
  1. package/README.md +111 -20
  2. package/dist/cli.js +23 -8
  3. package/dist/home.d.ts +24 -1
  4. package/dist/home.js +394 -146
  5. package/dist/index.d.ts +7 -5
  6. package/dist/index.js +4 -2
  7. package/dist/internal.d.ts +18 -0
  8. package/dist/internal.js +12 -0
  9. package/dist/lines.d.ts +24 -1
  10. package/dist/lines.js +135 -25
  11. package/dist/mirror.d.ts +13 -0
  12. package/dist/mirror.js +15 -0
  13. package/dist/pool-worker.d.ts +6 -0
  14. package/dist/pool-worker.js +50 -0
  15. package/dist/pool.d.ts +106 -0
  16. package/dist/pool.js +288 -0
  17. package/dist/price.d.ts +13 -5
  18. package/dist/price.js +31 -21
  19. package/dist/read.d.ts +14 -4
  20. package/dist/read.js +41 -7
  21. package/dist/reader.d.ts +38 -8
  22. package/dist/readers/claude-code.d.ts +24 -0
  23. package/dist/readers/claude-code.js +51 -35
  24. package/dist/readers/codex.d.ts +60 -1
  25. package/dist/readers/codex.js +494 -52
  26. package/dist/readers/copilot.d.ts +4 -0
  27. package/dist/readers/copilot.js +224 -0
  28. package/dist/readers/index.d.ts +2 -0
  29. package/dist/readers/index.js +4 -0
  30. package/dist/readers/line-readers.d.ts +7 -0
  31. package/dist/readers/line-readers.js +10 -0
  32. package/dist/readers/opencode.d.ts +42 -0
  33. package/dist/readers/opencode.js +920 -0
  34. package/dist/readers/pi.js +2 -2
  35. package/dist/record-index.d.ts +32 -1
  36. package/dist/record-index.js +133 -13
  37. package/dist/scan-wasm.d.ts +1 -0
  38. package/dist/scan-wasm.js +2 -0
  39. package/dist/scan.d.ts +21 -0
  40. package/dist/scan.js +164 -0
  41. package/dist/text.d.ts +3 -0
  42. package/dist/text.js +36 -2
  43. package/dist/types.d.ts +20 -3
  44. package/dist/usage.d.ts +6 -2
  45. package/dist/usage.js +42 -1
  46. package/package.json +4 -2
package/dist/index.d.ts CHANGED
@@ -1,12 +1,14 @@
1
- export type { Answer, Ended, ToolCall, Turn, Usage } from "./types.js";
1
+ export type { Answer, Ended, Mirror, ToolCall, Turn, Usage } from "./types.js";
2
2
  export { ACTIVE_GAP_MS } from "./types.js";
3
3
  export { mostEffortOf, personsWords } from "./text.js";
4
- export { addTokens, noTokens, normalizeUsage, type OtelUsage, otelUsage, type Tokens, type UsageFormat } from "./usage.js";
4
+ export { addTokens, noTokens, normalizeUsage, type OtelUsage, otelUsage, type Tokens, type UsageFormat, type UsageOptions } from "./usage.js";
5
5
  export { atOf, type Counts } from "./counts.js";
6
- export { type Env, type Locator, locatorKey, type Reader, type ReadOptions, type ReadResult, type SessionRead } from "./reader.js";
6
+ export { type Env, type Locator, type LocatorSize, locatorKey, type OrderKey, type Reader, type ReadOptions, type ReadResult, type SessionRead } from "./reader.js";
7
7
  export { type FileCursor, type LineSource, lineReader, type ReadContext, type ReadState } from "./lines.js";
8
8
  export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES, type Source } from "./readers/index.js";
9
- export { childrenOf, inOrder, locatorOf, type Readers, readerOf, readSession, type Session, sessionLocators } from "./read.js";
9
+ export { copilotSessionId } from "./readers/copilot.js";
10
+ export { childrenOf, inOrder, locatorOf, locatorParent, locatorSize, type Readers, readerOf, readSession, type Session, sessionLocators } from "./read.js";
10
11
  export { builtinCatalog, type CalculateCost, type Catalog, catalogOf, type Listed, type ModelCost, type Priced, priceRequests } from "./price.js";
11
- export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionRequest, type SessionTotals } from "./home.js";
12
+ export { mirroredIn, ownRequests, sessionKey } from "./mirror.js";
13
+ export { type HomeState, type ParseOptions, parseHome, type ReadFailure, ReadFailures, type SessionRequest, type SessionTotals, withSubagentCosts } from "./home.js";
12
14
  export { type Wrapped, wrappedHome } from "./wrapped.js";
package/dist/index.js CHANGED
@@ -5,7 +5,9 @@ export { atOf } from "./counts.js";
5
5
  export { locatorKey } from "./reader.js";
6
6
  export { lineReader } from "./lines.js";
7
7
  export { HARNESS_OF, READERS, SOURCE_NAMES, SOURCES } from "./readers/index.js";
8
- export { childrenOf, inOrder, locatorOf, readerOf, readSession, sessionLocators } from "./read.js";
8
+ export { copilotSessionId } from "./readers/copilot.js";
9
+ export { childrenOf, inOrder, locatorOf, locatorParent, locatorSize, readerOf, readSession, sessionLocators } from "./read.js";
9
10
  export { builtinCatalog, catalogOf, priceRequests } from "./price.js";
10
- export { parseHome, ReadFailures } from "./home.js";
11
+ export { mirroredIn, ownRequests, sessionKey } from "./mirror.js";
12
+ export { parseHome, ReadFailures, withSubagentCosts } from "./home.js";
11
13
  export { wrappedHome } from "./wrapped.js";
@@ -0,0 +1,18 @@
1
+ import type { ReadOptions } from "./reader.js";
2
+ /** A read option keyed by a symbol, so no ReadOptions a caller writes can name it: true when the caller drops the read's
3
+ * cursor unread (parseHome with no state, the read pool's workers, readSession). The read then makes no copy for that
4
+ * cursor: its state is the read's own. A totals read's cursor holds the read's own counts, not a copy trimmed to its
5
+ * requests (the copy is the size of the counts), and its session and source state keep what a kept cursor forgets. A
6
+ * file whose last line has no newline yet is read with no copy of its whole state to leave that line out, so the
7
+ * cursor's state then holds the line its offset is before: hand such a cursor to no read. */
8
+ export declare const DROPS_CURSOR: unique symbol;
9
+ /** A read option keyed by a symbol, as DROPS_CURSOR is: true reads a file's next chunk only after this one's lines are
10
+ * read, into one buffer. Unset, the next chunk is read while this one's lines are, which pays where a core is spare to
11
+ * make the read (parseHome's own thread). The read pool's workers set it: their threads take every core they are given,
12
+ * so a read made ahead waits for one, and its chunk lands on another core than the one that reads it. */
13
+ export declare const NO_READ_AHEAD: unique symbol;
14
+ /** ReadOptions with this package's own options. */
15
+ export type InternalReadOptions = ReadOptions & {
16
+ [DROPS_CURSOR]?: boolean;
17
+ [NO_READ_AHEAD]?: boolean;
18
+ };
@@ -0,0 +1,12 @@
1
+ /** A read option keyed by a symbol, so no ReadOptions a caller writes can name it: true when the caller drops the read's
2
+ * cursor unread (parseHome with no state, the read pool's workers, readSession). The read then makes no copy for that
3
+ * cursor: its state is the read's own. A totals read's cursor holds the read's own counts, not a copy trimmed to its
4
+ * requests (the copy is the size of the counts), and its session and source state keep what a kept cursor forgets. A
5
+ * file whose last line has no newline yet is read with no copy of its whole state to leave that line out, so the
6
+ * cursor's state then holds the line its offset is before: hand such a cursor to no read. */
7
+ export const DROPS_CURSOR = Symbol("dropsCursor");
8
+ /** A read option keyed by a symbol, as DROPS_CURSOR is: true reads a file's next chunk only after this one's lines are
9
+ * read, into one buffer. Unset, the next chunk is read while this one's lines are, which pays where a core is spare to
10
+ * make the read (parseHome's own thread). The read pool's workers set it: their threads take every core they are given,
11
+ * so a read made ahead waits for one, and its chunk lands on another core than the one that reads it. */
12
+ export const NO_READ_AHEAD = Symbol("noReadAhead");
package/dist/lines.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type Counts } from "./counts.js";
2
- import { type Env, type Reader } from "./reader.js";
2
+ import { type Env, type Reader, type ReadOptions } from "./reader.js";
3
+ import { type Shape } from "./scan.js";
3
4
  import { type Answer, type SessionOf, type Turn } from "./types.js";
4
5
  /** One file's read so far, all of it plain data (no function, Maps and Sets allowed), so a cursor can carry it and
5
6
  * structuredClone or v8.serialize can copy it. `answers` holds every request read, whether turns are kept or not: what
@@ -60,7 +61,24 @@ export type LineSource<S extends string, O> = Pick<Reader<S>, "source" | "name"
60
61
  * added: the source sets no turn's model, usage or time after adding it, or keeps its requests in `counts` itself. Without it a totals
61
62
  * read is a turns: false read, its requests whole. */
62
63
  totals?: true;
64
+ /** What `record` reads of a record in a totals read: a line is then read for these fields alone, from its bytes (scan),
65
+ * every other value checked as JSON but not decoded, and parsed whole only when the scan leaves it to JSON.parse. It
66
+ * names every field whose value can change what a totals read gives (a field whose value goes only into a turn or
67
+ * text a totals read drops may be left out); the read itself takes the record's `timestamp`. Without it, or in any
68
+ * other read, each line is parsed whole. */
69
+ fields?: Shape;
70
+ /** The shape of the state (`own`) its cursors hold, set when it changes from one a release saved: a cursor saved at
71
+ * another (none for a source that never set one) is no place to go on from, and the file is read from its start. */
72
+ stateVersion?: number;
63
73
  };
74
+ /** A line longer than the read's maxLine (ReadOptions): the read ends before decoding it. */
75
+ export declare class LineTooLong extends Error {
76
+ readonly file: string;
77
+ readonly offset: number;
78
+ readonly bytes: number;
79
+ readonly maxLine: number;
80
+ constructor(file: string, offset: number, bytes: number, maxLine: number);
81
+ }
64
82
  /** Where a read of a file stopped, and what it had read. Plain data (Maps, Sets and shared objects, no function):
65
83
  * structuredClone or v8.serialize keeps it whole. Read it through its reader alone. A turns: true read's cursor
66
84
  * holds the session's text, as its state does (ReadState); keep or send it as you would the session. */
@@ -76,7 +94,12 @@ export type FileCursor = {
76
94
  /** Whether the read kept turns, and whether it was a totals read: a cursor of another kind is no place to go on from. */
77
95
  keep: boolean;
78
96
  totals?: boolean;
97
+ /** Its reader's state shape when saved (LineSource.stateVersion). */
98
+ stateVersion?: number;
79
99
  state: ReadState;
80
100
  };
101
+ /** Whether `spec`'s line reader would go on from `cursor` in `file` now (a read with `options`), as it decides when it
102
+ * reads: so a reader built on it can choose how to read before reading. A file it cannot open is no place to go on. */
103
+ export declare function resumes<S extends string, O>(spec: LineSource<S, O>, file: string, cursor: FileCursor | undefined, { turns: keep, totals: asked }?: ReadOptions): Promise<boolean>;
81
104
  /** The Reader of a JSONL source: each file one locator, its cursor a FileCursor. */
82
105
  export declare function lineReader<S extends string, O>(spec: LineSource<S, O>): Reader<S, FileCursor>;
package/dist/lines.js CHANGED
@@ -2,12 +2,30 @@
2
2
  // into a Session, a line that is not JSON, or not a record its source knows, passed over. A read goes on from a cursor:
3
3
  // the file's identity (device, inode), the byte after the last whole line read, and the read's state, so a later read
4
4
  // takes only the bytes written since.
5
- import { createReadStream } from "node:fs";
6
5
  import { open } from "node:fs/promises";
7
6
  import { addRequest, counts, trimmed } from "./counts.js";
7
+ import { DROPS_CURSOR, NO_READ_AHEAD } from "./internal.js";
8
8
  import { rememberUser } from "./reader.js";
9
+ import { fieldsOf, scan } from "./scan.js";
9
10
  import { isObject, mostEffortOf, timeOf } from "./text.js";
10
11
  import { ACTIVE_GAP_MS } from "./types.js";
12
+ /** The bytes a read takes from its file at once. */
13
+ const CHUNK = 1 << 20;
14
+ /** A line longer than the read's maxLine (ReadOptions): the read ends before decoding it. */
15
+ export class LineTooLong extends Error {
16
+ file;
17
+ offset;
18
+ bytes;
19
+ maxLine;
20
+ constructor(file, offset, bytes, maxLine) {
21
+ super(`${file}: a line at byte ${offset} is longer than ${maxLine} bytes (${bytes} so far)`);
22
+ this.file = file;
23
+ this.offset = offset;
24
+ this.bytes = bytes;
25
+ this.maxLine = maxLine;
26
+ this.name = "LineTooLong";
27
+ }
28
+ }
11
29
  /** What a listing reads from the session's text: a turns: false cursor keeps none of it, and a read resumed from one
12
30
  * gives none (it would describe only what was written since). */
13
31
  const withoutText = (session) => {
@@ -23,19 +41,50 @@ async function markOf(handle, offset) {
23
41
  const { bytesRead } = await handle.read(bytes, 0, n, offset - n);
24
42
  return bytes.subarray(0, bytesRead).toString("base64");
25
43
  }
44
+ /** A read started ahead of its turn: a failure the read never gets to (a line too long ends it first) is not unhandled;
45
+ * awaited, it still throws. */
46
+ const ahead = (read) => {
47
+ read.catch(() => { });
48
+ return read;
49
+ };
50
+ /** Whether a read from `cursor` of the open file goes on from it: the same source, kind of read and state shape
51
+ * (LineSource.stateVersion), the same file (device and inode), no shorter, and the bytes before its offset as they
52
+ * were. Else it reads the file from its start. */
53
+ async function goesOn(spec, keep, totals, cursor, handle, stats) {
54
+ return cursor.source === spec.source && cursor.keep === keep && (cursor.totals ?? false) === totals && cursor.stateVersion === spec.stateVersion && cursor.dev === stats.dev && cursor.ino === stats.ino && stats.size >= cursor.offset && (await markOf(handle, cursor.offset)) === cursor.mark;
55
+ }
56
+ /** Whether a read with these options is a totals read: asked for, with no turns kept, from a source that has one. */
57
+ const totalsRead = (spec, keep, asked) => asked && !keep && spec.totals === true;
58
+ /** Whether `spec`'s line reader would go on from `cursor` in `file` now (a read with `options`), as it decides when it
59
+ * reads: so a reader built on it can choose how to read before reading. A file it cannot open is no place to go on. */
60
+ export async function resumes(spec, file, cursor, { turns: keep = true, totals: asked = false } = {}) {
61
+ if (cursor === undefined)
62
+ return false;
63
+ const handle = await open(file, "r").catch(() => undefined);
64
+ if (!handle)
65
+ return false;
66
+ try {
67
+ return await goesOn(spec, keep, totalsRead(spec, keep, asked), cursor, handle, await handle.stat());
68
+ }
69
+ finally {
70
+ await handle.close();
71
+ }
72
+ }
26
73
  /** The records seen, as a source asks: `extra` over `base`, so a line read that is not kept leaves `base` as it was. */
27
74
  const overlay = (base) => {
28
75
  const extra = new Set();
29
76
  return { has: (key) => extra.has(key) || base.has(key), add: (key) => extra.add(key) };
30
77
  };
31
78
  /** One session file of `spec`'s source, read from its start or from `cursor`. */
32
- async function readLines(spec, file, cursor, { turns: keep = true, totals: asked = false, seen, keepsCursor = true } = {}) {
79
+ async function readLines(spec, shape, file, cursor, { turns: keep = true, totals: asked = false, seen, keepsCursor = true, [DROPS_CURSOR]: dropsCursor = false, [NO_READ_AHEAD]: inTurn = false, maxLine = Infinity } = {}) {
33
80
  const { source } = spec;
34
- const totals = asked && !keep && spec.totals === true;
81
+ const totals = totalsRead(spec, keep, asked);
82
+ const fields = totals ? shape : undefined;
35
83
  const handle = await open(file, "r");
36
84
  try {
37
85
  const stats = await handle.stat();
38
- const resumed = cursor !== undefined && cursor.source === source && cursor.keep === keep && (cursor.totals ?? false) === totals && cursor.dev === stats.dev && cursor.ino === stats.ino && stats.size >= cursor.offset && (await markOf(handle, cursor.offset)) === cursor.mark;
86
+ // The cursor's presence checked here, so `resumed` narrows it where its state and offset are read.
87
+ const resumed = cursor !== undefined && (await goesOn(spec, keep, totals, cursor, handle, stats));
39
88
  const state = (resumed
40
89
  ? structuredClone(cursor.state)
41
90
  : { session: { source, id: "", file, state: "completed", child: false, turns: [], users: 0, activeMs: 0, copies: 0 }, turns: [], answers: [], names: new Map(), priced: { sum: 0, unknown: false }, activeMs: 0, own: spec.start(), ...(totals ? { counts: counts() } : {}), ...(seen ? {} : { seen: new Set() }) });
@@ -55,14 +104,7 @@ async function readLines(spec, file, cursor, { turns: keep = true, totals: asked
55
104
  state.answers.push(turn);
56
105
  },
57
106
  };
58
- const line = (text) => {
59
- let value;
60
- try {
61
- value = JSON.parse(text);
62
- }
63
- catch {
64
- return;
65
- }
107
+ const line = (value) => {
66
108
  if (!isObject(value))
67
109
  return;
68
110
  const at = timeOf(value.timestamp);
@@ -80,44 +122,100 @@ async function readLines(spec, file, cursor, { turns: keep = true, totals: asked
80
122
  }
81
123
  }
82
124
  };
125
+ // A line's bytes b[from, to): its fields alone where the source names them and the scan is sure of the line, else
126
+ // the line decoded and parsed whole; a line that is not JSON is passed over.
127
+ const take = (b, from, to) => {
128
+ let value = fields ? scan(b, from, to, fields) : undefined;
129
+ if (value === undefined) {
130
+ const text = b.toString("utf8", from, to);
131
+ try {
132
+ value = JSON.parse(text);
133
+ }
134
+ catch {
135
+ return;
136
+ }
137
+ }
138
+ line(value);
139
+ };
83
140
  const start = resumed ? cursor.offset : 0;
84
141
  let offset = start;
85
142
  let read = 0;
86
143
  let rest = [];
144
+ let restBytes = 0;
145
+ const tooLong = (bytes) => {
146
+ if (bytes > maxLine)
147
+ throw new LineTooLong(file, offset, bytes, maxLine);
148
+ };
87
149
  if (stats.size > start) {
88
- // The open handle's descriptor, so the bytes streamed are the file stat described, whatever the path names now.
89
- for await (const chunk of createReadStream(file, { fd: handle.fd, start, autoClose: false, highWaterMark: 1 << 20 })) {
150
+ // The open handle, so the bytes read are the file stat described, whatever the path names now. The buffers last the
151
+ // whole read (a new buffer a chunk leaves freed native memory behind on every thread that reads, the read pool's):
152
+ // two taken in turn, the next chunk read into one while this one's lines are read; read in turn (NO_READ_AHEAD),
153
+ // one, the next chunk read into it once its lines are.
154
+ const buffers = inTurn ? [Buffer.allocUnsafeSlow(CHUNK)] : [Buffer.allocUnsafeSlow(CHUNK), Buffer.allocUnsafeSlow(CHUNK)];
155
+ let which = 0;
156
+ let next = ahead(handle.read(buffers[0], 0, CHUNK, start));
157
+ for (let at = start;;) {
158
+ const { bytesRead } = await next;
159
+ if (!bytesRead)
160
+ break;
161
+ const buffer = buffers[which];
162
+ at += bytesRead;
163
+ which = (which + 1) % buffers.length;
164
+ if (!inTurn)
165
+ next = ahead(handle.read(buffers[which], 0, CHUNK, at));
166
+ const chunk = buffer.subarray(0, bytesRead);
90
167
  read += chunk.length;
91
168
  let from = 0;
92
169
  for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, from)) {
93
- const whole = rest.length ? Buffer.concat([...rest, chunk.subarray(from, nl)]) : chunk.subarray(from, nl);
94
- rest = [];
95
- line(whole.toString("utf8", 0, whole.length && whole[whole.length - 1] === 13 ? whole.length - 1 : whole.length));
96
- offset += whole.length + 1;
170
+ tooLong(restBytes + nl - from);
171
+ // The line in the chunk where it starts there, else its start's copies and the chunk's part as one.
172
+ let b = chunk;
173
+ let s = from;
174
+ let n = nl;
175
+ if (rest.length) {
176
+ b = Buffer.concat([...rest, chunk.subarray(from, nl)]);
177
+ s = 0;
178
+ n = b.length;
179
+ rest = [];
180
+ restBytes = 0;
181
+ }
182
+ take(b, s, n > s && b[n - 1] === 13 ? n - 1 : n);
183
+ offset += n - s + 1;
97
184
  from = nl + 1;
98
185
  }
99
- if (from < chunk.length)
100
- rest.push(chunk.subarray(from));
186
+ // The buffer is read into again: a line's start is kept as a copy.
187
+ if (from < chunk.length) {
188
+ restBytes += chunk.length - from;
189
+ tooLong(restBytes);
190
+ rest.push(Buffer.from(chunk.subarray(from)));
191
+ }
192
+ if (inTurn)
193
+ next = handle.read(buffer, 0, CHUNK, at);
101
194
  }
102
195
  }
103
196
  // A last line with no newline yet may be a record still being written: read into this result when it is whole JSON,
104
197
  // but the cursor stays before it, its state without it. A caller that keeps the cursor reads the line again from it,
105
198
  // so its `seen` is left untouched by it; one that keeps none (readSession) has it in `seen` like any other line.
199
+ // A caller that drops the cursor (DROPS_CURSOR) gets one on the read's own state, that line in it: no copy of the
200
+ // whole state (the file's request index and counts with it) is made to leave the line out.
106
201
  let kept = state;
107
202
  if (rest.length) {
108
- kept = structuredClone(state);
203
+ if (!dropsCursor)
204
+ kept = structuredClone(state);
109
205
  if (keepsCursor)
110
206
  context.seen = overlay(context.seen);
111
- line(Buffer.concat(rest).toString("utf8"));
207
+ const last = Buffer.concat(rest);
208
+ take(last, 0, last.length);
112
209
  }
113
210
  const mark = await markOf(handle, offset);
114
211
  let session = finish(spec, file, state, context);
115
212
  if (!keep) {
116
- kept = { ...kept, session: withoutText(kept.session), own: spec.forget ? spec.forget(kept.own) : kept.own, ...(kept.counts ? { counts: trimmed(kept.counts) } : {}) };
213
+ if (!dropsCursor)
214
+ kept = { ...kept, session: withoutText(kept.session), own: spec.forget ? spec.forget(kept.own) : kept.own, ...(kept.counts ? { counts: trimmed(kept.counts) } : {}) };
117
215
  if (resumed)
118
216
  session = withoutText(session);
119
217
  }
120
- return { sessions: [{ locator: { file }, session, requests: state.answers, ...(state.counts ? { counts: state.counts } : {}) }], cursor: { source, dev: stats.dev, ino: stats.ino, offset, mark, keep, ...(totals ? { totals } : {}), state: kept }, read, resumed };
218
+ return { sessions: [{ locator: { file }, session, requests: state.answers, ...(state.counts ? { counts: state.counts } : {}) }], cursor: { source, dev: stats.dev, ino: stats.ino, offset, mark, keep, ...(totals ? { totals } : {}), ...(spec.stateVersion !== undefined ? { stateVersion: spec.stateVersion } : {}), state: kept }, read, resumed };
121
219
  }
122
220
  finally {
123
221
  await handle.close();
@@ -140,16 +238,28 @@ function finish(spec, file, state, context) {
140
238
  out.effort = effort;
141
239
  return out;
142
240
  }
241
+ /** Each source's fields as scan takes them, made once per Shape: a reader built again over the same fields (a Codex
242
+ * fork's, whose spec differs only in its start) reads with the node they were compiled to, since the walk's table, which
243
+ * holds every compiled node, only grows. */
244
+ const compiled = new WeakMap();
245
+ function fieldsFor(shape) {
246
+ let fields = compiled.get(shape);
247
+ if (!fields)
248
+ compiled.set(shape, (fields = fieldsOf({ ...shape, timestamp: true })));
249
+ return fields;
250
+ }
143
251
  /** The Reader of a JSONL source: each file one locator, its cursor a FileCursor. */
144
252
  export function lineReader(spec) {
145
253
  const { source, name, harness, order, children } = spec;
254
+ const fields = spec.fields ? fieldsFor(spec.fields) : undefined;
146
255
  return {
147
256
  source,
148
257
  name,
149
258
  harness,
150
259
  ...(order ? { order } : {}),
151
260
  discover: async (home, env) => (await spec.files(home, env)).map((file) => ({ file })),
152
- read: (locator, cursor, options) => readLines(spec, locator.file, cursor, options),
261
+ idOf: ({ file }) => spec.idOf(file),
262
+ read: (locator, cursor, options) => readLines(spec, fields, locator.file, cursor, options),
153
263
  ...(children ? { children: async (home, env) => (await children(home, env)).map(({ file, of }) => ({ locator: { file }, of: { file: of } })) } : {}),
154
264
  };
155
265
  }
@@ -0,0 +1,13 @@
1
+ import type { Answer } from "./types.js";
2
+ /** A session as the rule names it: its source and its id. */
3
+ export declare const sessionKey: (source: string, id: string) => string;
4
+ /** The rule over the sessions counted (each a sessionKey): whether a request is one of theirs, so not its own session's.
5
+ * `kept` maps a session id as the request names it to the id the counted set holds it by, where the two differ (serve
6
+ * keeps an id that holds a key as a hash of it). */
7
+ export declare const mirroredIn: (counted: ReadonlySet<string>, kept?: ReadonlyMap<string, string>) => ({ mirrors }: Pick<Answer, "mirrors">) => boolean;
8
+ /** A session's own requests, those `mirrored` takes left out, and its cost of them: the cost it wrote when it holds none
9
+ * of another's, else its own requests' summed, unknown when one that used tokens is not priced. */
10
+ export declare function ownRequests<A extends Answer>(requests: readonly A[], cost: number | undefined, mirrored: (request: A) => boolean): {
11
+ requests: A[];
12
+ cost: number | undefined;
13
+ };
package/dist/mirror.js ADDED
@@ -0,0 +1,15 @@
1
+ /** A session as the rule names it: its source and its id. */
2
+ export const sessionKey = (source, id) => `${source}:${id}`;
3
+ /** The rule over the sessions counted (each a sessionKey): whether a request is one of theirs, so not its own session's.
4
+ * `kept` maps a session id as the request names it to the id the counted set holds it by, where the two differ (serve
5
+ * keeps an id that holds a key as a hash of it). */
6
+ export const mirroredIn = (counted, kept) => ({ mirrors }) => mirrors !== undefined && counted.has(sessionKey(mirrors.source, kept?.get(mirrors.sessionId) ?? mirrors.sessionId));
7
+ /** A session's own requests, those `mirrored` takes left out, and its cost of them: the cost it wrote when it holds none
8
+ * of another's, else its own requests' summed, unknown when one that used tokens is not priced. */
9
+ export function ownRequests(requests, cost, mirrored) {
10
+ const own = requests.filter((request) => !mirrored(request));
11
+ if (own.length === requests.length)
12
+ return { requests: own, cost };
13
+ const priced = own.every((request) => request.costUsd !== undefined || !request.usage);
14
+ return { requests: own, cost: priced ? own.reduce((n, request) => n + (request.costUsd ?? 0), 0) : undefined };
15
+ }
@@ -0,0 +1,6 @@
1
+ import type { Locator } from "./reader.js";
2
+ export type PoolAsk = {
3
+ id: number;
4
+ source: string;
5
+ locator: Locator;
6
+ };
@@ -0,0 +1,50 @@
1
+ // A read pool's worker (pool.ts): reads one locator of a line source (LINE_READERS) as parseHome's totals read does,
2
+ // through a `seen` of the locator's own records alone, and hands back its sessions, the records it added (mine) and the
3
+ // records it asked for, did not hold and never added (missed). parseHome takes the read as its own when no record of
4
+ // either is one an earlier locator holds: its `seen` would then have answered every question alike (a record asked for
5
+ // and then added is in mine), so the read is the one it would have made.
6
+ import { parentPort, workerData } from "node:worker_threads";
7
+ import { packed, packInto } from "./record-key.js";
8
+ import { addRecord, indexArrays, notIn, ownerOf, recordIndex } from "./record-index.js";
9
+ import { DROPS_CURSOR, NO_READ_AHEAD } from "./internal.js";
10
+ import { LINE_READERS } from "./readers/line-readers.js";
11
+ /** The longest line this worker decodes (pool.ts sets it from the heap cap): a file with a longer one is handed back. */
12
+ const { maxLine } = workerData;
13
+ /** What readers look up once, shared by this worker's reads (ReadOptions.lookups): a pool lives for one parseHome, so
14
+ * this is one import's, and each worker looks up at most once what the import's own thread looks up once. */
15
+ const lookups = new Map();
16
+ /** The index's arrays, moved with the reply rather than copied (its tags too: a copy is made on this thread and again on
17
+ * parseHome's, which every read passes through). */
18
+ const buffers = (index) => indexArrays(index).map((a) => a.buffer);
19
+ parentPort.on("message", async ({ id, source, locator }) => {
20
+ const reader = LINE_READERS[source];
21
+ const mine = recordIndex(64);
22
+ // Every record asked for while mine did not hold it; the ones added after are taken out once the read ends.
23
+ const asked = recordIndex(64);
24
+ const at = packed();
25
+ const seen = {
26
+ has: (record) => {
27
+ if (ownerOf(mine, packInto(record, at)) !== -1)
28
+ return true;
29
+ addRecord(asked, at, 0);
30
+ return false;
31
+ },
32
+ add(record) {
33
+ addRecord(mine, packInto(record, at), 0);
34
+ return this;
35
+ },
36
+ };
37
+ try {
38
+ // The cursor is never sent back: the read makes no copy for it. No read ahead (NO_READ_AHEAD): the pool's workers take
39
+ // every core it was given.
40
+ const options = { turns: false, totals: true, seen, maxLine, lookups, [DROPS_CURSOR]: true, [NO_READ_AHEAD]: true };
41
+ const result = await reader.read(locator, undefined, options);
42
+ const missed = notIn(asked, mine);
43
+ const counts = result.sessions.flatMap(({ counts }) => (counts ? [counts.model.buffer, counts.values.buffer, counts.has.buffer] : []));
44
+ parentPort.postMessage({ id, ok: true, sessions: result.sessions, mine, missed }, [...new Set([...buffers(mine), ...buffers(missed), ...counts])]);
45
+ }
46
+ catch {
47
+ // The read is made again in order by parseHome, which records its failure as its own.
48
+ parentPort.postMessage({ id, ok: false });
49
+ }
50
+ });
package/dist/pool.d.ts ADDED
@@ -0,0 +1,106 @@
1
+ import type { Locator, SessionRead } from "./reader.js";
2
+ import { type RecordIndex } from "./record-index.js";
3
+ /** A read the pool made: its sessions, the records it added, those it asked for and did not hold. Not ok: make it again. */
4
+ export type PoolRead = {
5
+ ok: true;
6
+ sessions: SessionRead[];
7
+ mine: RecordIndex;
8
+ missed: RecordIndex;
9
+ } | {
10
+ ok: false;
11
+ };
12
+ /** Each worker's old generation. Unbounded, each grows to several times what it holds (eight workers: 0.5 GiB of heap
13
+ * for 0.12 GiB in use, on a 24 GB home). A worker past it ends; its file is read by parseHome. */
14
+ export declare const OLD_MB = 64;
15
+ /** The smallest old generation a worker may be given (parseHome's workerOldMb). On node 24.22.3, one pool worker started
16
+ * at N MB to read a synthetic home of four files (one of 1.2 MB), each N in a process of its own: at 1 and 2 MB V8 ends
17
+ * the whole process as the worker starts ("Fatal JavaScript out of memory: GC during deserialization"); from 3 to 6 MB
18
+ * no worker read a file (5 processes each, 29 at 6); at 7, 28 of 29 processes lost a worker; at 8 to 10 (29 processes
19
+ * each) and at 11 and 12 (5 each), every worker read every file. A worker under it can only end the process or lose
20
+ * every read, so it is refused. */
21
+ export declare const MIN_OLD_MB = 8;
22
+ /** A file this large or larger is read ahead of the import's order, the largest first: such files set the time. */
23
+ export declare const BIG_FILE: number;
24
+ /** The most bytes of finished reads that may wait to be taken by default; at the read-ahead, the pool reads only the one
25
+ * parseHome waits for. A cap on finished reads waiting, plus at most one read in flight per thread; not on the process's
26
+ * memory. */
27
+ export declare const READ_AHEAD_BYTES: number;
28
+ /** The memory this process may use: its container's limit (process.constrainedMemory) when one is set below the
29
+ * machine's, else the machine's. A 2 GiB container on a 512 GiB host has 2 GiB. */
30
+ export declare const memoryLimit: (total?: number, constrained?: number) => number;
31
+ /** The default read-ahead: READ_AHEAD_BYTES, or a sixteenth of the memory this process may use when that is less (512 MiB
32
+ * at 8 GiB, 128 MiB in a 2 GiB container). */
33
+ export declare const readAheadBytes: (memory?: number) => number;
34
+ /** The default threads' ceiling. On a 48-core machine, a 23 GB home (pooled, median of 2) took 27.5 s at 8 threads
35
+ * (peak 1.13 GiB), 20.3 s at 16 (1.77 GiB), 17.2 s at 24 (2.39 GiB) and 23.3 s at 32 (2.87 GiB): 16 takes most of 24's
36
+ * gain for three quarters of its memory, and past 24 the threads slow each other down. */
37
+ export declare const DEFAULT_THREADS_CEILING = 16;
38
+ /** The most a worker's heap holds: its young generation (YOUNG_MB) and its old one (`oldMb`), both capped at its start.
39
+ * The pool's peak grew by about this, 80 MiB a worker at the default, from 8 threads to 24 (the runs DEFAULT_THREADS_CEILING cites). */
40
+ export declare const workerBytes: (oldMb?: number) => number;
41
+ /** The memory still free to this process: the machine's (os.freemem, MemAvailable on Linux: page cache it may reclaim
42
+ * counts as free), at most its container's limit (memoryLimit). Not process.availableMemory: under a cgroup it takes the
43
+ * limit less memory.current, which counts the page cache as used. On a 503 GiB machine with 345 GiB free, in a cgroup
44
+ * of 350 GiB whose 346 GiB in use were 250 GiB of page cache, it read 130 MiB to 3.6 GiB from one second to the next. */
45
+ export declare const freeMemory: (free?: number, limit?: number) => number;
46
+ /** parseHome's default threads: the fewest of
47
+ * - the cores this process may run on, one left for the thread that takes the reads and totals them (two cores keep
48
+ * two threads: one worker would read no faster than the calling thread alone);
49
+ * - DEFAULT_THREADS_CEILING;
50
+ * - the workers whose heaps (workerBytes) fit in the memory still free (freeMemory) once the read-ahead (`aheadBytes`)
51
+ * is set aside, since the reads waiting are held on the calling thread;
52
+ * and at least 1 (every file read on the calling thread). A caller's `threads` is taken as given, up to MOST_THREADS. */
53
+ export declare const defaultThreads: (cores?: number, available?: number, aheadBytes?: number, oldMb?: number) => number;
54
+ /** A read's strings as V8 holds them (a session's first prompt and title can run to megabytes), wherever they are in its
55
+ * objects and arrays (a session's turns, a read's requests and paths): each object once, on a stack of its own, so no
56
+ * depth runs the call stack out and a cycle ends. A typed array holds none: heldBytes counts its bytes apart. */
57
+ export declare function stringBytes(read: object): number;
58
+ export declare class ReadPool {
59
+ private readonly threads;
60
+ private readonly aheadBytes;
61
+ private readonly oldMb;
62
+ private readonly live;
63
+ private readonly idle;
64
+ private readonly running;
65
+ private readonly jobs;
66
+ /** Queued jobs, the largest first (the import's order among equals). */
67
+ private bySize;
68
+ /** The job parseHome waits for (or last took): no job before it is read for it. */
69
+ private cursor;
70
+ /** The first job, in the import's order, that may still be queued. */
71
+ private nextInOrder;
72
+ /** The job parseHome waits for, and how it is handed over. */
73
+ private wanted;
74
+ private waiting;
75
+ private losses;
76
+ private broken;
77
+ /** The most bytes of reads waiting at once, read by the lane's measuring script alone. The read-ahead is checked before
78
+ * a read is sent, so the reads in flight then (at most `threads`) may land past it. */
79
+ peakWaiting: number;
80
+ constructor(threads: number, aheadBytes?: number, oldMb?: number);
81
+ /** Queues each locator; a job's id is its place in the import's order, so `items` come in that order. The ids, for take. */
82
+ readAll(items: readonly {
83
+ source: string;
84
+ locator: Locator;
85
+ size: number;
86
+ }[]): number[];
87
+ /** The read of job `id`, made next when it is not made yet. Each id is taken once; a second take, or a pool that broke,
88
+ * gives a read that is not ok (parseHome makes it itself). */
89
+ take(id: number): Promise<PoolRead>;
90
+ /** Gives up jobs parseHome will not take (a source it reads again whole): their reads waiting are let go, those queued
91
+ * are not read, those running are let go when they end. */
92
+ drop(ids: readonly number[]): void;
93
+ close(): void;
94
+ private spawn;
95
+ /** The next job to read: the one parseHome waits for; else, while the reads waiting are under the budget, the largest
96
+ * file left if it is large, or the first queued past the cursor. */
97
+ private pick;
98
+ private dispatch;
99
+ /** A job's read is made: handed to parseHome if it waits for it, else held until it takes it. */
100
+ private made;
101
+ private finished;
102
+ /** A worker ended (out of memory, or crashed): its file is parseHome's to read, and another worker takes its place. */
103
+ private gone;
104
+ /** The pool stops: no read is taken from it any more; parseHome makes each one itself. */
105
+ private fail;
106
+ }