conare 0.24.0 → 0.25.1

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.
package/README.md CHANGED
@@ -61,11 +61,12 @@ for await (const doc of docs.list()) {} // every document, page by page (
61
61
  await docs.delete("refunds"); // 404 document_not_found if it does not exist
62
62
  await docs.deleteMany(["a", "b"]); // up to 1000 ids in one call; missing ids are skipped. Returns the count
63
63
  await docs.deleteWhere({ team: "support" }); // every document matching the filter, whole documents. Returns the count
64
- await docs.uploadFile(bytes, "report.pdf"); // any file up to 512 MiB in one call: a PDF (one document per page), a .docx, a .pptx
65
- // (one per slide), an .xlsx (Markdown tables per sheet), CSV, text or images; scans are OCR'd.
66
- // Documents are <sourceId>:<fileId>:<part>; the same name (or { id }) again replaces them.
64
+ await docs.uploadFile(bytes, "report.pdf"); // any file up to 512 MiB in one call: a PDF, a .docx, a .pptx, an .xlsx
65
+ // (Markdown tables per sheet), CSV, text or images; scans are OCR'd.
66
+ // The file is one document, <sourceId>:<fileId>; each hit says its page,
67
+ // slide, sheet and rows or part. The same name (or { id }) again replaces it.
67
68
  // { user, metadata, type, wait } optional. Returns { state, fileId, ids, markdown, parts, ... }
68
- await docs.getFile("report.pdf"); // its state; once ready, its documents and parse
69
+ await docs.getFile("report.pdf"); // its state; once ready, its document and parse
69
70
  await docs.drop(); // delete the namespace and its documents (succeeds if already emptied; 404 namespace_not_found if never written)
70
71
 
71
72
  await conare.namespaces(); // [{ name, documents }]
@@ -73,7 +74,9 @@ await conare.namespaces({ prefix: "u7f3a9c-" }); // one user's namespaces
73
74
  ```
74
75
 
75
76
  Namespace names: 1-64 characters of `a-z 0-9 _ -`. Ids: up to 256 characters of
76
- `A-Z a-z 0-9 . _ : -`. Metadata values are strings, numbers, booleans or arrays of strings.
77
+ `A-Z a-z 0-9 . _ : -`. Metadata values are strings, numbers, booleans or arrays of strings. A
78
+ document's text is of any length within a write's 32 MiB; a long one is stored in parts and
79
+ searched, read, listed and deleted as one document.
77
80
 
78
81
  ### Query
79
82
 
@@ -263,8 +266,8 @@ a readable transcript with the prompts, the answers, one line per tool call, and
263
266
  output that succeeded, images and thinking are left out, and secrets (API keys, tokens, private
264
267
  keys, passwords) are replaced with `[REDACTED:<kind>]` before anything is sent. Ids are
265
268
  `claude:<session>`, `claude:<session>:agent:<agent>` for a subagent, and `codex:<rollout file
266
- name>`; a session over 250 KB is split into `<id>:part:000001`, `:part:000002`, and so on (one
267
- layout per session, never both). Metadata: `source` (`claude-code` or `codex`), `session_id`,
269
+ name>`; a session over 250 KB is sent as `<id>:part:000001`, `:part:000002`, and so on (one
270
+ layout per session, never both), so a sync sends only the parts that changed. Metadata: `source` (`claude-code` or `codex`), `session_id`,
268
271
  `agent_id`, `project`, `cwd`, `git_branch`, `started_at`, `date` (the last activity) and
269
272
  `content_hash`.
270
273
 
@@ -301,7 +304,7 @@ name is left alone, and that repository's sync stops with an error.
301
304
  bun install
302
305
  bun run build
303
306
  bun test # local fake API
304
- CONARE_API_KEY=sk-conare-... bun test # also runs test/live.test.ts against the real API
307
+ CONARE_BENCH_API_KEY=sk-conare-... bun test # also runs test/live.test.ts against the real API (a test organization's key)
305
308
  ```
306
309
 
307
310
  Releases: push a tag `sdk-v<version>` matching `package.json`; CI tests and publishes to npm.
package/dist/cli/args.js CHANGED
@@ -5,7 +5,9 @@ export const HELP = `Usage:
5
5
  conare sync github <owner/repo>... [opts] issues, PRs and markdown docs -> "<repo>-github", "<repo>-docs"
6
6
 
7
7
  Run it as npx conare … or bunx conare …. Only new or changed sessions, threads and docs are
8
- sent; secrets in sessions are redacted first.
8
+ sent; secrets are redacted first. To leave a project's sessions out, put its name (its git
9
+ repository's, else its directory's) on a line of ~/.conare/sync-exclude; sessions it already
10
+ uploaded stay until you delete them.
9
11
 
10
12
  Options:
11
13
  --dry-run count what would upload; upload nothing
@@ -11,6 +11,7 @@ export function resolvePaths(env = process.env, home = homedir()) {
11
11
  lockFile: join(dir, "sync.lock"),
12
12
  logFile: join(dir, "sync.log"),
13
13
  statusFile: join(dir, "sync-status.json"),
14
+ excludeFile: join(dir, "sync-exclude"),
14
15
  githubStateFile: join(dir, "github-state.json"),
15
16
  installRoot: join(dir, "sync"),
16
17
  claudeDir: env.CLAUDE_CONFIG_DIR || join(home, ".claude"),
@@ -26,6 +27,20 @@ export function readSavedKey(keyFile) {
26
27
  return undefined;
27
28
  }
28
29
  }
