conare 0.19.0 → 0.20.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,125 @@
1
+ // The record of sessions sync runs: one line per run appended to ~/.conare/sync.log, and the
2
+ // last run, the last success and the newest uploaded session in ~/.conare/sync-status.json,
3
+ // which `conare sync status` reads.
4
+ import { appendFileSync, mkdirSync, readFileSync, statSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+ import { writePrivate } from "./config.js";
7
+ /** `conare sync status` fails when the last success is older than this. */
8
+ export const MAX_SUCCESS_AGE_MS = 60 * 60 * 1000;
9
+ export function readStatus(file) {
10
+ try {
11
+ const s = JSON.parse(readFileSync(file, "utf8"));
12
+ return s && typeof s === "object" ? s : {};
13
+ }
14
+ catch {
15
+ return {};
16
+ }
17
+ }
18
+ /** The line a run adds to the log. */
19
+ export function runLine(run) {
20
+ const counts = `uploaded ${run.uploaded}, skipped ${run.skipped}, failed ${run.failed}, deleted ${run.deleted}`;
21
+ return `${run.at} sync sessions ${run.ok ? "ok" : "FAILED"}: ${counts}, ${(run.durationMs / 1000).toFixed(1)} s${run.error ? `: ${oneLine(run.error)}` : ""}`;
22
+ }
23
+ /** Append the run to the log and the status file. Never throws: recording must not fail a sync. */
24
+ export function recordRun(files, run, newest) {
25
+ try {
26
+ mkdirSync(dirname(files.logFile), { recursive: true, mode: 0o700 });
27
+ appendFileSync(files.logFile, `${runLine(run)}\n`);
28
+ }
29
+ catch {
30
+ // A full or read-only disk: the status file below may still be written.
31
+ }
32
+ try {
33
+ const status = readStatus(files.statusFile);
34
+ status.lastRun = run;
35
+ if (run.ok)
36
+ status.lastSuccessAt = run.at;
37
+ if (newest && (!status.newestSession || newest.date > status.newestSession.date))
38
+ status.newestSession = newest;
39
+ writePrivate(files.statusFile, `${JSON.stringify(status, null, 2)}\n`);
40
+ }
41
+ catch {
42
+ // As above.
43
+ }
44
+ }
45
+ /**
46
+ * Transcripts last changed before `before` (the start of the last successful run) that the
47
+ * sync state does not stamp as synced. A run stamps every file it read, uploaded or not (empty
48
+ * sessions and duplicates included), so one of these was never read by that run: the
49
+ * background sync scans another directory (CLAUDE_CONFIG_DIR or CODEX_HOME changed since
50
+ * --install), the file cannot be read, or the server refused its documents.
51
+ */
52
+ export function unsyncedTranscripts(paths, stamps, before) {
53
+ const out = [];
54
+ for (const path of paths) {
55
+ let stat;
56
+ try {
57
+ stat = statSync(path);
58
+ }
59
+ catch {
60
+ continue; // removed since it was listed
61
+ }
62
+ if (stat.mtimeMs >= before)
63
+ continue; // the next run reads it
64
+ const s = stamps[path];
65
+ if (!s || s.size !== stat.size || s.mtimeMs !== stat.mtimeMs)
66
+ out.push(path);
67
+ }
68
+ return out;
69
+ }
70
+ /** The file stamps in a sync state file, whatever key wrote it; {} when there is none. */
71
+ export function readStamps(stateFile) {
72
+ try {
73
+ const files = JSON.parse(readFileSync(stateFile, "utf8")).files;
74
+ return files && typeof files === "object" ? files : {};
75
+ }
76
+ catch {
77
+ return {};
78
+ }
79
+ }
80
+ /**
81
+ * The status report and whether the sync is healthy: a success within the last hour, and no
82
+ * transcript on disk that the last success should have synced and did not (`unsynced`).
83
+ */
84
+ export function describeStatus(status, now, schedule, unsynced = []) {
85
+ const lines = [];
86
+ const run = status.lastRun;
87
+ lines.push(run ? `Last run: ${when(run.at, now)}, ${run.ok ? "ok" : "failed"}: uploaded ${run.uploaded}, skipped ${run.skipped}, failed ${run.failed}, deleted ${run.deleted}, ${(run.durationMs / 1000).toFixed(1)} s` : "Last run: never");
88
+ if (run?.error)
89
+ lines.push(` ${oneLine(run.error)}`);
90
+ lines.push(`Last success: ${status.lastSuccessAt ? when(status.lastSuccessAt, now) : "never"}`);
91
+ const newest = status.newestSession;
92
+ lines.push(`Newest upload: ${newest ? `${newest.id}, last activity ${when(newest.date, now)}` : "none recorded"}`);
93
+ lines.push(`Background: ${schedule ?? "not installed (conare sync --install)"}`);
94
+ const success = status.lastSuccessAt ? Date.parse(status.lastSuccessAt) : NaN;
95
+ const recent = Number.isFinite(success) && now - success <= MAX_SUCCESS_AGE_MS;
96
+ if (!recent)
97
+ lines.push(status.lastSuccessAt ? "UNHEALTHY: the last successful sync is over 1 h old." : "UNHEALTHY: no successful sync recorded.");
98
+ if (unsynced.length > 0) {
99
+ lines.push(`UNHEALTHY: ${unsynced.length} transcripts changed before the last successful sync are not synced, e.g. ${unsynced[0]}.`, " The background sync may read another directory (CLAUDE_CONFIG_DIR or CODEX_HOME changed since --install: run it again), or could not read or upload them (see the log).");
100
+ }
101
+ return { text: `${lines.join("\n")}\n`, ok: recent && unsynced.length === 0 };
102
+ }
103
+ /** "2026-10-07 12:00 UTC (12 min ago)". */
104
+ export function when(iso, now) {
105
+ const t = Date.parse(iso);
106
+ if (!Number.isFinite(t))
107
+ return iso;
108
+ return `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC (${age(now - t)})`;
109
+ }
110
+ export function age(ms) {
111
+ if (ms < 0)
112
+ return "in the future";
113
+ const min = Math.floor(ms / 60_000);
114
+ if (min < 1)
115
+ return "just now";
116
+ if (min < 120)
117
+ return `${min} min ago`;
118
+ const h = Math.floor(min / 60);
119
+ if (h < 48)
120
+ return `${h} h ago`;
121
+ return `${Math.floor(h / 24)} days ago`;
122
+ }
123
+ function oneLine(s) {
124
+ return s.replace(/\s+/g, " ").trim().slice(0, 500);
125
+ }
@@ -0,0 +1,219 @@
1
+ // One sync run: find transcripts, render the new or changed ones, upload them in batches,
2
+ // and record what the server accepted.
3
+ import { statSync } from "node:fs";
4
+ import { NAMESPACE, baseId, toDocuments } from "./documents.js";
5
+ import { projectName } from "./project.js";
6
+ import { findClaudeFiles, readClaudeFile } from "./sources/claude.js";
7
+ import { findCodexFiles, readCodexFile } from "./sources/codex.js";
8
+ import { isStamped, loadState, saveState } from "./state.js";
9
+ import { BATCH_BYTES, BATCH_DOCUMENTS, UPLOADS_IN_FLIGHT, heldAs, listLayouts, removeStaleParts, sendBatch } from "./upload.js";
10
+ export function findTranscripts(paths) {
11
+ return [
12
+ ...findClaudeFiles(paths.claudeDir).map((f) => ({ path: f.path, read: () => readClaudeFile(f) })),
13
+ ...findCodexFiles(paths.codexDir).map((f) => ({ path: f.path, read: () => readCodexFile(f) })),
14
+ ];
15
+ }
16
+ export async function runSync(opts) {
17
+ const dryRun = !opts.client;
18
+ const ns = opts.client?.namespace(NAMESPACE);
19
+ const log = opts.log ?? (() => { });
20
+ const state = loadState(opts.stateFile, opts.account);
21
+ const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, deleted: 0, rejected: [], planned: [] };
22
+ // The layout the server holds for a session: what the state said this tool stored last;
23
+ // on a fresh state (the first sync, after the migration of older history), or for a session
24
+ // whose upload an earlier run cut short after some of its documents were accepted (0: any
25
+ // of its parts, gaps included, may be there), one listing of the namespace, read once;
26
+ // else unknown, and probed.
27
+ const fresh = !Object.values(state.parts).some((n) => n > 0);
28
+ let layouts;
29
+ const held = async (entry) => {
30
+ if (entry.previous)
31
+ return heldAs(entry.previous);
32
+ if (!ns || (!fresh && entry.previous !== 0))
33
+ return undefined;
34
+ layouts ??= listLayouts(ns);
35
+ return (await layouts).get(entry.base) ?? { whole: false, parts: [] };
36
+ };
37
+ const owner = new Map();
38
+ const produced = new Set(); // base ids
39
+ let queue = [];
40
+ let queuedBytes = 0;
41
+ // Up to UPLOADS_IN_FLIGHT batches at once: the server embeds a batch before it answers
42
+ // (~10 s a MB), so one at a time left the embedders idle (5 MB a minute, 2026-10-07).
43
+ const inflight = new Set();
44
+ let failure;
45
+ const flush = async () => {
46
+ if (queue.length > 0 && ns) {
47
+ const batch = queue;
48
+ queue = [];
49
+ queuedBytes = 0;
50
+ const sent = send(ns, batch).then(() => undefined, (err) => {
51
+ failure ??= err;
52
+ });
53
+ const tracked = sent.finally(() => inflight.delete(tracked));
54
+ inflight.add(tracked);
55
+ }
56
+ while (inflight.size >= UPLOADS_IN_FLIGHT)
57
+ await Promise.race(inflight);
58
+ if (failure !== undefined) {
59
+ await Promise.all(inflight); // what they accept is recorded before the run returns
60
+ throw failure;
61
+ }
62
+ };
63
+ const drain = async () => {
64
+ await flush();
65
+ await Promise.all(inflight);
66
+ if (failure !== undefined)
67
+ throw failure;
68
+ };
69
+ const send = async (ns, batch) => {
70
+ const result = await sendBatch(ns, batch);
71
+ const touched = new Set();
72
+ for (const doc of result.accepted) {
73
+ state.documents[doc.id] = String(doc.metadata.content_hash);
74
+ report.documents++;
75
+ report.bytes += Buffer.byteLength(doc.text);
76
+ const date = doc.metadata.date;
77
+ if (typeof date === "string" && (!report.newest || date > report.newest.date))
78
+ report.newest = { id: doc.id.replace(/:part:\d+$/, ""), date };
79
+ const entry = owner.get(doc.id);
80
+ entry.waiting.delete(doc.id);
81
+ touched.add(entry);
82
+ // Part of a new layout is on the server: until the entry settles, its old count no
83
+ // longer says what to remove, so a run cut short here leaves 0 (list next time).
84
+ if (entry.probe)
85
+ state.parts[entry.base] = 0;
86
+ }
87
+ for (const { doc, error } of result.rejected) {
88
+ report.rejected.push({ id: doc.id, message: `${error.code}: ${error.message}` });
89
+ const entry = owner.get(doc.id);
90
+ entry.failed = true;
91
+ touched.add(entry);
92
+ }
93
+ for (const entry of touched)
94
+ if (entry.waiting.size === 0 && !entry.failed)
95
+ await settle(ns, state, entry, report, held);
96
+ saveState(opts.stateFile, state);
97
+ log(`Uploaded ${report.documents} documents (${formatBytes(report.bytes)})`);
98
+ };
99
+ try {
100
+ const files = newestFirst(opts.files);
101
+ for (const file of files)
102
+ await visit(file);
103
+ await drain();
104
+ // Forget the stamps of transcripts that were deleted.
105
+ const present = new Set(files.map((f) => f.path));
106
+ for (const path of Object.keys(state.files))
107
+ if (!present.has(path))
108
+ delete state.files[path];
109
+ }
110
+ finally {
111
+ // Accepted batches are already saved; this keeps the probes and stamps of a cut-short run.
112
+ if (!dryRun)
113
+ saveState(opts.stateFile, state);
114
+ }
115
+ return report;
116
+ async function visit(file) {
117
+ if (isStamped(state, file.path, file.stamp)) {
118
+ report.unchanged++;
119
+ return;
120
+ }
121
+ let docs;
122
+ let base;
123
+ try {
124
+ const transcript = file.read();
125
+ base = baseId(transcript);
126
+ docs = transcript.messages.length > 0 ? toDocuments(transcript, projectName(transcript.cwd)) : [];
127
+ }
128
+ catch (err) {
129
+ log(`Skipped ${file.path}: ${err instanceof Error ? err.message : String(err)}`);
130
+ return;
131
+ }
132
+ // Two files of one session (a session copied between projects), even in different
133
+ // layouts: the most recently modified wins. The other is stamped too, so a later run,
134
+ // which skips the stamped winner, does not upload it over the winner; it uploads again
135
+ // only once it changes.
136
+ if (produced.has(base)) {
137
+ if (!dryRun)
138
+ state.files[file.path] = file.stamp;
139
+ report.unchanged++;
140
+ return;
141
+ }
142
+ produced.add(base);
143
+ const changed = docs.filter((d) => state.documents[d.id] !== d.metadata.content_hash);
144
+ const entry = {
145
+ path: file.path,
146
+ stamp: file.stamp,
147
+ base,
148
+ count: docs.length,
149
+ // First sight included: the migration of older history may hold another layout.
150
+ probe: docs.length > 0 && state.parts[base] !== docs.length,
151
+ previous: state.parts[base],
152
+ waiting: new Set(changed.map((d) => d.id)),
153
+ failed: false,
154
+ };
155
+ if (changed.length === 0 && !entry.probe) {
156
+ if (!dryRun)
157
+ state.files[file.path] = file.stamp;
158
+ report.unchanged++;
159
+ return;
160
+ }
161
+ if (changed.length > 0)
162
+ report.sessions++;
163
+ if (dryRun) {
164
+ for (const d of changed)
165
+ report.planned.push({ id: d.id, bytes: Buffer.byteLength(d.text) });
166
+ report.documents += changed.length;
167
+ report.bytes += changed.reduce((n, d) => n + Buffer.byteLength(d.text), 0);
168
+ return;
169
+ }
170
+ if (changed.length === 0) {
171
+ await settle(ns, state, entry, report, held);
172
+ return;
173
+ }
174
+ for (const doc of changed) {
175
+ const size = Buffer.byteLength(doc.text);
176
+ if (queue.length >= BATCH_DOCUMENTS || (queue.length > 0 && queuedBytes + size > BATCH_BYTES))
177
+ await flush();
178
+ owner.set(doc.id, entry);
179
+ queue.push(doc);
180
+ queuedBytes += size;
181
+ }
182
+ }
183
+ }
184
+ /**
185
+ * Every document of the file is on the server: when the session's document count is new
186
+ * to the state, remove its older layout, record the count, then stamp the file. Deleting
187
+ * only now means a crash in between leaves a duplicate, never a gap.
188
+ */
189
+ async function settle(ns, state, entry, report, held) {
190
+ if (entry.probe) {
191
+ for (const id of await removeStaleParts(ns, entry.base, entry.count, await held(entry))) {
192
+ delete state.documents[id];
193
+ report.deleted++;
194
+ }
195
+ state.parts[entry.base] = entry.count;
196
+ }
197
+ state.files[entry.path] = entry.stamp;
198
+ }
199
+ /** Stat every file (skipping ones that vanished) and order newest first, so a cut-short run keeps the recent work. */
200
+ function newestFirst(files) {
201
+ const out = [];
202
+ for (const f of files) {
203
+ try {
204
+ const s = statSync(f.path);
205
+ out.push({ ...f, stamp: { size: s.size, mtimeMs: s.mtimeMs } });
206
+ }
207
+ catch {
208
+ // Removed since it was listed.
209
+ }
210
+ }
211
+ return out.sort((a, b) => b.stamp.mtimeMs - a.stamp.mtimeMs);
212
+ }
213
+ export function formatBytes(n) {
214
+ if (n < 1000)
215
+ return `${n} B`;
216
+ if (n < 1_000_000)
217
+ return `${(n / 1000).toFixed(1)} KB`;
218
+ return `${(n / 1_000_000).toFixed(1)} MB`;
219
+ }
@@ -0,0 +1,103 @@
1
+ // The parsed form of one agent session, shared by the sources and the renderer.
2
+ /** RFC 3339 UTC for a timestamp string or epoch number, or undefined. */
3
+ export function toIso(value) {
4
+ if (typeof value !== "string" && typeof value !== "number")
5
+ return undefined;
6
+ const ms = typeof value === "number" ? (value < 1e11 ? value * 1000 : value) : Date.parse(value);
7
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
8
+ }
9
+ /** Keeps the head and the tail of a long text (errors carry their cause at either end). */
10
+ export function clip(text, max) {
11
+ const t = text.trim();
12
+ if (t.length <= max)
13
+ return t;
14
+ const head = Math.floor(max * 0.6);
15
+ const tail = max - head;
16
+ return `${t.slice(0, head)}\n… [${t.length - max} characters omitted] …\n${t.slice(t.length - tail)}`;
17
+ }
18
+ /** One line of at most max characters. */
19
+ export function oneLine(text, max) {
20
+ const t = text.replace(/\s+/g, " ").trim();
21
+ return t.length <= max ? t : `${t.slice(0, max - 1)}…`;
22
+ }
23
+ // Images and inline binary have no text value; a data URI or a long unbroken base64 run is
24
+ // replaced by a marker. 200 characters of the base64 alphabet with no space, dot or dash is
25
+ // never prose, code or a path.
26
+ const DATA_URI = /data:[\w.+-]+\/[\w.+-]+;base64,[A-Za-z0-9+/=]+/g;
27
+ const BASE64_RUN = /[A-Za-z0-9+/]{200,}={0,2}/g;
28
+ export function dropBinary(text) {
29
+ return text.replace(DATA_URI, "[binary data]").replace(BASE64_RUN, (run) => (/[+/]/.test(run) || /\d/.test(run) ? "[binary data]" : run));
30
+ }
31
+ // Harness-injected context inside user and tool text, never typed by the user: Claude Code
32
+ // wraps it in <system-reminder>.
33
+ export function stripReminders(text) {
34
+ return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "");
35
+ }
36
+ /** Command shown for a shell call: argv ["bash", "-lc", "cmd"] becomes "cmd". */
37
+ export function shellCommand(command) {
38
+ if (typeof command === "string")
39
+ return command;
40
+ if (!Array.isArray(command) || !command.every((c) => typeof c === "string"))
41
+ return undefined;
42
+ const argv = command;
43
+ if (argv.length === 3 && /(^|\/)(ba|z)?sh$/.test(argv[0]) && /^-l?c$/.test(argv[1]))
44
+ return argv[2];
45
+ return argv.join(" ");
46
+ }
47
+ const COMMAND_MAX = 500;
48
+ const ARG_MAX = 200;
49
+ /**
50
+ * One line (a shell command may keep its own lines) for a tool call: what ran, on which
51
+ * path, with which pattern. File contents and patches are left out; they are in the repo.
52
+ */
53
+ export function summarizeTool(name, input) {
54
+ const i = (input && typeof input === "object" ? input : {});
55
+ const s = (key) => (typeof i[key] === "string" ? i[key] : undefined);
56
+ const cmd = shellCommand(i.command) ?? shellCommand(i.cmd);
57
+ switch (name) {
58
+ case "Bash":
59
+ case "shell":
60
+ case "shell_command":
61
+ case "exec_command":
62
+ case "local_shell":
63
+ case "container.exec":
64
+ return cmd ? `$ ${clip(cmd, COMMAND_MAX)}` : name;
65
+ case "Read":
66
+ case "Write":
67
+ case "Edit":
68
+ case "MultiEdit":
69
+ case "NotebookEdit":
70
+ case "view_image":
71
+ return `${name} ${s("file_path") ?? s("notebook_path") ?? s("path") ?? ""}`.trim();
72
+ case "Grep":
73
+ return `Grep "${oneLine(s("pattern") ?? "", ARG_MAX)}"${s("path") ? ` in ${s("path")}` : ""}${s("glob") ? ` (${s("glob")})` : ""}`;
74
+ case "Glob":
75
+ return `Glob ${s("pattern") ?? ""}${s("path") ? ` in ${s("path")}` : ""}`;
76
+ case "WebFetch":
77
+ return `WebFetch ${s("url") ?? ""}`.trim();
78
+ case "WebSearch":
79
+ case "web_search":
80
+ return `${name} "${oneLine(s("query") ?? "", ARG_MAX)}"`;
81
+ case "AskUserQuestion": {
82
+ const questions = Array.isArray(i.questions) ? i.questions : [];
83
+ return `AskUserQuestion: ${oneLine(questions.map((q) => String(q?.question ?? "")).join(" | "), ARG_MAX * 2)}`;
84
+ }
85
+ case "Task":
86
+ case "Agent":
87
+ return `${name}${s("subagent_type") ? ` (${s("subagent_type")})` : ""}: ${oneLine(s("description") ?? "", ARG_MAX)}`;
88
+ case "Skill":
89
+ return `Skill ${s("skill") ?? s("name") ?? ""}`.trim();
90
+ case "ExitPlanMode":
91
+ return name; // the plan follows as text
92
+ case "apply_patch":
93
+ return `apply_patch ${patchFiles(s("input") ?? s("patch") ?? (typeof input === "string" ? input : ""))}`.trim();
94
+ }
95
+ // Anything else (MCP tools, task lists): the name and its arguments, compact.
96
+ const args = input === undefined ? "" : typeof input === "string" ? input : JSON.stringify(input);
97
+ return args && args !== "{}" ? `${name} ${oneLine(args, ARG_MAX)}` : name;
98
+ }
99
+ /** "Update a.ts, Add b.ts" from an apply_patch body. */
100
+ export function patchFiles(patch) {
101
+ const files = [...patch.matchAll(/^\*\*\* (Add|Update|Delete) File: (.+)$/gm)].map((m) => `${m[1]} ${m[2].trim()}`);
102
+ return files.join(", ");
103
+ }
@@ -0,0 +1,139 @@
1
+ // Sending documents through the SDK client. The client retries 429, 5xx and network errors
2
+ // with backoff, honouring Retry-After (bounded by its maxRetries); what still fails here is
3
+ // either one bad document (sent again alone, then left for the next run) or a server or
4
+ // auth problem that stops the run.
5
+ import { ConareError } from "../index.js";
6
+ import { partId } from "./documents.js";
7
+ /** The API takes 1-100 documents per write; a byte budget keeps each request's embedding work small. */
8
+ export const BATCH_DOCUMENTS = 100;
9
+ export const BATCH_BYTES = 1_000_000;
10
+ /** Batches sent at once (sync.ts). */
11
+ export const UPLOADS_IN_FLIGHT = 4;
12
+ export const WRITE_TIMEOUT_MS = 120_000;
13
+ /** Groups documents in order into batches within both limits. */
14
+ export function batches(docs, maxDocs = BATCH_DOCUMENTS, maxBytes = BATCH_BYTES) {
15
+ const out = [];
16
+ let current = [];
17
+ let bytes = 0;
18
+ for (const doc of docs) {
19
+ const size = Buffer.byteLength(doc.text);
20
+ if (current.length > 0 && (current.length >= maxDocs || bytes + size > maxBytes)) {
21
+ out.push(current);
22
+ current = [];
23
+ bytes = 0;
24
+ }
25
+ current.push(doc);
26
+ bytes += size;
27
+ }
28
+ if (current.length > 0)
29
+ out.push(current);
30
+ return out;
31
+ }
32
+ /** A request the API refused because of what one of its documents holds. */
33
+ function isDocumentError(err) {
34
+ return err instanceof ConareError && (err.status === 400 || err.status === 413 || err.status === 422);
35
+ }
36
+ /**
37
+ * Write one batch. When the API refuses the batch for its content, each document is sent
38
+ * alone so one bad document does not hold back the others. Any other failure throws.
39
+ */
40
+ export async function sendBatch(ns, batch) {
41
+ const unchanged = (results) => results.filter((r) => r.result === "unchanged").length;
42
+ try {
43
+ return { accepted: batch, unchanged: unchanged(await ns.write(batch, { timeout: WRITE_TIMEOUT_MS })), rejected: [] };
44
+ }
45
+ catch (err) {
46
+ if (!isDocumentError(err))
47
+ throw err;
48
+ if (batch.length === 1)
49
+ return { accepted: [], unchanged: 0, rejected: [{ doc: batch[0], error: err }] };
50
+ }
51
+ const result = { accepted: [], unchanged: 0, rejected: [] };
52
+ for (const doc of batch) {
53
+ try {
54
+ result.unchanged += unchanged(await ns.write(doc, { timeout: WRITE_TIMEOUT_MS }));
55
+ result.accepted.push(doc);
56
+ }
57
+ catch (err) {
58
+ if (!isDocumentError(err))
59
+ throw err;
60
+ result.rejected.push({ doc, error: err });
61
+ }
62
+ }
63
+ return result;
64
+ }
65
+ /** Delete one document; false when it does not exist (404 document_not_found). */
66
+ export async function deleteIfPresent(ns, id) {
67
+ try {
68
+ await ns.delete(id);
69
+ return true;
70
+ }
71
+ catch (err) {
72
+ if (err instanceof ConareError && err.status === 404)
73
+ return false;
74
+ throw err;
75
+ }
76
+ }
77
+ /** Loop guard for the part probe; a 256 KB-per-part session would need to exceed 25 GB. */
78
+ const MAX_PARTS = 100_000;
79
+ const PART_ID = /^(.+):part:(\d{6})$/;
80
+ /** List every id in the namespace once and group them by session; an absent namespace holds nothing. */
81
+ export async function listLayouts(ns) {
82
+ const layouts = new Map();
83
+ try {
84
+ for await (const doc of ns.list({ limit: 100 })) {
85
+ const m = PART_ID.exec(doc.id);
86
+ const base = m ? m[1] : doc.id;
87
+ const held = layouts.get(base) ?? { whole: false, parts: [] };
88
+ if (m)
89
+ held.parts.push(Number(m[2]));
90
+ else
91
+ held.whole = true;
92
+ layouts.set(base, held);
93
+ }
94
+ }
95
+ catch (err) {
96
+ if (!(err instanceof ConareError && err.status === 404))
97
+ throw err;
98
+ }
99
+ return layouts;
100
+ }
101
+ /** The layout of a session this tool stored as `count` documents. */
102
+ export function heldAs(count) {
103
+ return count > 1 ? { whole: false, parts: Array.from({ length: count }, (_, i) => i + 1) } : { whole: true, parts: [] };
104
+ }
105
+ /**
106
+ * Remove what an earlier layout of a session left behind, once its k new documents are
107
+ * accepted. A session is stored as the single document <base> or as the parts
108
+ * <base>:part:000001..k (this tool and the migration of older history both write that):
109
+ * with parts, <base> is stale; otherwise every part is; with parts, those after k are.
110
+ *
111
+ * When the old layout is known (`held`: what this tool stored last, or a listing of the
112
+ * namespace), exactly its stale ids are deleted, gaps included. Otherwise the parts are
113
+ * probed from the first stale number until the first 404. Returns the ids deleted.
114
+ */
115
+ export async function removeStaleParts(ns, base, k, held) {
116
+ const deleted = [];
117
+ const remove = async (id) => {
118
+ if (await deleteIfPresent(ns, id))
119
+ deleted.push(id);
120
+ };
121
+ const firstStale = k > 1 ? k + 1 : 1;
122
+ if (held) {
123
+ if (k > 1 && held.whole)
124
+ await remove(base);
125
+ for (const n of [...held.parts].sort((a, b) => a - b))
126
+ if (n >= firstStale)
127
+ await remove(partId(base, n));
128
+ return deleted;
129
+ }
130
+ if (k > 1)
131
+ await remove(base);
132
+ for (let n = firstStale; n <= MAX_PARTS; n++) {
133
+ const id = partId(base, n);
134
+ if (!(await deleteIfPresent(ns, id)))
135
+ break;
136
+ deleted.push(id);
137
+ }
138
+ return deleted;
139
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.19.0";
1
+ export declare const VERSION = "0.20.0";
2
2
  /** A metadata value: string, number, boolean or an array of strings. */
3
3
  export type MetadataValue = string | number | boolean | string[];
4
4
  export type Metadata = Record<string, MetadataValue>;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
2
- export const VERSION = "0.19.0";
2
+ export const VERSION = "0.20.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  // ---- Errors ----------------------------------------------------------------
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
+ "bin": { "conare": "./dist/cli/main.js" },
8
9
  "exports": {
9
10
  ".": {
10
11
  "types": "./dist/index.d.ts",
@@ -14,8 +15,8 @@
14
15
  "files": ["dist"],
15
16
  "sideEffects": false,
16
17
  "scripts": {
17
- "build": "rm -rf dist && tsc -p tsconfig.json",
18
- "typecheck": "tsc -p tsconfig.json --noEmit",
18
+ "build": "rm -rf dist && tsc -p tsconfig.json && tsc -p tsconfig.cli.json && chmod +x dist/cli/main.js",
19
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.cli.json --noEmit",
19
20
  "test": "bun test",
20
21
  "prepublishOnly": "bun run build"
21
22
  },