@aispendbook/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Prompt chains of Claude Code requests, for the cache audit.
3
+ *
4
+ * Every transcript line has a uuid and a parentUuid; following the parents from a request gives the
5
+ * messages that were sent before it. Each line's content is hashed (SHA-256) together with its
6
+ * parent's hash, so a request's prefix hash names everything sent before it, and two requests with the
7
+ * same hash at some point sent the same messages up to there. Hashing happens in memory: no content is
8
+ * kept, printed or uploaded, only the hashes, ids and token counts.
9
+ *
10
+ * For each request the nearest earlier request on its chain is its "previous" request: that request's
11
+ * whole prompt (its messages) was sent again, verbatim, at the start of this one. The system prompt and
12
+ * tool definitions are not in the transcript, so they are not part of the hash.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+ import { join } from "node:path";
16
+ import { toEvent } from "./claude-code.js";
17
+ import { emptyStats, jsonLines, str } from "./util.js";
18
+ const sha = (s) => createHash("sha256").update(s).digest("hex");
19
+ export class ClaudePromptChainSource {
20
+ fs;
21
+ configDirs;
22
+ constructor(fs, configDirs) {
23
+ this.fs = fs;
24
+ this.configDirs = configDirs;
25
+ }
26
+ async read(options) {
27
+ const stats = emptyStats();
28
+ const links = new Map();
29
+ const sinceMs = options.since?.getTime() ?? -Infinity;
30
+ for (const dir of this.configDirs) {
31
+ const files = await this.fs.listFiles(join(dir, "projects"), (n) => n.endsWith(".jsonl"));
32
+ for (const f of files) {
33
+ if (f.mtimeMs < sinceMs)
34
+ continue;
35
+ let text;
36
+ try {
37
+ text = await this.fs.readText(f.path);
38
+ }
39
+ catch {
40
+ stats.filesSkipped++;
41
+ continue;
42
+ }
43
+ stats.filesRead++;
44
+ for (const l of chainLinks(text, stats)) {
45
+ if (links.has(l.key))
46
+ stats.duplicates++;
47
+ else
48
+ links.set(l.key, l);
49
+ }
50
+ }
51
+ }
52
+ return { links: [...links.values()].sort((a, b) => a.at.getTime() - b.at.getTime()), stats };
53
+ }
54
+ }
55
+ /** Links of one transcript file. */
56
+ export function chainLinks(text, stats) {
57
+ const nodes = new Map();
58
+ const firstLine = new Map();
59
+ for (const line of jsonLines(text, stats)) {
60
+ const uuid = str(line.uuid);
61
+ if (!uuid)
62
+ continue;
63
+ const payload = line.message ?? line.attachment ?? line.content ?? null;
64
+ const node = { parent: str(line.parentUuid), contentHash: sha(`${String(line.type)}\u0000${JSON.stringify(payload)}`), requestKey: null };
65
+ nodes.set(uuid, node);
66
+ if (line.type !== "assistant")
67
+ continue;
68
+ const ev = toEvent(line, "");
69
+ if (!ev || ev === "skip")
70
+ continue;
71
+ node.requestKey = ev.dedupeKey;
72
+ if (!firstLine.has(ev.dedupeKey))
73
+ firstLine.set(ev.dedupeKey, { parent: node.parent, event: ev });
74
+ }
75
+ const memo = new Map();
76
+ const chainHash = (uuid) => {
77
+ const path = [];
78
+ let cur = uuid;
79
+ while (cur && !memo.has(cur) && nodes.has(cur) && path.length <= nodes.size) {
80
+ path.push(cur);
81
+ cur = nodes.get(cur).parent;
82
+ }
83
+ let h = cur && memo.has(cur) ? memo.get(cur) : "";
84
+ for (let i = path.length - 1; i >= 0; i--) {
85
+ h = sha(`${h}\u0000${nodes.get(path[i]).contentHash}`);
86
+ memo.set(path[i], h);
87
+ }
88
+ return h;
89
+ };
90
+ const out = [];
91
+ for (const [key, { parent, event: e }] of firstLine) {
92
+ let previous = null;
93
+ let cur = parent;
94
+ for (let steps = 0; cur && steps <= nodes.size; steps++) {
95
+ const n = nodes.get(cur);
96
+ if (!n)
97
+ break;
98
+ if (n.requestKey && n.requestKey !== key) {
99
+ previous = n.requestKey;
100
+ break;
101
+ }
102
+ cur = n.parent;
103
+ }
104
+ out.push({
105
+ key, model: e.model, at: e.occurredAt, sessionId: e.sessionId, inputTokens: e.inputTokens,
106
+ cacheReadTokens: e.cacheReadTokens, cacheWriteTokens: e.cacheWriteTokens, cacheWrite1hTokens: e.cacheWrite1hTokens,
107
+ prefixHash: chainHash(parent), previous,
108
+ });
109
+ }
110
+ return out;
111
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * OpenAI Codex CLI rollouts: $CODEX_HOME/sessions/YYYY/MM/DD/rollout-*.jsonl, and archived ones in
3
+ * $CODEX_HOME/archived_sessions (plain or zstd-compressed .jsonl.zst).
4
+ *
5
+ * Lines are {timestamp, type, payload}. session_meta gives the session id, cwd and model provider;
6
+ * turn_context gives the model of each turn (turn_id). Usage comes from one of two record kinds:
7
+ * - token_usage_record (newer Codex): one per model response, with response_id, turn_id and usage.
8
+ * - event_msg / token_count (all versions): info.last_token_usage and the cumulative
9
+ * info.total_token_usage. The same count is often emitted twice; a repeat of the previous
10
+ * cumulative total is a duplicate.
11
+ * A file with token_usage_record lines is read from those only, so a response is never counted twice.
12
+ * OpenAI usage counts cached (and cache-write) tokens inside input_tokens; they are split out here.
13
+ */
14
+ import { join } from "node:path";
15
+ import { count, date, emptyStats, jsonLines, obj, projectFromCwd, str } from "./util.js";
16
+ const ROLLOUT = /^rollout-.*\.jsonl(\.zst)?$/;
17
+ export class CodexSource {
18
+ fs;
19
+ codexHome;
20
+ id = "codex";
21
+ constructor(fs, codexHome) {
22
+ this.fs = fs;
23
+ this.codexHome = codexHome;
24
+ }
25
+ async read(options) {
26
+ const stats = emptyStats();
27
+ const notes = [];
28
+ const byKey = new Map();
29
+ const sinceMs = options.since?.getTime() ?? -Infinity;
30
+ let noDecoder = 0;
31
+ for (const sub of ["sessions", "archived_sessions"]) {
32
+ const files = await this.fs.listFiles(join(this.codexHome, sub), (n) => ROLLOUT.test(n));
33
+ for (const f of files) {
34
+ if (f.mtimeMs < sinceMs)
35
+ continue;
36
+ let text;
37
+ try {
38
+ text = f.path.endsWith(".zst") ? await this.fs.readZstdText(f.path) : await this.fs.readText(f.path);
39
+ }
40
+ catch {
41
+ stats.filesSkipped++;
42
+ continue;
43
+ }
44
+ if (text === null) {
45
+ noDecoder++;
46
+ stats.filesSkipped++;
47
+ continue;
48
+ }
49
+ stats.filesRead++;
50
+ for (const ev of parseRollout(text, stats)) {
51
+ if (byKey.has(ev.dedupeKey))
52
+ stats.duplicates++;
53
+ else
54
+ byKey.set(ev.dedupeKey, ev);
55
+ }
56
+ }
57
+ }
58
+ if (noDecoder) {
59
+ notes.push(`${noDecoder} compressed archived Codex session file(s) skipped: reading .zst needs Node.js 22.15 or later.`);
60
+ }
61
+ return { events: [...byKey.values()], stats, notes };
62
+ }
63
+ }
64
+ function usageOf(v) {
65
+ const u = obj(v);
66
+ if (!u)
67
+ return null;
68
+ return {
69
+ input: count(u.input_tokens),
70
+ cached: count(u.cached_input_tokens),
71
+ cacheWrite: count(u.cache_write_input_tokens),
72
+ output: count(u.output_tokens),
73
+ };
74
+ }
75
+ function sameUsage(a, b) {
76
+ return JSON.stringify(a) === JSON.stringify(b);
77
+ }
78
+ /** Usage events of one rollout file. */
79
+ export function parseRollout(text, stats) {
80
+ let sessionId = null;
81
+ let cwd = null;
82
+ let provider = "openai";
83
+ let currentModel = null;
84
+ const turnModel = new Map();
85
+ const records = [];
86
+ const counts = [];
87
+ let prevTotal = null;
88
+ for (const line of jsonLines(text, stats)) {
89
+ const payload = obj(line.payload);
90
+ const at = date(line.timestamp);
91
+ switch (line.type) {
92
+ case "session_meta":
93
+ sessionId = str(payload?.id) ?? sessionId;
94
+ cwd = str(payload?.cwd) ?? cwd;
95
+ provider = str(payload?.model_provider)?.toLowerCase() ?? provider;
96
+ break;
97
+ case "turn_context": {
98
+ const model = str(payload?.model);
99
+ if (model) {
100
+ currentModel = model;
101
+ const turn = str(payload?.turn_id);
102
+ if (turn)
103
+ turnModel.set(turn, model);
104
+ }
105
+ cwd = cwd ?? str(payload?.cwd);
106
+ break;
107
+ }
108
+ case "token_usage_record": {
109
+ const responseId = str(payload?.response_id);
110
+ const usage = usageOf(payload?.usage);
111
+ if (!responseId || !usage || !at) {
112
+ stats.linesSkipped++;
113
+ break;
114
+ }
115
+ records.push({ at, responseId, turnId: str(payload?.turn_id), usage });
116
+ // A record without a turn_context of its own is priced with the model in effect.
117
+ if (payload?.turn_id && currentModel && !turnModel.has(String(payload.turn_id))) {
118
+ turnModel.set(String(payload.turn_id), currentModel);
119
+ }
120
+ break;
121
+ }
122
+ case "event_msg": {
123
+ if (payload?.type !== "token_count")
124
+ break;
125
+ const info = obj(payload.info);
126
+ if (!info)
127
+ break; // rate-limit only update, no usage
128
+ const total = obj(info.total_token_usage);
129
+ const last = usageOf(info.last_token_usage);
130
+ if (!at || !last) {
131
+ stats.linesSkipped++;
132
+ break;
133
+ }
134
+ if (total && sameUsage(total, prevTotal)) {
135
+ stats.duplicates++;
136
+ break;
137
+ }
138
+ prevTotal = total;
139
+ const key = `tc:${line.timestamp}:${JSON.stringify(info.last_token_usage)}:${JSON.stringify(total)}`;
140
+ counts.push({ at, key, usage: last, model: currentModel });
141
+ break;
142
+ }
143
+ default:
144
+ break;
145
+ }
146
+ }
147
+ const project = cwd ? projectFromCwd(cwd) : "unknown";
148
+ const make = (at, key, model, u) => {
149
+ if (!model) {
150
+ stats.linesSkipped++;
151
+ return null;
152
+ }
153
+ const cacheRead = Math.min(u.cached, u.input);
154
+ const cacheWrite = Math.min(u.cacheWrite, u.input - cacheRead);
155
+ return {
156
+ tool: "codex", provider, model, occurredAt: at, dedupeKey: key, sessionId, project,
157
+ inputTokens: u.input - cacheRead - cacheWrite, outputTokens: u.output, cacheReadTokens: cacheRead,
158
+ cacheWriteTokens: cacheWrite, cacheWrite1hTokens: 0,
159
+ };
160
+ };
161
+ const events = records.length
162
+ ? records.map((r) => make(r.at, `resp:${r.responseId}`, (r.turnId && turnModel.get(r.turnId)) || currentModel, r.usage))
163
+ : counts.map((c) => make(c.at, c.key, c.model, c.usage));
164
+ return events.filter((e) => e !== null);
165
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Gemini CLI chat recordings: ~/.gemini/tmp/<project id>/chats/ (subagent sessions in a subfolder).
3
+ *
4
+ * Current versions append JSON Lines (session-*.jsonl): a metadata line {sessionId, projectHash,
5
+ * directories, ...}, one line per message, and update lines {"$set"}, {"$patch"} or {"$rewindTo"}.
6
+ * Older versions wrote one JSON object {sessionId, projectHash, messages: [...]} (session-*.json).
7
+ * A message of type "gemini" carries model and tokens {input, output, cached, thoughts, tool, total},
8
+ * copied from the API usage metadata: input = promptTokenCount (which includes the cached tokens),
9
+ * output = candidatesTokenCount, thoughts = thoughtsTokenCount (billed as output),
10
+ * tool = toolUsePromptTokenCount (billed as input). A message written again under the same id
11
+ * replaces the earlier copy. Only ids, model, timestamps and token counts are read.
12
+ */
13
+ import { relative, sep } from "node:path";
14
+ import { baseName, count, date, emptyStats, jsonLines, obj, str } from "./util.js";
15
+ const LEGACY_HASH = /^[0-9a-f]{64}$/;
16
+ export class GeminiSource {
17
+ fs;
18
+ tmpDirs;
19
+ id = "gemini";
20
+ constructor(fs, tmpDirs) {
21
+ this.fs = fs;
22
+ this.tmpDirs = tmpDirs;
23
+ }
24
+ async read(options) {
25
+ const stats = emptyStats();
26
+ const byKey = new Map();
27
+ const sinceMs = options.since?.getTime() ?? -Infinity;
28
+ for (const tmp of this.tmpDirs) {
29
+ const files = await this.fs.listFiles(tmp, (n) => /\.jsonl?$/.test(n));
30
+ for (const f of files) {
31
+ const parts = relative(tmp, f.path).split(sep);
32
+ if (parts.length < 3 || parts[1] !== "chats" || f.mtimeMs < sinceMs)
33
+ continue;
34
+ let text;
35
+ try {
36
+ text = await this.fs.readText(f.path);
37
+ }
38
+ catch {
39
+ stats.filesSkipped++;
40
+ continue;
41
+ }
42
+ stats.filesRead++;
43
+ for (const ev of parseChat(text, f.path.endsWith(".jsonl"), parts[0] ?? "unknown", stats)) {
44
+ if (byKey.has(ev.dedupeKey))
45
+ stats.duplicates++;
46
+ byKey.set(ev.dedupeKey, ev);
47
+ }
48
+ }
49
+ }
50
+ return { events: [...byKey.values()], stats, notes: [] };
51
+ }
52
+ }
53
+ /** Usage events of one chat file (JSON Lines, or the legacy single JSON object). */
54
+ export function parseChat(text, isJsonl, projectId, stats) {
55
+ let meta = {};
56
+ const messages = new Map();
57
+ const put = (m) => {
58
+ const id = str(m.id);
59
+ if (!id)
60
+ return;
61
+ if (messages.has(id))
62
+ stats.duplicates++;
63
+ messages.set(id, { ...(messages.get(id) ?? {}), ...m });
64
+ };
65
+ if (isJsonl) {
66
+ for (const line of jsonLines(text, stats)) {
67
+ if ("$set" in line || "$rewindTo" in line)
68
+ continue; // metadata edits; rewound turns were still billed
69
+ if ("$patch" in line) {
70
+ const updates = obj(line.$patch)?.updates;
71
+ const list = Array.isArray(updates) ? updates : Object.entries(obj(updates) ?? {}).map(([id, v]) => ({ ...obj(v), id }));
72
+ for (const u of list) {
73
+ const m = obj(u);
74
+ if (m && str(m.id) && messages.has(String(m.id)))
75
+ put(m);
76
+ }
77
+ continue;
78
+ }
79
+ if (str(line.type) && str(line.id))
80
+ put(line);
81
+ else if (str(line.sessionId))
82
+ meta = line;
83
+ else
84
+ stats.linesSkipped++;
85
+ }
86
+ }
87
+ else {
88
+ let doc = null;
89
+ try {
90
+ doc = obj(JSON.parse(text));
91
+ }
92
+ catch {
93
+ doc = null;
94
+ }
95
+ if (!doc || !Array.isArray(doc.messages)) {
96
+ stats.linesSkipped++;
97
+ return [];
98
+ }
99
+ meta = doc;
100
+ for (const m of doc.messages) {
101
+ const o = obj(m);
102
+ if (o)
103
+ put(o);
104
+ else
105
+ stats.linesSkipped++;
106
+ }
107
+ }
108
+ const sessionId = str(meta.sessionId);
109
+ const dirs = Array.isArray(meta.directories) ? meta.directories.filter((d) => typeof d === "string") : [];
110
+ const project = !LEGACY_HASH.test(projectId) ? projectId : dirs[0] ? baseName(dirs[0]) : `gemini-${projectId.slice(0, 8)}`;
111
+ const events = [];
112
+ for (const [id, m] of messages) {
113
+ if (m.type !== "gemini")
114
+ continue;
115
+ const tokens = obj(m.tokens);
116
+ const at = date(m.timestamp);
117
+ if (!tokens || !at) {
118
+ if (!tokens)
119
+ continue; // a message with no usage (e.g. cancelled before a response)
120
+ stats.linesSkipped++;
121
+ continue;
122
+ }
123
+ const input = count(tokens.input);
124
+ const cached = Math.min(count(tokens.cached), input);
125
+ events.push({
126
+ tool: "gemini",
127
+ provider: "google",
128
+ model: str(m.model) ?? "unknown",
129
+ occurredAt: at,
130
+ dedupeKey: `${sessionId ?? "nosession"}:${id}`,
131
+ sessionId,
132
+ project,
133
+ inputTokens: input - cached + count(tokens.tool),
134
+ outputTokens: count(tokens.output) + count(tokens.thoughts),
135
+ cacheReadTokens: cached,
136
+ cacheWriteTokens: 0,
137
+ cacheWrite1hTokens: 0,
138
+ });
139
+ }
140
+ return events;
141
+ }
@@ -0,0 +1,53 @@
1
+ export function obj(v) {
2
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
3
+ }
4
+ export function str(v) {
5
+ return typeof v === "string" && v.length > 0 ? v : null;
6
+ }
7
+ /** A non-negative integer token count, or 0. */
8
+ export function count(v) {
9
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0;
10
+ }
11
+ export function date(v) {
12
+ if (typeof v !== "string" && typeof v !== "number")
13
+ return null;
14
+ const d = new Date(v);
15
+ return Number.isNaN(d.getTime()) ? null : d;
16
+ }
17
+ /** Parse JSON Lines; a line that is not a JSON object is counted as skipped. */
18
+ export function* jsonLines(text, stats) {
19
+ for (const line of text.split("\n")) {
20
+ const t = line.trim();
21
+ if (!t)
22
+ continue;
23
+ let parsed;
24
+ try {
25
+ parsed = JSON.parse(t);
26
+ }
27
+ catch {
28
+ stats.linesSkipped++;
29
+ continue;
30
+ }
31
+ const o = obj(parsed);
32
+ if (o)
33
+ yield o;
34
+ else
35
+ stats.linesSkipped++;
36
+ }
37
+ }
38
+ export function emptyStats() {
39
+ return { filesRead: 0, filesSkipped: 0, linesSkipped: 0, duplicates: 0 };
40
+ }
41
+ /** The last path segment of a POSIX or Windows path. */
42
+ export function baseName(p) {
43
+ const parts = p.replace(/[\\/]+$/, "").split(/[\\/]/);
44
+ return parts[parts.length - 1] || p;
45
+ }
46
+ /**
47
+ * A readable project name for a working directory. A git worktree that a tool keeps inside the
48
+ * project (".../<project>/.claude/worktrees/<name>") belongs to that project.
49
+ */
50
+ export function projectFromCwd(cwd) {
51
+ const m = cwd.match(/^(.*?)[\\/]\.(?:claude|codex|gemini)[\\/]worktrees[\\/]/);
52
+ return baseName(m ? m[1] : cwd);
53
+ }
package/dist/sync.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Upload of usage counts to POST {api}/api/v1/ingest/batch with an ingestion key.
3
+ *
4
+ * Each event carries only counts, the model, a timestamp and pseudonymous ids. The event id is a hash
5
+ * of the tool and the request's own id, so syncing the same logs again is deduplicated by the server.
6
+ */
7
+ import { createHash } from "node:crypto";
8
+ import { join } from "node:path";
9
+ import { DEFAULTS } from "./config.js";
10
+ const EVENT_PREFIX = { "claude-code": "cc_", codex: "cx_", gemini: "gm_" };
11
+ const MAX_ID = 200; // IngestEvent string id limit
12
+ function sha256(s) {
13
+ return createHash("sha256").update(s).digest("hex");
14
+ }
15
+ export function projectId(project, plain) {
16
+ return plain ? project.slice(0, MAX_ID) : `p_${sha256(`project:${project}`).slice(0, 24)}`;
17
+ }
18
+ export function toIngestEvent(e, o) {
19
+ const ev = {
20
+ event_id: EVENT_PREFIX[e.tool] + sha256(`${e.tool}:${e.dedupeKey}`).slice(0, 40),
21
+ occurred_at: e.occurredAt.toISOString(),
22
+ provider: e.provider,
23
+ model: e.model.slice(0, MAX_ID),
24
+ input_tokens: e.inputTokens,
25
+ output_tokens: e.outputTokens,
26
+ cache_read_tokens: e.cacheReadTokens,
27
+ cache_write_tokens: e.cacheWriteTokens,
28
+ cache_write_1h_tokens: Math.min(e.cacheWrite1hTokens, e.cacheWriteTokens),
29
+ feature: e.tool,
30
+ project_id: projectId(e.project, o.plainProjectNames),
31
+ sdk: { name: DEFAULTS.sdkName, version: o.version },
32
+ };
33
+ if (e.sessionId)
34
+ ev.session_id = `s_${sha256(`${e.tool}:session:${e.sessionId}`).slice(0, 24)}`;
35
+ return ev;
36
+ }
37
+ /** Seconds or an HTTP date, as Retry-After allows. */
38
+ export function retryAfterMs(header, now) {
39
+ if (!header)
40
+ return null;
41
+ const s = Number(header.trim());
42
+ if (Number.isFinite(s) && s >= 0)
43
+ return s * 1000;
44
+ const at = Date.parse(header);
45
+ return Number.isNaN(at) ? null : Math.max(0, at - now.getTime());
46
+ }
47
+ function errorMessage(status, body) {
48
+ try {
49
+ const msg = JSON.parse(body).error?.message;
50
+ if (typeof msg === "string")
51
+ return `HTTP ${status}: ${msg}`;
52
+ }
53
+ catch {
54
+ // not JSON
55
+ }
56
+ return `HTTP ${status}`;
57
+ }
58
+ export class HttpUploader {
59
+ http;
60
+ sleeper;
61
+ clock;
62
+ constructor(http, sleeper, clock) {
63
+ this.http = http;
64
+ this.sleeper = sleeper;
65
+ this.clock = clock;
66
+ }
67
+ async upload(events, o) {
68
+ const result = {
69
+ batchesSent: 0, accepted: 0, duplicates: 0, crossSourceDuplicates: 0, rejected: 0,
70
+ rejectedReasons: [], retries: 0, error: null,
71
+ };
72
+ const url = `${o.apiBase}${o.ingestPath}`;
73
+ for (let i = 0; i < events.length; i += o.batchSize) {
74
+ const body = JSON.stringify({ events: events.slice(i, i + o.batchSize) });
75
+ let attempt = 0;
76
+ for (;;) {
77
+ let status = 0;
78
+ let text = "";
79
+ let wait = null;
80
+ try {
81
+ const res = await this.http(url, {
82
+ method: "POST",
83
+ headers: { "content-type": "application/json", authorization: `Bearer ${o.key}` },
84
+ body,
85
+ });
86
+ status = res.status;
87
+ text = await res.text();
88
+ if (status === 429)
89
+ wait = retryAfterMs(res.headers.get("retry-after"), this.clock.now());
90
+ }
91
+ catch (err) {
92
+ text = err instanceof Error ? err.message : String(err);
93
+ }
94
+ if (status >= 200 && status < 300) {
95
+ let r;
96
+ try {
97
+ r = JSON.parse(text);
98
+ }
99
+ catch {
100
+ result.error = `HTTP ${status}: the response was not JSON`;
101
+ return result;
102
+ }
103
+ result.batchesSent++;
104
+ result.accepted += r.accepted ?? 0;
105
+ result.duplicates += r.duplicates ?? 0;
106
+ result.crossSourceDuplicates += r.cross_source_duplicates ?? 0;
107
+ result.rejected += r.rejected?.length ?? 0;
108
+ for (const rej of r.rejected ?? []) {
109
+ if (result.rejectedReasons.length < 5 && rej.reason)
110
+ result.rejectedReasons.push(rej.reason);
111
+ }
112
+ break;
113
+ }
114
+ const retryable = status === 0 || status === 429 || status >= 500;
115
+ if (!retryable || attempt >= o.maxRetries) {
116
+ result.error = status === 0 ? `Could not reach ${o.apiBase}: ${text}` : errorMessage(status, text);
117
+ return result;
118
+ }
119
+ attempt++;
120
+ result.retries++;
121
+ await this.sleeper.sleep(Math.min(wait ?? 1000 * 2 ** attempt, o.maxRetryWaitMs));
122
+ }
123
+ }
124
+ return result;
125
+ }
126
+ }
127
+ export class SyncStateStore {
128
+ fs;
129
+ path;
130
+ constructor(fs, stateDir) {
131
+ this.fs = fs;
132
+ this.path = join(stateDir, DEFAULTS.stateFileName);
133
+ }
134
+ async load() {
135
+ try {
136
+ const s = JSON.parse(await this.fs.readText(this.path));
137
+ return { lastSyncAt: s.lastSyncAt && typeof s.lastSyncAt === "object" ? s.lastSyncAt : {} };
138
+ }
139
+ catch {
140
+ return { lastSyncAt: {} };
141
+ }
142
+ }
143
+ async save(state) {
144
+ await this.fs.writeText(this.path, `${JSON.stringify(state, null, 2)}\n`);
145
+ }
146
+ }
147
+ export class HttpComparisonPoster {
148
+ http;
149
+ constructor(http) {
150
+ this.http = http;
151
+ }
152
+ async post(body, o) {
153
+ try {
154
+ const res = await this.http(`${o.apiBase}${o.path}`, {
155
+ method: "POST",
156
+ headers: { "content-type": "application/json", authorization: `Bearer ${o.key}` },
157
+ body: JSON.stringify(body),
158
+ });
159
+ const text = await res.text();
160
+ let parsed = null;
161
+ try {
162
+ parsed = JSON.parse(text);
163
+ }
164
+ catch {
165
+ parsed = null;
166
+ }
167
+ const ok = res.status >= 200 && res.status < 300;
168
+ return { status: res.status, error: ok ? null : errorMessage(res.status, text), body: parsed };
169
+ }
170
+ catch (err) {
171
+ return { status: 0, error: `Could not reach ${o.apiBase}: ${err instanceof Error ? err.message : String(err)}`, body: null };
172
+ }
173
+ }
174
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Shared types and the interfaces that every implementation in this package sits behind. */
2
+ export const TOOLS = ["claude-code", "codex", "gemini"];