30
+ /**
31
+ * The projects in an exclude file: one name a line (a session's project is its git repository's name,
32
+ * else its directory's), blank lines and "#" comments ignored. No file: none.
33
+ */
34
+ export function readExcluded(file) {
35
+ let text;
36
+ try {
37
+ text = readFileSync(file, "utf8");
38
+ }
39
+ catch {
40
+ return new Set();
41
+ }
42
+ return new Set(text.split(/\r?\n/).map((l) => l.replace(/#.*/, "").trim()).filter(Boolean));
43
+ }
29
44
  export function saveKey(keyFile, key) {
30
45
  writePrivate(keyFile, `${JSON.stringify({ api_key: key }, null, 2)}\n`);
31
46
  }
@@ -1,11 +1,16 @@
1
1
  // Transcript → the documents sent to the namespace "sessions". Ids, parts and metadata are
2
- // the contract with the server (and with the migration of older history, which uses the
3
- // same ids).
2
+ // the contract with the server.
4
3
  import { createHash } from "node:crypto";
5
4
  import { render } from "./render.js";
6
5
  import { scrub } from "./scrub.js";
6
+ import { wellFormed } from "./transcript.js";
7
7
  export const NAMESPACE = "sessions";
8
- /** The API caps text at 256 KB; a part stays under this many UTF-8 bytes. */
8
+ /**
9
+ * A session is sent in parts of at most this many UTF-8 bytes, though the API takes one
10
+ * document of any length: a sync sends only the parts whose text changed, while one
11
+ * session document re-sent whole would rewrite every passage on every sync (its date
12
+ * changes each sync).
13
+ */
9
14
  export const PART_BYTES = 250_000;
10
15
  const METADATA_VALUE_BYTES = 4096;
11
16
  /** claude:<session>, claude:<session>:agent:<agent>, codex:<session>. */
@@ -21,15 +26,16 @@ export function partId(base, n) {
21
26
  function idSegment(value) {
22
27
  return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 160);
23
28
  }
24
- /** The documents for one transcript: one, or numbered parts when the text is too large. */
29
+ /** The documents for one transcript: one, or numbered parts of at most PART_BYTES each. */
25
30
  export function toDocuments(t, project) {
26
- const text = scrub(render(t, project));
31
+ // Well-formed: a lone surrogate would go out as a "\udXXX" escape, which the API refuses.
32
+ const text = wellFormed(scrub(render(t, project)));
27
33
  const parts = splitText(text, PART_BYTES);
28
34
  const base = baseId(t);
29
35
  const shared = {};
30
36
  // Metadata is scrubbed like the text: a path or branch name can hold a secret too.
31
37
  const set = (key, value) => {
32
- const clean = value && scrub(value);
38
+ const clean = value && wellFormed(scrub(value));
33
39
  if (clean && Buffer.byteLength(clean) <= METADATA_VALUE_BYTES)
34
40
  shared[key] = clean;
35
41
  };
@@ -9,7 +9,7 @@ const MAX_WAIT_MS = 15 * 60 * 1000;
9
9
  * Bounds one request, body included: a stall before the response is retried, one while reading
10
10
  * the body ends the run; either way a hung connection never holds the run (and its lock) forever.
11
11
  */
12
- export const REQUEST_TIMEOUT_MS = 120_000;
12
+ const REQUEST_TIMEOUT_MS = 120_000;
13
13
  export class GitHubError extends Error {
14
14
  status;
15
15
  constructor(status, message) {
@@ -26,14 +26,12 @@ export class GitHub {
26
26
  base;
27
27
  graphqlURL;
28
28
  sleep;
29
- timeoutMs;
30
29
  constructor(token, options = {}) {
31
30
  this.token = token;
32
31
  this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
33
32
  this.base = (options.baseURL ?? API).replace(/\/+$/, "");
34
33
  this.graphqlURL = options.graphqlURL ?? `${this.base}/graphql`;
35
34
  this.sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
36
- this.timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
37
35
  }
38
36
  async send(url, init = {}) {
39
37
  for (let attempt = 1;; attempt++) {
@@ -43,7 +41,7 @@ export class GitHub {
43
41
  try {
44
42
  res = await this.fetchFn(url, {
45
43
  ...init,
46
- signal: AbortSignal.timeout(this.timeoutMs),
44
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
47
45
  headers: {
48
46
  Accept: "application/vnd.github+json",
49
47
  Authorization: `Bearer ${this.token}`,
@@ -2,12 +2,12 @@
2
2
  // conare-docs (build_corpus.py, gs://conare-results/pointer/corpus-2026-10-02/): a thread is
3
3
  // one document "pr-<n>" / "issue-<n>" in "<repo>-github" (head line, state line, body, then
4
4
  // every kept comment in time order); a markdown file is one document in "<repo>-docs" whose id
5
- // is its path with / as : and whose text starts with the path. Pure: no network.
5
+ // is its path with / as : and whose text starts with the path. Text and title pass scrub() first, as a
6
+ // session's do: people paste tokens into issues and docs. Pure: no network.
6
7
  import { createHash } from "node:crypto";
8
+ import { scrub } from "../scrub.js";
7
9
  /** Bots whose comments are review findings agents answered; other bots are CI noise. */
8
10
  export const KEEP_BOTS = new Set(["greptile-apps[bot]", "claude[bot]"]);
9
- /** Bytes; the API takes 256 KiB per text. */
10
- export const MAX_TEXT_BYTES = 250_000;
11
11
  /** Greptile's appended summary, HTML comments and badge images removed; blank runs collapsed. */
12
12
  export function clean(s) {
13
13
  let t = (s ?? "").split("<!-- greptile_comment -->")[0];
@@ -19,16 +19,6 @@ export function clean(s) {
19
19
  export function kept(c) {
20
20
  return c.user?.type !== "Bot" || KEEP_BOTS.has(c.user.login);
21
21
  }
22
- /** At most MAX_TEXT_BYTES of UTF-8, cut at a character boundary, marked "[truncated]". */
23
- export function fit(text, max = MAX_TEXT_BYTES) {
24
- const buf = Buffer.from(text, "utf8");
25
- if (buf.length <= max)
26
- return text;
27
- let end = max;
28
- while (end > 0 && (buf[end] & 0xc0) === 0x80)
29
- end--;
30
- return `${buf.toString("utf8", 0, end)}\n[truncated]`;
31
- }
32
22
  /** The thread a comment belongs to. */
33
23
  export function commentNumber(c) {
34
24
  const url = c.issue_url ?? c.pull_request_url;
@@ -53,7 +43,7 @@ export function threadDocument(repo, issue, comments) {
53
43
  .sort(compareTuples);
54
44
  const parts = [head, clean(issue.body), ...entries.map(([at, who, where, body]) => `--- ${who} on ${at.slice(0, 10)}${where}:\n${clean(body)}`)];
55
45
  const metadata = {
56
- title: issue.title,
46
+ title: scrub(issue.title),
57
47
  author,
58
48
  date: issue.created_at,
59
49
  updated_at: issue.updated_at,
@@ -66,7 +56,7 @@ export function threadDocument(repo, issue, comments) {
66
56
  };
67
57
  if (merged)
68
58
  metadata.merged_at = merged;
69
- return { id: threadId(issue), text: fit(parts.filter(Boolean).join("\n\n")), metadata };
59
+ return { id: threadId(issue), text: scrub(parts.filter(Boolean).join("\n\n")), metadata };
70
60
  }
71
61
  // Python's tuple order: created_at, then login, then where, then body.
72
62
  function compareTuples(a, b) {
@@ -102,11 +92,12 @@ export function docTitle(path, text) {
102
92
  export function docDocument(repo, branch, f) {
103
93
  if (!f.text.trim())
104
94
  return undefined;
95
+ const text = scrub(f.text);
105
96
  return {
106
97
  id: docId(f.path),
107
- text: fit(`${f.path}\n\n${f.text}`),
98
+ text: `${f.path}\n\n${text}`,
108
99
  metadata: {
109
- title: docTitle(f.path, f.text),
100
+ title: docTitle(f.path, text),
110
101
  author: f.author,
111
102
  date: f.date,
112
103
  path: f.path,
package/dist/cli/main.js CHANGED
@@ -9,7 +9,7 @@ import { homedir } from "node:os";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { Conare, ConareError, VERSION } from "../index.js";
11
11
  import { HELP, parseArgs, repoNamespace } from "./args.js";
12
- import { readSavedKey, resolvePaths, saveKey } from "./config.js";
12
+ import { readExcluded, readSavedKey, resolvePaths, saveKey } from "./config.js";
13
13
  import { GitHub, GitHubError, githubToken } from "./github/api.js";
14
14
  import { loadGitHubState, saveGitHubState, syncRepo } from "./github/sync.js";
15
15
  import { PASSED_ENV, installCopy, installSchedule, installedSchedule, pruneVersions, stableRuntime, uninstallSchedule } from "./schedule.js";
@@ -83,7 +83,7 @@ async function main(argv) {
83
83
  return install(args, paths, say, fail);
84
84
  }
85
85
  if (args.dryRun)
86
- return (await syncSessions(args, paths, apiKey, say, fail)).code; // writes nothing: no lock, no record
86
+ return syncSessions(args, paths, apiKey, say, fail); // writes nothing: no lock, no record
87
87
  const release = acquireLock(paths.lockFile);
88
88
  if (!release) {
89
89
  if (!args.quiet)
@@ -91,7 +91,7 @@ async function main(argv) {
91
91
  return args.quiet ? 0 : INCOMPLETE;
92
92
  }
93
93
  try {
94
- return (await syncSessions(args, paths, apiKey, say, fail)).code;
94
+ return await syncSessions(args, paths, apiKey, say, fail);
95
95
  }
96
96
  finally {
97
97
  release();
@@ -151,12 +151,15 @@ async function syncSessions(args, paths, apiKey, say, fail) {
151
151
  account: client ? accountOf(client.baseURL, apiKey) : "",
152
152
  client: args.dryRun ? undefined : client,
153
153
  log: say,
154
+ exclude: readExcluded(paths.excludeFile),
154
155
  });
156
+ if (report.excluded > 0)
157
+ say(`Left out ${report.excluded} sessions of the projects in ${tilde(paths.excludeFile)}.`);
155
158
  if (args.dryRun) {
156
159
  for (const p of report.planned)
157
160
  say(` ${p.id} ${formatBytes(p.bytes)}`);
158
161
  say(`Would upload ${report.documents} documents from ${report.sessions} sessions (${formatBytes(report.bytes)}). ${report.unchanged} unchanged.`);
159
- return { code: 0 };
162
+ return 0;
160
163
  }
161
164
  for (const r of report.rejected)
162
165
  fail(`Not accepted, tried again next run: ${r.id}: ${r.message}`);
@@ -180,7 +183,7 @@ async function syncSessions(args, paths, apiKey, say, fail) {
180
183
  code = INCOMPLETE;
181
184
  }
182
185
  else {
183
- const detail = err instanceof ConareError ? `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})` : String(err);
186
+ const detail = err instanceof ConareError ? apiDetail(err) : String(err);
184
187
  error = `Sync stopped: ${detail}`;
185
188
  fail(`${error}. What was uploaded is saved; the rest is tried next run.`);
186
189
  code = err instanceof ConareError ? INCOMPLETE : 1; // anything else is a bug or a broken machine
@@ -196,7 +199,7 @@ async function syncSessions(args, paths, apiKey, say, fail) {
196
199
  deleted: report?.deleted ?? 0,
197
200
  ...(error ? { error } : {}),
198
201
  }, report?.newest);
199
- return { code };
202
+ return code;
200
203
  }
201
204
  async function syncGitHub(args, paths, apiKey, say, fail) {
202
205
  const token = githubToken();
@@ -252,11 +255,7 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
252
255
  fail(`The API key was refused (${err.status} ${err.code}).`);
253
256
  return AUTH_FAILED;
254
257
  }
255
- const detail = err instanceof ConareError
256
- ? `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})`
257
- : err instanceof GitHubError || err instanceof Error
258
- ? err.message
259
- : String(err);
258
+ const detail = err instanceof ConareError ? apiDetail(err) : err instanceof Error ? err.message : String(err);
260
259
  fail(`${repo}: sync stopped: ${detail}. The state is unchanged; the next run tries again.`);
261
260
  code = err instanceof ConareError || err instanceof GitHubError ? (code === 1 ? 1 : INCOMPLETE) : 1;
262
261
  }
@@ -267,6 +266,10 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
267
266
  }
268
267
  return code;
269
268
  }
269
+ /** "<message> (<status or code>, request <id>)". */
270
+ function apiDetail(err) {
271
+ return `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})`;
272
+ }
270
273
  function tilde(path) {
271
274
  const home = homedir();
272
275
  return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
package/dist/cli/scrub.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // [REDACTED:<kind>]. Specific key formats run before the generic rules, and a redaction
4
4
  // marker never matches again, so scrub(scrub(x)) === scrub(x).
5
5
  const hasDigit = (s) => /\d/.test(s);
6
- const REFERENCE = /^[$%{<([~/.#*]|\(|\$\{|\{\{|->|::/; // $VAR, %VAR%, {{x}}, <token>, [REDACTED:…], paths, calls
6
+ const REFERENCE = /^[$%{<([~/.#*]|->|::/; // $VAR, %VAR%, {{x}}, <token>, [REDACTED:…], paths, calls
7
7
  const DOTTED = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)+$/; // process.env.TOKEN, config.auth.token
8
8
  const CODE = /[([]/; // readPassword(prompt), os.environ["TOKEN"]
9
9
  // GITHUB_TOKEN, YOUR_TOKEN_HERE: an underscore makes it a variable name; a bare all-caps word
@@ -30,8 +30,8 @@
30
30
  // - isSidechain records in a parent file are subagent turns (older versions wrote them
31
31
  // inline): rendered under "Subagent" headings so they do not read as the user's words.
32
32
  // - Subagent transcripts agent-acompact-* and agent-aprompt_* (compaction and prompt
33
- // suggestion) restate the parent conversation: skipped. Known from the retired CLI;
34
- // none exist in the transcripts this was checked against.
33
+ // suggestion), which Claude Code writes beside a session's own subagents, restate the
34
+ // parent conversation: skipped.
35
35
  // Dropped from the retired CLI: the 50-character minimum turn length, the "narration"
36
36
  // filter ("Let me ..."), folding short prompts into the previous round, and the owner's
37
37
  // custom tag list (vibe-rules, good-behaviour, ...). They were content heuristics that lost
package/dist/cli/state.js CHANGED
@@ -33,8 +33,8 @@ export function saveState(path, state) {
33
33
  writePrivate(path, JSON.stringify(state));
34
34
  }
35
35
  /** True when the file is unchanged since all of its documents reached the server. */
36
- export function isStamped(state, path, stat) {
37
- const s = state.files[path];
36
+ export function isStamped(files, path, stat) {
37
+ const s = files[path];
38
38
  return !!s && s.size === stat.size && s.mtimeMs === stat.mtimeMs;
39
39
  }
40
40
  const STALE_LOCK_MS = 60 * 60 * 1000;
@@ -4,6 +4,9 @@
4
4
  import { appendFileSync, mkdirSync, readFileSync, statSync } from "node:fs";
5
5
  import { dirname } from "node:path";
6
6
  import { writePrivate } from "./config.js";
7
+ import { displayTime } from "./render.js";
8
+ import { isStamped } from "./state.js";
9
+ import { oneLine } from "./transcript.js";
7
10
  /** `conare sync status` fails when the last success is older than this. */
8
11
  export const MAX_SUCCESS_AGE_MS = 60 * 60 * 1000;
9
12
  export function readStatus(file) {
@@ -17,8 +20,11 @@ export function readStatus(file) {
17
20
  }
18
21
  /** The line a run adds to the log. */
19
22
  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)}` : ""}`;
23
+ return `${run.at} sync sessions ${run.ok ? "ok" : "FAILED"}: ${counts(run)}${run.error ? `: ${oneLine(run.error, 500)}` : ""}`;
24
+ }
25
+ /** "uploaded 3, skipped 15120, failed 0, deleted 1, 4.1 s". */
26
+ function counts(run) {
27
+ return `uploaded ${run.uploaded}, skipped ${run.skipped}, failed ${run.failed}, deleted ${run.deleted}, ${(run.durationMs / 1000).toFixed(1)} s`;
22
28
  }
23
29
  /** Append the run to the log and the status file. Never throws: recording must not fail a sync. */
24
30
  export function recordRun(files, run, newest) {
@@ -61,8 +67,7 @@ export function unsyncedTranscripts(paths, stamps, before) {
61
67
  }
62
68
  if (stat.mtimeMs >= before)
63
69
  continue; // the next run reads it
64
- const s = stamps[path];
65
- if (!s || s.size !== stat.size || s.mtimeMs !== stat.mtimeMs)
70
+ if (!isStamped(stamps, path, stat))
66
71
  out.push(path);
67
72
  }
68
73
  return out;
@@ -84,9 +89,9 @@ export function readStamps(stateFile) {
84
89
  export function describeStatus(status, now, schedule, unsynced = []) {
85
90
  const lines = [];
86
91
  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");
92
+ lines.push(run ? `Last run: ${when(run.at, now)}, ${run.ok ? "ok" : "failed"}: ${counts(run)}` : "Last run: never");
88
93
  if (run?.error)
89
- lines.push(` ${oneLine(run.error)}`);
94
+ lines.push(` ${oneLine(run.error, 500)}`);
90
95
  lines.push(`Last success: ${status.lastSuccessAt ? when(status.lastSuccessAt, now) : "never"}`);
91
96
  const newest = status.newestSession;
92
97
  lines.push(`Newest upload: ${newest ? `${newest.id}, last activity ${when(newest.date, now)}` : "none recorded"}`);
@@ -105,7 +110,7 @@ export function when(iso, now) {
105
110
  const t = Date.parse(iso);
106
111
  if (!Number.isFinite(t))
107
112
  return iso;
108
- return `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC (${age(now - t)})`;
113
+ return `${displayTime(iso)} (${age(now - t)})`;
109
114
  }
110
115
  export function age(ms) {
111
116
  if (ms < 0)
@@ -120,6 +125,3 @@ export function age(ms) {
120
125
  return `${h} h ago`;
121
126
  return `${Math.floor(h / 24)} days ago`;
122
127
  }
123
- function oneLine(s) {
124
- return s.replace(/\s+/g, " ").trim().slice(0, 500);
125
- }
package/dist/cli/sync.js CHANGED
@@ -18,7 +18,7 @@ export async function runSync(opts) {
18
18
  const ns = opts.client?.namespace(NAMESPACE);
19
19
  const log = opts.log ?? (() => { });
20
20
  const state = loadState(opts.stateFile, opts.account);
21
- const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, deleted: 0, rejected: [], planned: [] };
21
+ const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, excluded: 0, deleted: 0, rejected: [], planned: [] };
22
22
  // The layout the server holds for a session: what the state said this tool stored last;
23
23
  // on a fresh state (the first sync, after the migration of older history), or for a session
24
24
  // whose upload an earlier run cut short after some of its documents were accepted (0: any
@@ -114,7 +114,7 @@ export async function runSync(opts) {
114
114
  }
115
115
  return report;
116
116
  async function visit(file) {
117
- if (isStamped(state, file.path, file.stamp)) {
117
+ if (isStamped(state.files, file.path, file.stamp)) {
118
118
  report.unchanged++;
119
119
  return;
120
120
  }
@@ -122,8 +122,14 @@ export async function runSync(opts) {
122
122
  let base;
123
123
  try {
124
124
  const transcript = file.read();
125
+ const project = projectName(transcript.cwd);
126
+ // Not stamped: taken off the list, the project's sessions upload on the next run.
127
+ if (project !== undefined && opts.exclude?.has(project)) {
128
+ report.excluded++;
129
+ return;
130
+ }
125
131
  base = baseId(transcript);
126
- docs = transcript.messages.length > 0 ? toDocuments(transcript, projectName(transcript.cwd)) : [];
132
+ docs = transcript.messages.length > 0 ? toDocuments(transcript, project) : [];
127
133
  }
128
134
  catch (err) {
129
135
  log(`Skipped ${file.path}: ${err instanceof Error ? err.message : String(err)}`);
@@ -6,19 +6,31 @@ export function toIso(value) {
6
6
  const ms = typeof value === "number" ? (value < 1e11 ? value * 1000 : value) : Date.parse(value);
7
7
  return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
8
8
  }
9
+ /**
10
+ * An index at or below i that does not fall between the two halves of a surrogate pair (an
11
+ * emoji is two UTF-16 units): a cut there would leave a lone half, which the API refuses.
12
+ */
13
+ function charBoundary(t, i) {
14
+ const c = t.charCodeAt(i);
15
+ return i > 0 && c >= 0xdc00 && c <= 0xdfff && /[\uD800-\uDBFF]/.test(t[i - 1]) ? i - 1 : i;
16
+ }
9
17
  /** Keeps the head and the tail of a long text (errors carry their cause at either end). */
10
18
  export function clip(text, max) {
11
19
  const t = text.trim();
12
20
  if (t.length <= max)
13
21
  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)}`;
22
+ const head = charBoundary(t, Math.floor(max * 0.6));
23
+ const from = charBoundary(t, t.length - (max - Math.floor(max * 0.6)));
24
+ return `${t.slice(0, head)}\n… [${from - head} characters omitted] …\n${t.slice(from)}`;
17
25
  }
18
26
  /** One line of at most max characters. */
19
27
  export function oneLine(text, max) {
20
28
  const t = text.replace(/\s+/g, " ").trim();
21
- return t.length <= max ? t : `${t.slice(0, max - 1)}…`;
29
+ return t.length <= max ? t : `${t.slice(0, charBoundary(t, max - 1))}…`;
30
+ }
31
+ /** The text with any lone surrogate as U+FFFD (String.prototype.toWellFormed, which Node 18 lacks). */
32
+ export function wellFormed(text) {
33
+ return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
22
34
  }
23
35
  // Images and inline binary have no text value; a data URI or a long unbroken base64 run is
24
36
  // replaced by a marker. 200 characters of the base64 alphabet with no space, dot or dash is
@@ -34,7 +46,7 @@ export function stripReminders(text) {
34
46
  return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "");
35
47
  }
36
48
  /** Command shown for a shell call: argv ["bash", "-lc", "cmd"] becomes "cmd". */
37
- export function shellCommand(command) {
49
+ function shellCommand(command) {
38
50
  if (typeof command === "string")
39
51
  return command;
40
52
  if (!Array.isArray(command) || !command.every((c) => typeof c === "string"))
@@ -97,7 +109,7 @@ export function summarizeTool(name, input) {
97
109
  return args && args !== "{}" ? `${name} ${oneLine(args, ARG_MAX)}` : name;
98
110
  }
99
111
  /** "Update a.ts, Add b.ts" from an apply_patch body. */
100
- export function patchFiles(patch) {
112
+ function patchFiles(patch) {
101
113
  const files = [...patch.matchAll(/^\*\*\* (Add|Update|Delete) File: (.+)$/gm)].map((m) => `${m[1]} ${m[2].trim()}`);
102
114
  return files.join(", ");
103
115
  }
@@ -9,7 +9,7 @@ export const BATCH_DOCUMENTS = 100;
9
9
  export const BATCH_BYTES = 1_000_000;
10
10
  /** Batches sent at once (sync.ts). */
11
11
  export const UPLOADS_IN_FLIGHT = 4;
12
- export const WRITE_TIMEOUT_MS = 120_000;
12
+ const WRITE_TIMEOUT_MS = 120_000;
13
13
  /** Groups documents in order into batches within both limits. */
14
14
  export function batches(docs, maxDocs = BATCH_DOCUMENTS, maxBytes = BATCH_BYTES) {
15
15
  const out = [];
@@ -64,7 +64,7 @@ export async function sendBatch(ns, batch) {
64
64
  return result;
65
65
  }
66
66
  /** Delete one document; false when it does not exist (404 document_not_found). */
67
- export async function deleteIfPresent(ns, id) {
67
+ async function deleteIfPresent(ns, id) {
68
68
  try {
69
69
  await ns.delete(id);
70
70
  return true;
@@ -75,7 +75,7 @@ export async function deleteIfPresent(ns, id) {
75
75
  throw err;
76
76
  }
77
77
  }
78
- /** Loop guard for the part probe; a 256 KB-per-part session would need to exceed 25 GB. */
78
+ /** Loop guard for the part probe; a session in parts of PART_BYTES would need to exceed 25 GB. */
79
79
  const MAX_PARTS = 100_000;
80
80
  const PART_ID = /^(.+):part:(\d{6})$/;
81
81
  /** List every id in the namespace once and group them by session; an absent namespace holds nothing. */
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.24.0";
1
+ export declare const VERSION = "0.25.1";
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>;
@@ -80,7 +80,7 @@ export type FileType = "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt"
80
80
  export interface PictureWithoutText {
81
81
  /** A deck's: the slide it is on. */
82
82
  slide?: number;
83
- /** Its number in reading order (per slide in a deck), as the `image` of its documents would be. */
83
+ /** Its number in reading order (per slide in a deck), as its part's `image` would be. */
84
84
  image: number;
85
85
  /** A Word document's: the headings it sits under. */
86
86
  heading?: string;
@@ -178,7 +178,7 @@ export interface FileUpload {
178
178
  parts: ParsePart[];
179
179
  /** The type it was read as: an image of any format is `image`. */
180
180
  type: "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "image";
181
- /** The documents it made, in reading order. */
181
+ /** The file's one document, `<sourceId>:<fileId>` (a file uploaded before 2026-10-25 keeps one per part until uploaded again). */
182
182
  ids: string[];
183
183
  /** A PDF's pages (null for any other file). */
184
184
  pages: number | null;
@@ -190,7 +190,7 @@ export interface FileUpload {
190
190
  slidesWithoutText: number[];
191
191
  /** PDF or image pages read by OCR; stored like the rest. */
192
192
  pagesOcr: number;
193
- /** Pictures of a Word document or deck read by OCR, each a document of its own. */
193
+ /** Pictures of a Word document or deck read by OCR, each a part of the file's document. */
194
194
  imagesOcr: number;
195
195
  /** Pictures of a Word document or deck OCR did not turn into text, each with where it is and why. */
196
196
  imagesWithoutText: PictureWithoutText[];
@@ -203,7 +203,7 @@ export interface FileUpload {
203
203
  * again (`ocrPending`). `ready`: every document is stored. `failed`: the parse failed (`error`).
204
204
  */
205
205
  state: "queued" | "parsing" | "ocr" | "ready" | "failed";
206
- /** The files source of the namespace (and user): its documents are `<sourceId>:<fileId>:<part>`. */
206
+ /** The files source of the namespace (and user): the file's document is `<sourceId>:<fileId>`. */
207
207
  sourceId: string | null;
208
208
  /** Everything the file stored no text for, in one place (`pagesWithoutText`, `slidesWithoutText` and `imagesWithoutText` say the same). */
209
209
  withoutText: WithoutText;
@@ -243,7 +243,10 @@ export interface DocumentSummary {
243
243
  }
244
244
  export interface QueryResult {
245
245
  id: string;
246
- /** The best matching passage of the document. */
246
+ /**
247
+ * The passages of the document that answer, best first: its best matching passage and up to two more that
248
+ * match nearly as well. Passages that do not follow each other in the document are joined by a line holding only `…`.
249
+ */
247
250
  text: string;
248
251
  /** Higher is better: the reranker's score when `reranked`, else the fused rank score. The two do not compare. */
249
252
  score: number;
@@ -282,6 +285,12 @@ export interface NamespaceInfo {
282
285
  embeddingModel: string;
283
286
  /** The model that reranks its queries. */
284
287
  rerankModel: string;
288
+ /** When it was created (ISO 8601); before 2026-10-18, when its oldest document was written. */
289
+ createdAt: string | null;
290
+ /** Its last write; null when it has none to report. */
291
+ updatedAt: string | null;
292
+ /** Its last query, recorded at most once a minute; null when not queried since 2026-10-18. */
293
+ lastQueryAt: string | null;
285
294
  }
286
295
  export interface RerankResult {
287
296
  index: number;
@@ -474,7 +483,7 @@ export interface ConareOptions {
474
483
  baseURL?: string;
475
484
  /** Per-request timeout in milliseconds. Default 60000. */
476
485
  timeout?: number;
477
- /** Retries on 429, 5xx and network errors (a request that could create something twice only on 429 and 503). Default 2. */
486
+ /** Retries on 429, 5xx, 409 `idempotency_in_progress`, network errors and timeouts, every method: each write carries an Idempotency-Key, so a retry never applies it twice. Default 2. */
478
487
  maxRetries?: number;
479
488
  /** Custom fetch, e.g. for proxies or tests. */
480
489
  fetch?: (url: string, init: RequestInit) => Promise<Response>;
@@ -486,8 +495,8 @@ export interface ConareOptions {
486
495
  organization?: string;
487
496
  /**
488
497
  * Send JSON bodies of 8 KiB or more gzip-encoded (`Content-Encoding: gzip`). Default true where the
489
- * runtime has `CompressionStream` (Node 18+, Bun, browsers). A server that refuses gzip (400 or 415)
490
- * gets the request again as plain JSON, and no more gzip from this client.
498
+ * runtime has `CompressionStream` (Node 18+, Bun, browsers). A server that refuses gzip (415, or 400
499
+ * `invalid_json`) gets the request again as plain JSON, and no more gzip from this client.
491
500
  */
492
501
  gzip?: boolean;
493
502
  }
@@ -510,7 +519,7 @@ export interface RequestOptions {
510
519
  * writes nothing. A key is 1-255 visible ASCII characters, kept per API key; `write()` and `add()`
511
520
  * send batch `n` after the first as `<key>:<n>` and leave documents without an id to the API, which
512
521
  * derives their ids from the key; `deleteWhere()` sends round `n` after the first as `<key>:<n>`, and
513
- * so do `sources.documents.check()`, `delete()` and `restore()` with batch `n`; `imports.create()`
522
+ * so do `sources.documents.put()`, `check()`, `delete()` and `restore()` with batch `n`; `imports.create()`
514
523
  * sends its upload's parts as `<key>:part-<n>`, then `<key>:complete` and `<key>:import`.
515
524
  * The same key with another request is a 422 `idempotency_key_reused`.
516
525
  */
@@ -552,7 +561,7 @@ export declare class Conare {
552
561
  namespace(name: string): Namespace;
553
562
  /**
554
563
  * Every namespace in the organization (a scoped key: every one it reaches) with its document
555
- * count and models; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
564
+ * count, models and times; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
556
565
  */
557
566
  namespaces(options?: RequestOptions & {
558
567
  prefix?: string;
@@ -632,12 +641,13 @@ export declare class Namespace {
632
641
  * Store a file, up to 512 MiB, in one call: a PDF, a Word document (.docx), a PowerPoint deck (.pptx),
633
642
  * an Excel workbook (.xlsx), a CSV or TSV, a text or Markdown file, or an image (PNG, JPEG, WebP,
634
643
  * TIFF). Say its type with `type`: it is read as that type, and bytes of another type are refused (415)
635
- * rather than misread; without it the type comes from the bytes, then the name. It is parsed into one
636
- * document per PDF page, image page, slide, Word part or worksheet part, each `<sourceId>:<fileId>:<part>`
637
- * (`sourceId` is the namespace's files source) with `file`, `file_id`, `file_type` and its locator
638
- * (`page`, `part`, `slide`, `sheet`, `rows`) in metadata, beside `metadata` of your own. Pages without
639
- * a text layer are read by OCR. `fileId` defaults to the name in id characters; uploading the same one
640
- * again replaces every document it made, and the same bytes, name and options again answer
644
+ * rather than misread; without it the type comes from the bytes, then the name. The file is one
645
+ * document, `<sourceId>:<fileId>` (`sourceId` is the namespace's files source), with `file`, `file_id`
646
+ * and `file_type` in metadata beside `metadata` of your own. Its pages, slides, worksheet row ranges and
647
+ * Word parts are parts of it: a search hit says where it is (`page`, `sheet` and `rows`, `slide`, `part`,
648
+ * `heading` and `lines`, `frame`, `image`), and a search answers a page, slide or sheet's rows as a result of its own, its id `<sourceId>:<fileId>$<part>` (readable alone with `get`); a text, Markdown or Word file is one result, the file.
649
+ * Pages without a text layer are read by OCR. `fileId` defaults to the name in id characters; uploading
650
+ * the same one again replaces it, and the same bytes, name and options again answer
641
651
  * `result: "unchanged"`. `user` keeps the file to one of your users. The answer waits `wait` seconds
642
652
  * (default 60) for the parse: once `ready` it holds what `parse` answers (`markdown`, `parts`,
643
653
  * `withoutText`); before that it is `queued` or `parsing`, and `getFile` follows it.
@@ -648,17 +658,17 @@ export declare class Namespace {
648
658
  metadata?: Metadata;
649
659
  }): Promise<FileUpload>;
650
660
  /**
651
- * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its documents
661
+ * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its document
652
662
  * and its parse (`markdown`, `parts`). An id with no file throws 404 `file_not_found`.
653
663
  */
654
664
  getFile(fileId: string, options?: RequestOptions & {
655
665
  user?: string;
656
666
  }): Promise<FileStatus>;
657
667
  /**
658
- * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
668
+ * Hybrid search, reranked. One result per document: the passages of it that answer; `topK` documents when that
659
669
  * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
660
670
  * retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-1000) is how many of the
661
- * first passages the reranker ranks; unset, the first 20. `user` keeps the search to one user's documents and
671
+ * first passages the reranker ranks; unset, the first 100. `user` keeps the search to one user's documents and
662
672
  * `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
663
673
  * `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
664
674
  */
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.24.0";
2
+ export const VERSION = "0.25.1";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  // A JSON body this long or longer goes gzip-encoded: past the first ~14 KB a new connection may send,
@@ -159,7 +159,7 @@ export class Conare {
159
159
  }
160
160
  /**
161
161
  * Every namespace in the organization (a scoped key: every one it reaches) with its document
162
- * count and models; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
162
+ * count, models and times; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
163
163
  */
164
164
  async namespaces(options = {}) {
165
165
  const path = options.prefix ? `/namespaces?prefix=${encodeURIComponent(options.prefix)}` : "/namespaces";
@@ -169,6 +169,9 @@ export class Conare {
169
169
  documents: n.documents,
170
170
  embeddingModel: n.embedding_model,
171
171
  rerankModel: n.rerank_model,
172
+ createdAt: n.created_at ?? null,
173
+ updatedAt: n.updated_at ?? null,
174
+ lastQueryAt: n.last_query_at ?? null,
172
175
  }));
173
176
  }
174
177
  /**
@@ -282,8 +285,11 @@ export class Conare {
282
285
  const zipped = this.gzip && json !== undefined && json.length >= GZIP_MIN_BYTES ? await gzipText(json) : undefined;
283
286
  let res = await attempt(zipped);
284
287
  if (zipped !== undefined && (res.status === 400 || res.status === 415)) {
285
- // A server without gzip (a self-managed install before it) read the bytes as JSON.
286
- await res.body?.cancel();
288
+ // A server without gzip (a self-managed install before it) read the bytes as JSON: 415, or 400
289
+ // invalid_json. Any other 400 is the request's own, and goes once.
290
+ const text = await res.text();
291
+ if (res.status === 400 && !text.includes('"invalid_json"'))
292
+ return [res, text];
287
293
  res = await attempt(undefined);
288
294
  if (res.ok)
289
295
  this.gzip = false;
@@ -362,7 +368,7 @@ export class Namespace {
362
368
  seq: d.seq,
363
369
  if_version: d.ifVersion,
364
370
  })),
365
- }, { ...options, idempotencyKey: key && i > 0 ? `${key}:${i / BATCH_SIZE}` : key });
371
+ }, { ...options, idempotencyKey: stepKey(key, i / BATCH_SIZE) });
366
372
  body.ids.forEach((id, j) => {
367
373
  const r = body.results?.[j];
368
374
  const result = { id, version: body.versions?.[j] ?? null };
@@ -382,12 +388,13 @@ export class Namespace {
382
388
  * Store a file, up to 512 MiB, in one call: a PDF, a Word document (.docx), a PowerPoint deck (.pptx),
383
389
  * an Excel workbook (.xlsx), a CSV or TSV, a text or Markdown file, or an image (PNG, JPEG, WebP,
384
390
  * TIFF). Say its type with `type`: it is read as that type, and bytes of another type are refused (415)
385
- * rather than misread; without it the type comes from the bytes, then the name. It is parsed into one
386
- * document per PDF page, image page, slide, Word part or worksheet part, each `<sourceId>:<fileId>:<part>`
387
- * (`sourceId` is the namespace's files source) with `file`, `file_id`, `file_type` and its locator
388
- * (`page`, `part`, `slide`, `sheet`, `rows`) in metadata, beside `metadata` of your own. Pages without
389
- * a text layer are read by OCR. `fileId` defaults to the name in id characters; uploading the same one
390
- * again replaces every document it made, and the same bytes, name and options again answer
391
+ * rather than misread; without it the type comes from the bytes, then the name. The file is one
392
+ * document, `<sourceId>:<fileId>` (`sourceId` is the namespace's files source), with `file`, `file_id`
393
+ * and `file_type` in metadata beside `metadata` of your own. Its pages, slides, worksheet row ranges and
394
+ * Word parts are parts of it: a search hit says where it is (`page`, `sheet` and `rows`, `slide`, `part`,
395
+ * `heading` and `lines`, `frame`, `image`), and a search answers a page, slide or sheet's rows as a result of its own, its id `<sourceId>:<fileId>$<part>` (readable alone with `get`); a text, Markdown or Word file is one result, the file.
396
+ * Pages without a text layer are read by OCR. `fileId` defaults to the name in id characters; uploading
397
+ * the same one again replaces it, and the same bytes, name and options again answer
391
398
  * `result: "unchanged"`. `user` keeps the file to one of your users. The answer waits `wait` seconds
392
399
  * (default 60) for the parse: once `ready` it holds what `parse` answers (`markdown`, `parts`,
393
400
  * `withoutText`); before that it is `queued` or `parsing`, and `getFile` follows it.
@@ -406,7 +413,7 @@ export class Namespace {
406
413
  return toFileUpload(body);
407
414
  }
408
415
  /**
409
- * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its documents
416
+ * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its document
410
417
  * and its parse (`markdown`, `parts`). An id with no file throws 404 `file_not_found`.
411
418
  */
412
419
  async getFile(fileId, options = {}) {
@@ -415,10 +422,10 @@ export class Namespace {
415
422
  return { ...toFileUpload(body), name: body.name, uploadedAt: new Date(body.uploaded_at) };
416
423
  }
417
424
  /**
418
- * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
425
+ * Hybrid search, reranked. One result per document: the passages of it that answer; `topK` documents when that
419
426
  * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
420
427
  * retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-1000) is how many of the
421
- * first passages the reranker ranks; unset, the first 20. `user` keeps the search to one user's documents and
428
+ * first passages the reranker ranks; unset, the first 100. `user` keeps the search to one user's documents and
422
429
  * `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
423
430
  * `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
424
431
  */
@@ -495,7 +502,7 @@ export class Namespace {
495
502
  const key = options?.idempotencyKey;
496
503
  for (let round = 0;; round++) {
497
504
  // Each round is its own call (the same body deletes the next batch): its own key.
498
- const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { ...options, idempotencyKey: key && round > 0 ? `${key}:${round}` : key });
505
+ const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { ...options, idempotencyKey: stepKey(key, round) });
499
506
  deleted += out.deleted;
500
507
  if (!out.more)
501
508
  return deleted;
@@ -510,7 +517,7 @@ export class Namespace {
510
517
  async drop(options = {}) {
511
518
  const { force, ...rest } = options;
512
519
  const body = await this.client.request("DELETE", this.path(force ? "?force=true" : ""), undefined, rest);
513
- return { sourcesDeleted: body?.sources_deleted ?? [] };
520
+ return { sourcesDeleted: body.sources_deleted ?? [] };
514
521
  }
515
522
  }
516
523
  // ---- Sources ---------------------------------------------------------------
@@ -605,7 +612,7 @@ export class SourceDocuments {
605
612
  const all = Array.isArray(documents) ? documents : [documents];
606
613
  const out = [];
607
614
  for (let i = 0; i < all.length; i += BATCH_SIZE) {
608
- const body = await this.client.request("PUT", `/sources/${segment(sourceId)}/documents`, { run_id: options.runId, documents: all.slice(i, i + BATCH_SIZE).map(toWireCustomDocument) }, options);
615
+ const body = await this.client.request("PUT", `/sources/${segment(sourceId)}/documents`, { run_id: options.runId, documents: all.slice(i, i + BATCH_SIZE).map(toWireCustomDocument) }, { ...options, idempotencyKey: stepKey(options.idempotencyKey, i / BATCH_SIZE) });
609
616
  out.push(...body.results.map(toPushResult));
610
617
  }
611
618
  return out;
@@ -904,7 +911,6 @@ function toRun(r) {
904
911
  finishedAt: r.finished_at ? new Date(r.finished_at) : null,
905
912
  };
906
913
  }
907
- /** A random Idempotency-Key for one call (kept across its retries). */
908
914
  function base64(bytes) {
909
915
  let bin = "";
910
916
  for (const b of bytes)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.24.0",
3
+ "version": "0.25.1",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",