@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.
@@ -0,0 +1,242 @@
1
+ // Codex: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl. A subagent's thread names its parent in its session_meta.
2
+ import { basename, join } from "node:path";
3
+ import { lineReader } from "../lines.js";
4
+ import { entries, rememberUser } from "../reader.js";
5
+ import { argsOf, effortOf, isObject, str, textOf } from "../text.js";
6
+ import { normalizeUsage } from "../usage.js";
7
+ // The blocks the Codex CLI adds to a user message, each one of its own elements whole, an AGENTS.md as a heading over its
8
+ // <INSTRUCTIONS>; and the bare tags around an image. Only these: a prompt the person wrote as a tagged element is theirs,
9
+ // and a block the CLI adds later reads as text until it is named here.
10
+ const CODEX_BLOCK = /^\s*(?:#[^\n]*\n\s*)?<([A-Za-z_]+)(?:\s[^>]*)?>[\s\S]*<\/\1>\s*$/;
11
+ const CODEX_BLOCKS = new Set(["environment_context", "user_instructions", "INSTRUCTIONS", "turn_aborted", "subagent_notification", "skill", "user_shell_command", "user_action", "recommended_plugins", "codex_internal_context"]);
12
+ const IMAGE_TAG = /^\s*<\/?image\b[^>]*>\s*$/;
13
+ const typed = (text) => !CODEX_BLOCKS.has(CODEX_BLOCK.exec(text)?.[1] ?? "") && !IMAGE_TAG.test(text);
14
+ /** The person's words in a Codex user message: "" when the CLI wrote all of it. */
15
+ const wordsOf = (content) => textOf(Array.isArray(content) ? content.filter((block) => !isObject(block) || typeof block.text !== "string" || typed(block.text)) : content);
16
+ // The response items of the model's own output: each of one request, until its usage comes.
17
+ const CODEX_OUTPUTS = new Set(["reasoning", "function_call", "custom_tool_call", "web_search_call", "tool_search_call"]);
18
+ const CODEX_HEAD = /^(?:Command|Chunk ID|Exit code): /;
19
+ const CODEX_EXIT = /^(?:Exit code: |Process exited with code )(-?\d+)$/;
20
+ /** Whether a Codex tool call failed, as its output says, else undefined: a structured output's success flag or
21
+ * metadata.exit_code, the exit code in a shell call's head (the lines before "Output:"), or how a script ended. */
22
+ function codexFailed(output) {
23
+ if (isObject(output) && typeof output.success === "boolean")
24
+ return !output.success;
25
+ const text = textOf(isObject(output) && "content" in output ? output.content : output);
26
+ if (text.startsWith("{")) {
27
+ try {
28
+ const parsed = JSON.parse(text);
29
+ if (isObject(parsed) && isObject(parsed.metadata) && typeof parsed.metadata.exit_code === "number")
30
+ return parsed.metadata.exit_code !== 0;
31
+ }
32
+ catch {
33
+ // Not JSON: read as text.
34
+ }
35
+ }
36
+ const lines = text.split("\n", 64);
37
+ if (/^Script failed\b/.test(lines[0]))
38
+ return true;
39
+ if (/^Script completed\b/.test(lines[0]))
40
+ return false;
41
+ if (!CODEX_HEAD.test(lines[0]))
42
+ return undefined;
43
+ for (const line of lines) {
44
+ if (line === "Output:")
45
+ break;
46
+ const code = CODEX_EXIT.exec(line)?.[1];
47
+ if (code !== undefined)
48
+ return code !== "0";
49
+ }
50
+ return undefined;
51
+ }
52
+ function record(value, at, { state, keep, add }) {
53
+ const { session, names, turns, own: codex } = state;
54
+ const payload = isObject(value.payload) ? value.payload : {};
55
+ // One request's output items are one turn; its usage, when it comes, is that turn's. A usage with no request (a
56
+ // compaction's, one whose output is no item read here) is a turn of its own.
57
+ const answer = () => {
58
+ const turn = { role: "assistant", text: "", calls: [], at, ...(session.model ? { model: session.model } : {}), ...(state.effort ? { effort: state.effort } : {}) };
59
+ add(turn);
60
+ return turn;
61
+ };
62
+ const request = () => codex.open ?? (codex.open = codex.unpaid = answer());
63
+ // Each request's own counts (a token_count's last_token_usage), never the thread's running total.
64
+ const answered = (usage, response) => {
65
+ const tokens = normalizeUsage("openai", usage);
66
+ const turn = codex.unpaid ?? answer();
67
+ if (tokens)
68
+ turn.usage = tokens;
69
+ if (response)
70
+ turn.key = response;
71
+ codex.open = codex.unpaid = undefined;
72
+ };
73
+ if (value.type === "session_meta") {
74
+ if (str(payload.id))
75
+ session.id = payload.id;
76
+ if (str(payload.cwd))
77
+ session.cwd = payload.cwd;
78
+ if (str(payload.model_provider))
79
+ codex.provider = payload.model_provider;
80
+ if (str(payload.parent_thread_id) || (isObject(payload.source) && isObject(payload.source.subagent)))
81
+ session.child = true;
82
+ const spawn = isObject(payload.source) && isObject(payload.source.subagent) && isObject(payload.source.subagent.thread_spawn) ? payload.source.subagent.thread_spawn : undefined;
83
+ const parent = str(payload.parent_thread_id) ?? str(spawn?.parent_thread_id);
84
+ if (parent)
85
+ session.parent = parent;
86
+ return;
87
+ }
88
+ if (value.type === "turn_context") {
89
+ const model = str(payload.model);
90
+ if (model)
91
+ session.model = model.includes("/") ? model : `${codex.provider ?? "openai"}/${model}`;
92
+ if (!session.cwd && str(payload.cwd))
93
+ session.cwd = payload.cwd;
94
+ state.effort = effortOf(payload.effort);
95
+ // A new turn: a request left open (aborted) has no usage to come.
96
+ codex.open = codex.unpaid = undefined;
97
+ return;
98
+ }
99
+ // Each request's usage: a token_usage_record per response where the rollout has them (they also count requests no
100
+ // token_count reports, such as a compaction's), else each token_count whose total moved (one that repeats the last
101
+ // total is no new request).
102
+ if (value.type === "token_usage_record") {
103
+ codex.records = true;
104
+ const id = str(payload.response_id);
105
+ if (id && codex.responses.has(id))
106
+ return;
107
+ if (id)
108
+ codex.responses.add(id);
109
+ return answered(payload.usage, id);
110
+ }
111
+ if (value.type === "event_msg") {
112
+ if (payload.type === "user_message") {
113
+ codex.events = true;
114
+ if (str(payload.message))
115
+ add({ role: "user", text: payload.message, at });
116
+ }
117
+ else if (payload.type === "token_count") {
118
+ const info = isObject(payload.info) ? payload.info : undefined;
119
+ if (!info || codex.records)
120
+ return;
121
+ const total = isObject(info.total_token_usage) ? JSON.stringify(info.total_token_usage) : undefined;
122
+ if (total !== undefined && total === codex.total)
123
+ return;
124
+ codex.total = total;
125
+ answered(info.last_token_usage);
126
+ }
127
+ else if (payload.type === "item_completed" && isObject(payload.item) && str(payload.item.id)) {
128
+ // An item's id is its call's in some Codex versions: its status then says whether the call failed.
129
+ const { id, status, exit_code: code } = payload.item;
130
+ const failed = status === "failed" || (typeof code === "number" && code !== 0) ? true : status === "completed" ? false : undefined;
131
+ if (failed === undefined)
132
+ return;
133
+ codex.items.set(id, failed);
134
+ const result = codex.results.get(id);
135
+ if (result && !result.stated)
136
+ result.turn.isError = failed;
137
+ }
138
+ else if (payload.type === "task_complete")
139
+ session.state = "completed";
140
+ else if (payload.type === "turn_aborted")
141
+ session.state = "stopped";
142
+ else if (payload.type === "error")
143
+ session.state = "failed";
144
+ return;
145
+ }
146
+ if (value.type !== "response_item")
147
+ return;
148
+ if (payload.type === "message" && payload.role === "user") {
149
+ const text = wordsOf(payload.content);
150
+ if (text)
151
+ codex.held.push({ index: turns.length, turn: { role: "user", text, at } });
152
+ }
153
+ else if (payload.type === "message" && payload.role === "assistant") {
154
+ const text = textOf(payload.content);
155
+ if (text) {
156
+ const turn = request();
157
+ if (keep)
158
+ turn.text = [turn.text, text].filter(Boolean).join("\n");
159
+ }
160
+ }
161
+ else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type)) {
162
+ const turn = request();
163
+ if (payload.type !== "function_call" && payload.type !== "custom_tool_call")
164
+ return;
165
+ const id = String(payload.call_id ?? payload.id ?? "");
166
+ const name = String(payload.name ?? "");
167
+ names.set(id, name);
168
+ turn.calls.push({
169
+ type: "toolCall",
170
+ id,
171
+ name,
172
+ arguments: keep ? argsOf(payload.type === "function_call" ? payload.arguments : payload.input) : {},
173
+ });
174
+ }
175
+ else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
176
+ const id = String(payload.call_id ?? "");
177
+ const output = isObject(payload.output) && "content" in payload.output ? payload.output.content : payload.output;
178
+ const stated = codexFailed(payload.output);
179
+ // The model saw a result: what it writes next is another request.
180
+ if (codex.open?.calls.some((call) => call.id === id))
181
+ codex.open = undefined;
182
+ const turn = {
183
+ role: "toolResult",
184
+ callId: id,
185
+ name: names.get(id) ?? "",
186
+ // Without turns, no output text: the result is kept for whether it failed, in the result and the cursor alike.
187
+ text: keep ? textOf(output) : "",
188
+ isError: stated ?? codex.items.get(id) ?? false,
189
+ at,
190
+ };
191
+ codex.results.set(id, { turn, stated: stated !== undefined });
192
+ add(turn);
193
+ }
194
+ }
195
+ const spec = {
196
+ source: "codex",
197
+ name: "Codex",
198
+ harness: "codex",
199
+ async files(home, env) {
200
+ const out = [];
201
+ const walk = async (dir, depth) => {
202
+ for (const entry of await entries(dir)) {
203
+ if (entry.isDirectory() && depth < 3)
204
+ await walk(join(dir, entry.name), depth + 1);
205
+ else if (entry.isFile() && depth === 3 && /^rollout-.*\.jsonl$/.test(entry.name))
206
+ out.push(join(dir, entry.name));
207
+ }
208
+ };
209
+ // CODEX_HOME where the environment names it, else ~/.codex.
210
+ await walk(join(env?.CODEX_HOME || join(home, ".codex"), "sessions"), 0);
211
+ return out;
212
+ },
213
+ start: () => ({ events: false, held: [], records: false, responses: new Set(), items: new Map(), results: new Map() }),
214
+ record,
215
+ // Older Codex writes each of the person's turns twice, as a user_message event and as a user message; current Codex
216
+ // writes the user message alone. One source per file, so no turn counts twice.
217
+ finish(out, turns, { state: { own }, keep }) {
218
+ if (own.events || !own.held.length)
219
+ return turns;
220
+ // Held indexes refer to the non-user turns as read. Merge both ordered lists once: inserting each user into the middle
221
+ // of the transcript shifts its remaining turns again and again on a long current-Codex session.
222
+ const ordered = [];
223
+ let next = 0;
224
+ for (const { index, turn } of own.held) {
225
+ rememberUser(out, turn);
226
+ if (keep) {
227
+ while (next < index)
228
+ ordered.push(turns[next++]);
229
+ ordered.push(turn);
230
+ }
231
+ }
232
+ if (!keep)
233
+ return turns;
234
+ while (next < turns.length)
235
+ ordered.push(turns[next++]);
236
+ return ordered;
237
+ },
238
+ idOf: (file) => basename(file, ".jsonl"),
239
+ // A turns: false cursor keeps each held prompt for its count alone: a read resumed from it gives no first prompt.
240
+ forget: (own) => ({ ...own, held: own.held.map(({ index, turn }) => ({ index, turn: { ...turn, text: "" } })) }),
241
+ };
242
+ export const codex = lineReader(spec);
@@ -0,0 +1,12 @@
1
+ import type { Reader } from "../reader.js";
2
+ export declare const READERS: {
3
+ readonly "claude-code": Reader<"claude-code", import("../lines.js").FileCursor>;
4
+ readonly codex: Reader<"codex", import("../lines.js").FileCursor>;
5
+ readonly pi: Reader<"pi", import("../lines.js").FileCursor>;
6
+ };
7
+ export type Source = keyof typeof READERS;
8
+ export declare const SOURCES: Source[];
9
+ /** The harness of serve that runs what each source ran. */
10
+ export declare const HARNESS_OF: Record<Source, string>;
11
+ /** Each source's name as a person reads it. */
12
+ export declare const SOURCE_NAMES: Record<Source, string>;
@@ -0,0 +1,13 @@
1
+ import { claudeCode } from "./claude-code.js";
2
+ import { codex } from "./codex.js";
3
+ import { pi } from "./pi.js";
4
+ export const READERS = {
5
+ "claude-code": claudeCode,
6
+ codex,
7
+ pi,
8
+ };
9
+ export const SOURCES = Object.keys(READERS);
10
+ /** The harness of serve that runs what each source ran. */
11
+ export const HARNESS_OF = Object.fromEntries(SOURCES.map((source) => [source, READERS[source].harness]));
12
+ /** Each source's name as a person reads it. */
13
+ export const SOURCE_NAMES = Object.fromEntries(SOURCES.map((source) => [source, READERS[source].name]));
@@ -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;