conare 0.25.0 → 0.26.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.
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
 
@@ -109,6 +112,18 @@ compare numbers, string bounds compare strings by their UTF-8 bytes, so ISO date
109
112
 
110
113
  `$ne` and `$nin` work in queries; a delete by filter with one answers 400 `invalid_filter`.
111
114
 
115
+
116
+ ### Grep
117
+
118
+ ```ts
119
+ const { matches, nextCursor } = await docs.grep("MAX_FILE_[A-Z]+", { limit: 20 });
120
+ await docs.grep({ query: "turbopufer", max_distance: 1, case_sensitive: false });
121
+ await docs.query("upload limits", { filter: { $text: { $regex: "(?i)max_file" } } });
122
+ ```
123
+
124
+ The documents whose text matches a regular expression, or nearly matches a spelling, with the lines that match, in id
125
+ order. `docs.create({ regexIndex: true })` before a namespace's first write makes it fast at any size.
126
+
112
127
  ### Embed and rerank
113
128
 
114
129
  ```ts
@@ -263,8 +278,8 @@ a readable transcript with the prompts, the answers, one line per tool call, and
263
278
  output that succeeded, images and thinking are left out, and secrets (API keys, tokens, private
264
279
  keys, passwords) are replaced with `[REDACTED:<kind>]` before anything is sent. Ids are
265
280
  `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`,
281
+ name>`; a session over 250 KB is sent as `<id>:part:000001`, `:part:000002`, and so on (one
282
+ layout per session, never both), so a sync sends only the parts that changed. Metadata: `source` (`claude-code` or `codex`), `session_id`,
268
283
  `agent_id`, `project`, `cwd`, `git_branch`, `started_at`, `date` (the last activity) and
269
284
  `content_hash`.
270
285
 
@@ -275,7 +290,8 @@ await sessions.query("why did we drop the Redis cache?", { filter: { project: "s
275
290
 
276
291
  It reads `~/.claude/projects` (or `$CLAUDE_CONFIG_DIR`) and `~/.codex/sessions` (or `$CODEX_HOME`).
277
292
  The key comes from `--key`, else `CONARE_API_KEY`, else `~/.conare/sync.json`. What the server
278
- already has is kept in `~/.conare/sync-state.json`, and one run at a time holds `~/.conare/sync.lock`.
293
+ already has is kept in `~/.conare/sync-state.json` and checked against the namespace's listing at the start of a run (what
294
+ the server lost goes up again), and one run at a time holds `~/.conare/sync.lock`.
279
295
  `--install` copies the command to `~/.conare/sync/<version>/`, checks the copy file by file, runs
280
296
  it once, and only then adds a launchd agent (`ai.conare.sync`) on macOS or a systemd user timer on
281
297
  Linux. Every run adds a line to `~/.conare/sync.log` (uploaded, skipped and failed counts, duration).
@@ -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}`,
@@ -8,8 +8,6 @@ import { createHash } from "node:crypto";
8
8
  import { scrub } from "../scrub.js";
9
9
  /** Bots whose comments are review findings agents answered; other bots are CI noise. */
10
10
  export const KEEP_BOTS = new Set(["greptile-apps[bot]", "claude[bot]"]);
11
- /** Bytes; the API takes 256 KiB per text. */
12
- export const MAX_TEXT_BYTES = 250_000;
13
11
  /** Greptile's appended summary, HTML comments and badge images removed; blank runs collapsed. */
14
12
  export function clean(s) {
15
13
  let t = (s ?? "").split("<!-- greptile_comment -->")[0];
@@ -21,16 +19,6 @@ export function clean(s) {
21
19
  export function kept(c) {
22
20
  return c.user?.type !== "Bot" || KEEP_BOTS.has(c.user.login);
23
21
  }
24
- /** At most MAX_TEXT_BYTES of UTF-8, cut at a character boundary, marked "[truncated]". */
25
- export function fit(text, max = MAX_TEXT_BYTES) {
26
- const buf = Buffer.from(text, "utf8");
27
- if (buf.length <= max)
28
- return text;
29
- let end = max;
30
- while (end > 0 && (buf[end] & 0xc0) === 0x80)
31
- end--;
32
- return `${buf.toString("utf8", 0, end)}\n[truncated]`;
33
- }
34
22
  /** The thread a comment belongs to. */
35
23
  export function commentNumber(c) {
36
24
  const url = c.issue_url ?? c.pull_request_url;
@@ -68,7 +56,7 @@ export function threadDocument(repo, issue, comments) {
68
56
  };
69
57
  if (merged)
70
58
  metadata.merged_at = merged;
71
- return { id: threadId(issue), text: fit(scrub(parts.filter(Boolean).join("\n\n"))), metadata };
59
+ return { id: threadId(issue), text: scrub(parts.filter(Boolean).join("\n\n")), metadata };
72
60
  }
73
61
  // Python's tuple order: created_at, then login, then where, then body.
74
62
  function compareTuples(a, b) {
@@ -107,7 +95,7 @@ export function docDocument(repo, branch, f) {
107
95
  const text = scrub(f.text);
108
96
  return {
109
97
  id: docId(f.path),
110
- text: fit(`${f.path}\n\n${text}`),
98
+ text: `${f.path}\n\n${text}`,
111
99
  metadata: {
112
100
  title: docTitle(f.path, text),
113
101
  author: f.author,
package/dist/cli/main.js CHANGED
@@ -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();
@@ -159,7 +159,7 @@ async function syncSessions(args, paths, apiKey, say, fail) {
159
159
  for (const p of report.planned)
160
160
  say(` ${p.id} ${formatBytes(p.bytes)}`);
161
161
  say(`Would upload ${report.documents} documents from ${report.sessions} sessions (${formatBytes(report.bytes)}). ${report.unchanged} unchanged.`);
162
- return { code: 0 };
162
+ return 0;
163
163
  }
164
164
  for (const r of report.rejected)
165
165
  fail(`Not accepted, tried again next run: ${r.id}: ${r.message}`);
@@ -183,7 +183,7 @@ async function syncSessions(args, paths, apiKey, say, fail) {
183
183
  code = INCOMPLETE;
184
184
  }
185
185
  else {
186
- 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);
187
187
  error = `Sync stopped: ${detail}`;
188
188
  fail(`${error}. What was uploaded is saved; the rest is tried next run.`);
189
189
  code = err instanceof ConareError ? INCOMPLETE : 1; // anything else is a bug or a broken machine
@@ -199,7 +199,7 @@ async function syncSessions(args, paths, apiKey, say, fail) {
199
199
  deleted: report?.deleted ?? 0,
200
200
  ...(error ? { error } : {}),
201
201
  }, report?.newest);
202
- return { code };
202
+ return code;
203
203
  }
204
204
  async function syncGitHub(args, paths, apiKey, say, fail) {
205
205
  const token = githubToken();
@@ -255,11 +255,7 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
255
255
  fail(`The API key was refused (${err.status} ${err.code}).`);
256
256
  return AUTH_FAILED;
257
257
  }
258
- const detail = err instanceof ConareError
259
- ? `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})`
260
- : err instanceof GitHubError || err instanceof Error
261
- ? err.message
262
- : String(err);
258
+ const detail = err instanceof ConareError ? apiDetail(err) : err instanceof Error ? err.message : String(err);
263
259
  fail(`${repo}: sync stopped: ${detail}. The state is unchanged; the next run tries again.`);
264
260
  code = err instanceof ConareError || err instanceof GitHubError ? (code === 1 ? 1 : INCOMPLETE) : 1;
265
261
  }
@@ -270,6 +266,10 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
270
266
  }
271
267
  return code;
272
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
+ }
273
273
  function tilde(path) {
274
274
  const home = homedir();
275
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
@@ -6,7 +6,7 @@ import { projectName } from "./project.js";
6
6
  import { findClaudeFiles, readClaudeFile } from "./sources/claude.js";
7
7
  import { findCodexFiles, readCodexFile } from "./sources/codex.js";
8
8
  import { isStamped, loadState, saveState } from "./state.js";
9
- import { BATCH_BYTES, BATCH_DOCUMENTS, UPLOADS_IN_FLIGHT, heldAs, listLayouts, removeStaleParts, sendBatch } from "./upload.js";
9
+ import { BATCH_BYTES, BATCH_DOCUMENTS, UPLOADS_IN_FLIGHT, heldAs, listLayouts, removeStaleParts, sendBatch, splitPart } from "./upload.js";
10
10
  export function findTranscripts(paths) {
11
11
  return [
12
12
  ...findClaudeFiles(paths.claudeDir).map((f) => ({ path: f.path, read: () => readClaudeFile(f) })),
@@ -97,6 +97,10 @@ export async function runSync(opts) {
97
97
  log(`Uploaded ${report.documents} documents (${formatBytes(report.bytes)})`);
98
98
  };
99
99
  try {
100
+ // What the state says the server holds and it no longer does (a delete in the console,
101
+ // an erased namespace, a restore) goes up again: only those, since the rest still match.
102
+ if (ns && Object.keys(state.documents).length > 0)
103
+ forgetGone(state, await (layouts ??= listLayouts(ns)));
100
104
  const files = newestFirst(opts.files);
101
105
  for (const file of files)
102
106
  await visit(file);
@@ -114,7 +118,7 @@ export async function runSync(opts) {
114
118
  }
115
119
  return report;
116
120
  async function visit(file) {
117
- if (isStamped(state, file.path, file.stamp)) {
121
+ if (isStamped(state.files, file.path, file.stamp)) {
118
122
  report.unchanged++;
119
123
  return;
120
124
  }
@@ -202,6 +206,21 @@ async function settle(ns, state, entry, report, held) {
202
206
  }
203
207
  state.files[entry.path] = entry.stamp;
204
208
  }
209
+ /** Drop what the server no longer holds from the state; every file is then read again, as its stamp says nothing of that. */
210
+ function forgetGone(state, listed) {
211
+ let gone = false;
212
+ for (const id of Object.keys(state.documents)) {
213
+ const { base, part } = splitPart(id);
214
+ const held = listed.get(base);
215
+ if (part === undefined ? held?.whole : held?.parts.includes(part))
216
+ continue;
217
+ delete state.documents[id];
218
+ state.parts[base] = 0;
219
+ gone = true;
220
+ }
221
+ if (gone)
222
+ state.files = {};
223
+ }
205
224
  /** Stat every file (skipping ones that vanished) and order newest first, so a cut-short run keeps the recent work. */
206
225
  function newestFirst(files) {
207
226
  const out = [];
@@ -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,19 +75,23 @@ 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
+ /** A document id as its session and, for one stored in parts, its part. */
82
+ export function splitPart(id) {
83
+ const m = PART_ID.exec(id);
84
+ return m ? { base: m[1], part: Number(m[2]) } : { base: id };
85
+ }
81
86
  /** List every id in the namespace once and group them by session; an absent namespace holds nothing. */
82
87
  export async function listLayouts(ns) {
83
88
  const layouts = new Map();
84
89
  try {
85
90
  for await (const doc of ns.list({ limit: 100 })) {
86
- const m = PART_ID.exec(doc.id);
87
- const base = m ? m[1] : doc.id;
91
+ const { base, part } = splitPart(doc.id);
88
92
  const held = layouts.get(base) ?? { whole: false, parts: [] };
89
- if (m)
90
- held.parts.push(Number(m[2]));
93
+ if (part !== undefined)
94
+ held.parts.push(part);
91
95
  else
92
96
  held.whole = true;
93
97
  layouts.set(base, held);
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.25.0";
1
+ export declare const VERSION = "0.26.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>;
@@ -20,16 +20,40 @@ export interface FilterOperators {
20
20
  $ne?: Scalar;
21
21
  $nin?: Scalar[];
22
22
  }
23
+ /**
24
+ * Text within `maxDistance` edits of `query`, anywhere in a passage: `query` holds at least
25
+ * 3 x (`maxDistance` + 1) characters and at most 64. The wire form, as `Filter`'s `$text` takes it.
26
+ */
27
+ export interface FuzzyText {
28
+ query: string;
29
+ /** 0, 1 or 2; default 1. */
30
+ max_distance?: number;
31
+ /** Default true. */
32
+ case_sensitive?: boolean;
33
+ }
34
+ /** A test on each passage's text: a regular expression matched anywhere, or a near spelling. */
35
+ export type TextFilter = {
36
+ $regex: string;
37
+ } | {
38
+ $fuzzy: FuzzyText;
39
+ };
23
40
  /**
24
41
  * A metadata filter. `{ team: "support" }` means equals (or, for an array value, contains);
25
42
  * use `$eq` / `$in` / ranges per key and `$and` / `$or` to combine:
26
- * `{ $or: [{ team: "support" }, { year: { $gte: 2024 } }] }`.
43
+ * `{ $or: [{ team: "support" }, { year: { $gte: 2024 } }] }`. `$text` tests the text instead,
44
+ * in queries and `grep`, not beside `$ne` or `$nin`.
27
45
  */
28
- export interface Filter {
46
+ export type Filter = FieldFilter | TextClause;
47
+ interface FieldFilter {
29
48
  $and?: Filter[];
30
49
  $or?: Filter[];
31
50
  [key: string]: Scalar | FilterOperators | Filter[] | undefined;
32
51
  }
52
+ interface TextClause {
53
+ $and?: Filter[];
54
+ $or?: Filter[];
55
+ $text: TextFilter;
56
+ }
33
57
  export interface DocumentInput {
34
58
  /** 1-256 characters of [A-Za-z0-9._:-]. Omit to let Conare generate one. Same id replaces. */
35
59
  id?: string;
@@ -80,7 +104,7 @@ export type FileType = "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt"
80
104
  export interface PictureWithoutText {
81
105
  /** A deck's: the slide it is on. */
82
106
  slide?: number;
83
- /** Its number in reading order (per slide in a deck), as the `image` of its documents would be. */
107
+ /** Its number in reading order (per slide in a deck), as its part's `image` would be. */
84
108
  image: number;
85
109
  /** A Word document's: the headings it sits under. */
86
110
  heading?: string;
@@ -178,7 +202,7 @@ export interface FileUpload {
178
202
  parts: ParsePart[];
179
203
  /** The type it was read as: an image of any format is `image`. */
180
204
  type: "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "image";
181
- /** The documents it made, in reading order. */
205
+ /** The file's one document, `<sourceId>:<fileId>` (a file uploaded before 2026-10-25 keeps one per part until uploaded again). */
182
206
  ids: string[];
183
207
  /** A PDF's pages (null for any other file). */
184
208
  pages: number | null;
@@ -190,7 +214,7 @@ export interface FileUpload {
190
214
  slidesWithoutText: number[];
191
215
  /** PDF or image pages read by OCR; stored like the rest. */
192
216
  pagesOcr: number;
193
- /** Pictures of a Word document or deck read by OCR, each a document of its own. */
217
+ /** Pictures of a Word document or deck read by OCR, each a part of the file's document. */
194
218
  imagesOcr: number;
195
219
  /** Pictures of a Word document or deck OCR did not turn into text, each with where it is and why. */
196
220
  imagesWithoutText: PictureWithoutText[];
@@ -200,10 +224,11 @@ export interface FileUpload {
200
224
  ocrPending: number[];
201
225
  /**
202
226
  * `queued`, `parsing`: the parse runs; follow it with `getFile(fileId)`. `ocr`: stored, with pages OCR tries
203
- * again (`ocrPending`). `ready`: every document is stored. `failed`: the parse failed (`error`).
227
+ * again (`ocrPending`). `ready`: every document is stored. `failed`: the parse failed or parts of it could not be
228
+ * stored (`error`); what `ids` lists stays searchable.
204
229
  */
205
230
  state: "queued" | "parsing" | "ocr" | "ready" | "failed";
206
- /** The files source of the namespace (and user): its documents are `<sourceId>:<fileId>:<part>`. */
231
+ /** The files source of the namespace (and user): the file's document is `<sourceId>:<fileId>`. */
207
232
  sourceId: string | null;
208
233
  /** Everything the file stored no text for, in one place (`pagesWithoutText`, `slidesWithoutText` and `imagesWithoutText` say the same). */
209
234
  withoutText: WithoutText;
@@ -243,7 +268,10 @@ export interface DocumentSummary {
243
268
  }
244
269
  export interface QueryResult {
245
270
  id: string;
246
- /** The best matching passage of the document. */
271
+ /**
272
+ * The passages of the document that answer, best first: its best matching passage and up to two more that
273
+ * match nearly as well. Passages that do not follow each other in the document are joined by a line holding only `…`.
274
+ */
247
275
  text: string;
248
276
  /** Higher is better: the reranker's score when `reranked`, else the fused rank score. The two do not compare. */
249
277
  score: number;
@@ -269,6 +297,28 @@ export interface QueryOptions extends RequestOptions {
269
297
  /** 2 searches again from the best results, for answers that span documents (not with `queryPages`). */
270
298
  hops?: 1 | 2;
271
299
  }
300
+ export interface GrepOptions extends RequestOptions {
301
+ filter?: Filter;
302
+ user?: string;
303
+ userPrefix?: string;
304
+ /** At most this many documents: 1-100, default 20. */
305
+ limit?: number;
306
+ /** A page's `nextCursor`, to go on. */
307
+ cursor?: string;
308
+ }
309
+ /** A document whose text matches, with the lines that do. */
310
+ export interface GrepMatch {
311
+ namespace: string;
312
+ id: string;
313
+ date?: string;
314
+ lines: string[];
315
+ }
316
+ /** One page of `Namespace.grep`. */
317
+ export interface GrepPage {
318
+ matches: GrepMatch[];
319
+ /** Where the next page starts; null on the last page. A page can stop short of `limit`. */
320
+ nextCursor: string | null;
321
+ }
272
322
  /** One page of `Namespace.queryPages`. */
273
323
  export interface QueryPage {
274
324
  results: QueryResult[];
@@ -282,6 +332,12 @@ export interface NamespaceInfo {
282
332
  embeddingModel: string;
283
333
  /** The model that reranks its queries. */
284
334
  rerankModel: string;
335
+ /** When it was created (ISO 8601); before 2026-10-18, when its oldest document was written. */
336
+ createdAt: string | null;
337
+ /** Its last write; null when it has none to report. */
338
+ updatedAt: string | null;
339
+ /** Its last query, recorded at most once a minute; null when not queried since 2026-10-18. */
340
+ lastQueryAt: string | null;
285
341
  }
286
342
  export interface RerankResult {
287
343
  index: number;
@@ -474,7 +530,7 @@ export interface ConareOptions {
474
530
  baseURL?: string;
475
531
  /** Per-request timeout in milliseconds. Default 60000. */
476
532
  timeout?: number;
477
- /** Retries on 429, 5xx and network errors (a request that could create something twice only on 429 and 503). Default 2. */
533
+ /** 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
534
  maxRetries?: number;
479
535
  /** Custom fetch, e.g. for proxies or tests. */
480
536
  fetch?: (url: string, init: RequestInit) => Promise<Response>;
@@ -486,8 +542,8 @@ export interface ConareOptions {
486
542
  organization?: string;
487
543
  /**
488
544
  * 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.
545
+ * runtime has `CompressionStream` (Node 18+, Bun, browsers). A server that refuses gzip (415, or 400
546
+ * `invalid_json`) gets the request again as plain JSON, and no more gzip from this client.
491
547
  */
492
548
  gzip?: boolean;
493
549
  }
@@ -510,7 +566,7 @@ export interface RequestOptions {
510
566
  * writes nothing. A key is 1-255 visible ASCII characters, kept per API key; `write()` and `add()`
511
567
  * send batch `n` after the first as `<key>:<n>` and leave documents without an id to the API, which
512
568
  * 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()`
569
+ * so do `sources.documents.put()`, `check()`, `delete()` and `restore()` with batch `n`; `imports.create()`
514
570
  * sends its upload's parts as `<key>:part-<n>`, then `<key>:complete` and `<key>:import`.
515
571
  * The same key with another request is a 422 `idempotency_key_reused`.
516
572
  */
@@ -552,7 +608,7 @@ export declare class Conare {
552
608
  namespace(name: string): Namespace;
553
609
  /**
554
610
  * 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-"`.
611
+ * count, models and times; with `prefix`, only those whose name starts with it, e.g. one user's `"u7f3a9c-"`.
556
612
  */
557
613
  namespaces(options?: RequestOptions & {
558
614
  prefix?: string;
@@ -606,10 +662,12 @@ export declare class Namespace {
606
662
  * Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
607
663
  * (one of your organization's models from `GET /models`) needs this: a write creates one with the
608
664
  * default model. Its model never changes: creating it again with another one is a 409. Returns
609
- * the model that embeds it.
665
+ * the model that embeds it. `regexIndex` makes `grep` and `$text` filters answer from an index,
666
+ * chosen once: over a namespace that exists without one it is a 409.
610
667
  */
611
668
  create(options?: RequestOptions & {
612
669
  embeddingModel?: string;
670
+ regexIndex?: boolean;
613
671
  }): Promise<{
614
672
  embeddingModel: string;
615
673
  }>;
@@ -632,12 +690,13 @@ export declare class Namespace {
632
690
  * Store a file, up to 512 MiB, in one call: a PDF, a Word document (.docx), a PowerPoint deck (.pptx),
633
691
  * an Excel workbook (.xlsx), a CSV or TSV, a text or Markdown file, or an image (PNG, JPEG, WebP,
634
692
  * 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
693
+ * rather than misread; without it the type comes from the bytes, then the name. The file is one
694
+ * document, `<sourceId>:<fileId>` (`sourceId` is the namespace's files source), with `file`, `file_id`
695
+ * and `file_type` in metadata beside `metadata` of your own. Its pages, slides, worksheet row ranges and
696
+ * Word parts are parts of it: a search hit says where it is (`page`, `sheet` and `rows`, `slide`, `part`,
697
+ * `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.
698
+ * Pages without a text layer are read by OCR. `fileId` defaults to the name in id characters; uploading
699
+ * the same one again replaces it, and the same bytes, name and options again answer
641
700
  * `result: "unchanged"`. `user` keeps the file to one of your users. The answer waits `wait` seconds
642
701
  * (default 60) for the parse: once `ready` it holds what `parse` answers (`markdown`, `parts`,
643
702
  * `withoutText`); before that it is `queued` or `parsing`, and `getFile` follows it.
@@ -648,21 +707,27 @@ export declare class Namespace {
648
707
  metadata?: Metadata;
649
708
  }): Promise<FileUpload>;
650
709
  /**
651
- * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its documents
710
+ * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its document
652
711
  * and its parse (`markdown`, `parts`). An id with no file throws 404 `file_not_found`.
653
712
  */
654
713
  getFile(fileId: string, options?: RequestOptions & {
655
714
  user?: string;
656
715
  }): Promise<FileStatus>;
657
716
  /**
658
- * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
717
+ * Hybrid search, reranked. One result per document: the passages of it that answer; `topK` documents when that
659
718
  * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
660
719
  * 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
720
+ * first passages the reranker ranks; unset, the first 100. `user` keeps the search to one user's documents and
662
721
  * `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
663
722
  * `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
664
723
  */
665
724
  query(query: string, options?: QueryOptions): Promise<QueryResult[]>;
725
+ /**
726
+ * The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
727
+ * with the lines that match, in id order. A match lies inside one passage. Pass `nextCursor` as `cursor`
728
+ * to go on; a namespace created without `regexIndex` reads its passages, so a page can stop short of `limit`.
729
+ */
730
+ grep(pattern: string | FuzzyText, options?: GrepOptions): Promise<GrepPage>;
666
731
  /**
667
732
  * A deep search, page by page: ranks `maxResults` documents once (at least `topK`; at most 1,000,
668
733
  * or 5,000 on a custom model's engine) and yields them `topK` at a time. Later pages are read from
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.25.0";
2
+ export const VERSION = "0.26.0";
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;
@@ -324,10 +330,11 @@ export class Namespace {
324
330
  * Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
325
331
  * (one of your organization's models from `GET /models`) needs this: a write creates one with the
326
332
  * default model. Its model never changes: creating it again with another one is a 409. Returns
327
- * the model that embeds it.
333
+ * the model that embeds it. `regexIndex` makes `grep` and `$text` filters answer from an index,
334
+ * chosen once: over a namespace that exists without one it is a 409.
328
335
  */
329
336
  async create(options = {}) {
330
- const body = await this.client.request("POST", "/namespaces", { name: this.name, embedding_model: options.embeddingModel }, options);
337
+ const body = await this.client.request("POST", "/namespaces", { name: this.name, embedding_model: options.embeddingModel, regex_index: options.regexIndex }, options);
331
338
  return { embeddingModel: body.embedding_model };
332
339
  }
333
340
  /**
@@ -362,7 +369,7 @@ export class Namespace {
362
369
  seq: d.seq,
363
370
  if_version: d.ifVersion,
364
371
  })),
365
- }, { ...options, idempotencyKey: key && i > 0 ? `${key}:${i / BATCH_SIZE}` : key });
372
+ }, { ...options, idempotencyKey: stepKey(key, i / BATCH_SIZE) });
366
373
  body.ids.forEach((id, j) => {
367
374
  const r = body.results?.[j];
368
375
  const result = { id, version: body.versions?.[j] ?? null };
@@ -382,12 +389,13 @@ export class Namespace {
382
389
  * Store a file, up to 512 MiB, in one call: a PDF, a Word document (.docx), a PowerPoint deck (.pptx),
383
390
  * an Excel workbook (.xlsx), a CSV or TSV, a text or Markdown file, or an image (PNG, JPEG, WebP,
384
391
  * 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
392
+ * rather than misread; without it the type comes from the bytes, then the name. The file is one
393
+ * document, `<sourceId>:<fileId>` (`sourceId` is the namespace's files source), with `file`, `file_id`
394
+ * and `file_type` in metadata beside `metadata` of your own. Its pages, slides, worksheet row ranges and
395
+ * Word parts are parts of it: a search hit says where it is (`page`, `sheet` and `rows`, `slide`, `part`,
396
+ * `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.
397
+ * Pages without a text layer are read by OCR. `fileId` defaults to the name in id characters; uploading
398
+ * the same one again replaces it, and the same bytes, name and options again answer
391
399
  * `result: "unchanged"`. `user` keeps the file to one of your users. The answer waits `wait` seconds
392
400
  * (default 60) for the parse: once `ready` it holds what `parse` answers (`markdown`, `parts`,
393
401
  * `withoutText`); before that it is `queued` or `parsing`, and `getFile` follows it.
@@ -406,7 +414,7 @@ export class Namespace {
406
414
  return toFileUpload(body);
407
415
  }
408
416
  /**
409
- * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its documents
417
+ * A file's latest upload (of `user`'s files, when given): its state and, once `ready`, its document
410
418
  * and its parse (`markdown`, `parts`). An id with no file throws 404 `file_not_found`.
411
419
  */
412
420
  async getFile(fileId, options = {}) {
@@ -415,10 +423,10 @@ export class Namespace {
415
423
  return { ...toFileUpload(body), name: body.name, uploadedAt: new Date(body.uploaded_at) };
416
424
  }
417
425
  /**
418
- * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
426
+ * Hybrid search, reranked. One result per document: the passages of it that answer; `topK` documents when that
419
427
  * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
420
428
  * 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
429
+ * first passages the reranker ranks; unset, the first 100. `user` keeps the search to one user's documents and
422
430
  * `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
423
431
  * `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
424
432
  */
@@ -426,6 +434,22 @@ export class Namespace {
426
434
  const body = await this.client.request("POST", this.path("/query"), queryBody(query, options), options);
427
435
  return body.results;
428
436
  }
437
+ /**
438
+ * The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
439
+ * with the lines that match, in id order. A match lies inside one passage. Pass `nextCursor` as `cursor`
440
+ * to go on; a namespace created without `regexIndex` reads its passages, so a page can stop short of `limit`.
441
+ */
442
+ async grep(pattern, options = {}) {
443
+ const body = await this.client.request("POST", this.path("/grep"), {
444
+ ...(typeof pattern === "string" ? { pattern } : { fuzzy: pattern }),
445
+ filter: options.filter,
446
+ user: options.user,
447
+ user_prefix: options.userPrefix,
448
+ limit: options.limit,
449
+ cursor: options.cursor,
450
+ }, options);
451
+ return { matches: body.matches, nextCursor: body.next_cursor ?? null };
452
+ }
429
453
  /**
430
454
  * A deep search, page by page: ranks `maxResults` documents once (at least `topK`; at most 1,000,
431
455
  * or 5,000 on a custom model's engine) and yields them `topK` at a time. Later pages are read from
@@ -495,7 +519,7 @@ export class Namespace {
495
519
  const key = options?.idempotencyKey;
496
520
  for (let round = 0;; round++) {
497
521
  // 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 });
522
+ const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { ...options, idempotencyKey: stepKey(key, round) });
499
523
  deleted += out.deleted;
500
524
  if (!out.more)
501
525
  return deleted;
@@ -510,7 +534,7 @@ export class Namespace {
510
534
  async drop(options = {}) {
511
535
  const { force, ...rest } = options;
512
536
  const body = await this.client.request("DELETE", this.path(force ? "?force=true" : ""), undefined, rest);
513
- return { sourcesDeleted: body?.sources_deleted ?? [] };
537
+ return { sourcesDeleted: body.sources_deleted ?? [] };
514
538
  }
515
539
  }
516
540
  // ---- Sources ---------------------------------------------------------------
@@ -605,7 +629,7 @@ export class SourceDocuments {
605
629
  const all = Array.isArray(documents) ? documents : [documents];
606
630
  const out = [];
607
631
  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);
632
+ 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
633
  out.push(...body.results.map(toPushResult));
610
634
  }
611
635
  return out;
@@ -904,7 +928,6 @@ function toRun(r) {
904
928
  finishedAt: r.finished_at ? new Date(r.finished_at) : null,
905
929
  };
906
930
  }
907
- /** A random Idempotency-Key for one call (kept across its retries). */
908
931
  function base64(bytes) {
909
932
  let bin = "";
910
933
  for (const b of bytes)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",