conare 0.20.0 → 0.22.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
@@ -1,6 +1,6 @@
1
1
  # conare
2
2
 
3
- TypeScript client for [Conare](https://conare.ai): add documents, query them, connect apps.
3
+ TypeScript client for [Conare](https://conare.ai): add documents, query them, connect apps, sync your own.
4
4
  No dependencies. Works on Node 18+, Bun, Deno and edge runtimes.
5
5
 
6
6
  ## Quickstart
@@ -31,10 +31,16 @@ A namespace is created by its first write. Writing the same id again replaces th
31
31
  ```ts
32
32
  new Conare() // CONARE_API_KEY from the environment
33
33
  new Conare({ apiKey, baseURL, timeout: 60_000, maxRetries: 2 })
34
+ await conare.organizations() // [{ id, name, role }]: the organizations the key acts for
35
+ new Conare({ organization: "org_…" }) // acts for that one (X-Conare-Org)
34
36
  ```
35
37
 
36
38
  Every method also takes `{ signal, timeout }` as its last option.
37
39
 
40
+ A key acts for its own organization. A multi-organization key (made in the console by an admin of
41
+ each organization it names) acts for any of them: make one client per organization with
42
+ `organization`. Without it, such a key answers 400 on every call but `organizations()`.
43
+
38
44
  ### Namespaces and documents
39
45
 
40
46
  ```ts
@@ -54,12 +60,12 @@ for await (const doc of docs.list()) {} // every document, page by page (
54
60
  await docs.delete("refunds"); // 404 document_not_found if it does not exist
55
61
  await docs.deleteMany(["a", "b"]); // up to 1000 ids in one call; missing ids are skipped. Returns the count
56
62
  await docs.deleteWhere({ team: "support" }); // every document matching the filter, whole documents. Returns the count
57
- await docs.uploadFile(bytes, "report.pdf"); // a PDF (one document per page) or an .xlsx (Markdown tables per sheet),
58
- // up to 20 MiB. The same name (or { id }) again replaces it.
59
- // Returns { fileId, type, ids, pages, sheets, pagesOcr, pagesWithoutText, ocrPending }:
63
+ await docs.uploadFile(bytes, "report.pdf"); // a PDF (one document per page), a .docx (Markdown), a .pptx (one per slide)
64
+ // or an .xlsx (Markdown tables per sheet), up to 20 MiB. The same name (or { id }) again replaces it.
65
+ // Returns { fileId, type, ids, pages, sheets, slides, slidesWithoutText, pagesOcr, pagesWithoutText, ocrPending }:
60
66
  // scanned pages are OCR'd after the answer (ocrPending; { wait: true } reads them first)
67
+ await docs.getFile("report.pdf"); // that upload's outcome, OCR after the answer included (kept 7 days)
61
68
  await docs.drop(); // delete the namespace and its documents (succeeds if already emptied; 404 namespace_not_found if never written)
62
- await docs.create({ sparse: true }); // create it with a sparse (SPLADE) index, before its first write
63
69
 
64
70
  await conare.namespaces(); // [{ name, documents }]
65
71
  await conare.namespaces({ prefix: "u7f3a9c-" }); // one user's namespaces
@@ -72,21 +78,20 @@ Namespace names: 1-64 characters of `a-z 0-9 _ -`. Ids: up to 256 characters of
72
78
 
73
79
  ```ts
74
80
  await docs.query("how do refunds work?", {
75
- topK: 10, // 1-100, default 10
81
+ topK: 10, // 1-500, default 10
76
82
  filter: { team: "support" }, // optional metadata filter
77
83
  rerank: true, // default true
78
- retrievers: ["vector", "keyword"], // default; add "sparse" in a namespace created with a sparse index
84
+ retrievers: ["vector", "keyword"], // default; one of them alone searches with it alone
79
85
  });
80
86
  ```
81
87
 
82
88
  Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what it
83
- fuses: `"vector"` (the embedding model), `"keyword"` (BM25; alone, BM25 alone) and `"sparse"` (the
84
- learned-sparse SPLADE model, in a namespace created with `create({ sparse: true })`).
89
+ fuses: `"vector"` (the embedding model) and `"keyword"` (BM25; alone, BM25 alone).
85
90
  `score` is the reranker's when `reranked` is true, else the fused rank score of a result past the
86
91
  rerank window (or of a query not reranked); the two scales do not compare.
87
92
 
88
93
  Filters match metadata values: `{ key: value }` means equals (or, for an array value,
89
- contains). Operators: `$eq`, `$in` and the ranges below. Combine with `$and` and `$or`:
94
+ contains). Operators: `$eq`, `$in`, `$ne`, `$nin` (queries only) and the ranges below. Combine with `$and` and `$or`:
90
95
 
91
96
  ```ts
92
97
  { $or: [{ team: "support" }, { year: { $in: [2024, 2025] } }] }
@@ -101,20 +106,25 @@ compare numbers, string bounds compare strings by their UTF-8 bytes, so ISO date
101
106
  { published_at: { $gte: "2025-06-01" } }
102
107
  ```
103
108
 
104
- There is no `$ne` or `$nin`: the API answers 400 `invalid_filter`.
109
+ `$ne` and `$nin` work in queries; a delete by filter with one answers 400 `invalid_filter`.
105
110
 
106
111
  ### Embed and rerank
107
112
 
108
113
  ```ts
109
114
  await conare.embed(["some text"], { type: "query" }); // number[][]; type defaults to "document"
115
+ await conare.embed(["some text"], { outputDtype: "int8" }); // { values: Int8Array[], scales }; dequantize() gives floats
110
116
  await conare.rerank("refund window", ["a", "b"], { topK: 1 }); // [{ index, score, document }], plus .unscored
111
117
  ```
112
118
 
119
+ `outputDtype: "int8"` returns each vector as int8 values plus one scale (vector ≈ values × scale, scale = max|x| / 127):
120
+ a quarter of the bytes. Cosine on the values alone equals cosine on the floats, so they can be stored and searched as
121
+ they are. On our embedder's real vectors this cost no measurable retrieval quality (nDCG@10 -0.00 [-0.10, +0.10] on 1M
122
+ chunks). There is no binary output: 1-bit vectors lost 4 to 7.5 nDCG@10 points there.
123
+
113
124
  `rerank` takes 1-100 documents of 1-24,000 characters each (the query at most 8,192 characters, all
114
- together at most 256,000); more than 100 is a 400 `invalid_request`. More than 20 go through a
115
- tournament: windows of 20 documents, then one final window that reads the best 20 together and sets their order. A
116
- document no window read before the one-second budget ended, or whose window failed, is listed by
117
- index in `.unscored` and is not in the results; its score from another call would not compare.
125
+ together at most 256,000); more than 100 is a 400 `invalid_request`. A document not read before the
126
+ one-second budget ended, or whose read failed, is listed by index in `.unscored` and is not in the
127
+ results; its score from another call would not compare.
118
128
 
119
129
  ### Sources
120
130
 
@@ -133,10 +143,71 @@ await conare.sources.types(); // [{ type, name, logoUrl }]
133
143
  await conare.sources.list(); // [Source]
134
144
  await conare.sources.get(source.id); // { id, type, name, namespace, status, error, documents, lastSyncedAt, createdAt }
135
145
  await conare.sources.sync(source.id); // sync now
146
+ await conare.sources.sync(source.id, { full: true }); // re-read everything (Gmail and apps Conare reads itself); Gmail's rows are billed again
147
+ await conare.sources.update(source.id, { syncIntervalSeconds: 3600 }); // every hour; null is automatic
136
148
  await conare.sources.delete(source.id, { deleteDocuments: true });
137
149
  ```
138
150
 
139
- `status` is `connecting`, `syncing`, `ready` or `error`.
151
+ `status` is `connecting`, `syncing`, `ready` or `error`. A source syncs on an automatic interval
152
+ picked from what each sync reads, or on one you set from 5 minutes to 30 days. `source.cost` holds
153
+ what an estimate of a month at any interval needs: the rows the last sync read, whether syncs read
154
+ only changes, and the prices.
155
+
156
+ ### Custom sources
157
+
158
+ A custom source is a set of documents you push from your own system, keyed by your own ids.
159
+ Conare answers per document what each write did, keeps a deleted one out, and can mirror a whole
160
+ set: what a snapshot run never saw is deleted.
161
+
162
+ ```ts
163
+ const src = await conare.sources.create({ type: "custom", namespace: "kb", name: "Help center" });
164
+
165
+ await conare.sources.documents.put(src.id, [
166
+ { externalId: "article-12", text: "Refunds take 5 days.", seq: 1759698843000, tag: "etag-9" },
167
+ ]); // [{ externalId, key, result, storedSeq?, code? }], 100 a call:
168
+ // created, updated, unchanged, stale (a lower seq), deleted, rejected
169
+ await conare.sources.documents.check(src.id, [{ externalId: "article-12", tag: "etag-9" }]); // { need, excluded }
170
+ for await (const d of conare.sources.documents.list(src.id)) {} // { externalId, key, tag, seq, user, version }
171
+ await conare.sources.documents.get(src.id, "article-12"); // with text and metadata, or null
172
+ await conare.sources.documents.delete(src.id, ["article-12"], { exclude: true }); // kept out until restored
173
+ await conare.sources.documents.restore(src.id, ["article-12"]);
174
+
175
+ // Mirror the whole set: push (or check, when unchanged) every document through a run, then complete it.
176
+ const run = await conare.runs.open(src.id, { expected: 2 });
177
+ await run.put([{ externalId: "a", text: "..." }]);
178
+ await run.check([{ externalId: "b", tag: "etag-1" }]);
179
+ const done = await run.complete(); // { state, sweep, counts: { seen, live, planned, deleted } }
180
+ // sweep "held": over 10% (and over 1,000) would go at once; a run 24 h later that agrees applies it.
181
+
182
+ await conare.imports.create(src.id, jsonl, { mode: "snapshot" }); // a JSON-lines file, up to 1 GiB: a Run
183
+ await conare.runs.get(runId); // follow any run
184
+ await conare.users.delete("tenant-7:u_42"); // everything of a user, in every namespace: a purge Run
185
+ await conare.users.deletePrefix("tenant-7:");
186
+ await conare.events.list({ cursor: "0", types: ["run.*"] }); // { data: [{ seq, type, runId, data }], nextCursor }
187
+ ```
188
+
189
+ `sources.list()` and `sources.get()` answer custom sources too, with `kind: "custom"`. These
190
+ calls send an `Idempotency-Key` when they create or delete something, so their retries are safe.
191
+
192
+ ### Files
193
+
194
+ A PDF, Word document, PowerPoint deck, Excel workbook, CSV, text or image file becomes documents, one
195
+ per page, sheet part, slide or Word part, each citing where it came from (`page`; `sheet` and `rows`;
196
+ `slide`; `heading` and `part`) in its metadata. Parsing runs in the background; every page without a
197
+ usable text layer (a scan, an image) is read by OCR, and a page OCR could not read is listed in
198
+ `ocrFailed`, never left out silently. Declare the `type` when you know it: the file is parsed as that
199
+ type, and bytes of another type are a `ConareError` 415 `type_mismatch`.
200
+
201
+ ```ts
202
+ const { file } = await conare.files.upload({ file: bytes, name: "Q3 report.pdf", namespace: "kb", type: "pdf",
203
+ metadata: { deal: "acme" } }); // up to 64 MiB in one request, up to 512 MiB in 16 MiB parts
204
+ const [ready] = await conare.files.waitUntilReady({ namespace: "kb", ids: [file.id] });
205
+ // { state: "ready", pages, pagesText, pagesOcr, pagesWithoutText, ocrFailed, documents, locators, ... }
206
+ await conare.files.status({ namespace: "kb", ids: [file.id] });
207
+ await conare.files.reparse(file.id, { namespace: "kb" }); // again, from the stored original
208
+ ```
209
+
210
+ The same bytes and metadata again answer `result: "unchanged"`: nothing is parsed or embedded.
140
211
 
141
212
  ### Errors
142
213
 
@@ -179,32 +250,6 @@ const context = await user.query("how should we contact them?");
179
250
 
180
251
  Keep the API key on your server. It can read and write every namespace in your organization.
181
252
 
182
- ## MCP
183
-
184
- Conare is also an MCP server at `https://api.conare.ai/mcp`, with tools to search, fetch, save
185
- and delete documents and list namespaces. Clients that sign in over OAuth (claude.ai connectors,
186
- ChatGPT) need only the URL; the rest take a key:
187
-
188
- Claude Code:
189
-
190
- ```bash
191
- claude mcp add --transport http conare https://api.conare.ai/mcp \
192
- --header "Authorization: Bearer $CONARE_API_KEY"
193
- ```
194
-
195
- Cursor (`~/.cursor/mcp.json`):
196
-
197
- ```json
198
- {
199
- "mcpServers": {
200
- "conare": {
201
- "url": "https://api.conare.ai/mcp",
202
- "headers": { "Authorization": "Bearer sk-conare-..." }
203
- }
204
- }
205
- }
206
- ```
207
-
208
253
  ## The `conare` command: sync sessions and GitHub
209
254
 
210
255
  The package also ships a command (the library never loads it). It runs under Node and Bun:
@@ -251,7 +296,10 @@ review comments; bots other than `greptile-apps[bot]` and `claude[bot]` are left
251
296
  the default branch into `<repo>-docs` (id: the path with `/` as `:`; metadata `kind: "doc"`,
252
297
  `path`, `title`, `author`, `date`, `url`). Later runs read only threads updated since the last one
253
298
  and files whose content changed; docs whose file was deleted are deleted. `--state <file>` sets
254
- where that is kept (default `~/.conare/github-state.json`).
299
+ where that is kept (default `~/.conare/github-state.json`). `<repo>` is the repository's name
300
+ lowercased, with any character other than letters, digits, `_` and `-` as `-` (`vercel/next.js`
301
+ writes `next-js-github`). A namespace that already holds another owner's repository of the same
302
+ name is left alone, and that repository's sync stops with an error.
255
303
 
256
304
  ## Development
257
305
 
package/dist/cli/args.js CHANGED
@@ -26,6 +26,16 @@ The key comes from --key, else CONARE_API_KEY, else ~/.conare/sync.json.
26
26
  Create one at https://conare.ai/console/keys. GitHub: GITHUB_TOKEN, else \`gh auth token\`.
27
27
  `;
28
28
  const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
29
+ /**
30
+ * The name "<name>-github" and "<name>-docs" start with, for owner/repo: the repository's name
31
+ * as a namespace may hold it (1-64 of [a-z0-9_-], starting with a letter or digit): lowercased,
32
+ * any other character as "-", leading "-" and "_" dropped, at most 57 characters so
33
+ * "<name>-github" fits. vercel/next.js -> next-js. null when nothing is left.
34
+ */
35
+ export function repoNamespace(repo) {
36
+ const name = repo.slice(repo.indexOf("/") + 1).toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[-_]+/, "").slice(0, 57);
37
+ return name || null;
38
+ }
29
39
  export function parseArgs(argv) {
30
40
  const args = { help: false, version: false, command: "sessions", dryRun: false, quiet: false, install: false, uninstall: false, repos: [] };
31
41
  const rest = [...argv];
@@ -109,7 +119,9 @@ export function parseArgs(argv) {
109
119
  // Namespaces are named after the repository alone (<name>-github, <name>-docs).
110
120
  const byName = new Map();
111
121
  for (const repo of more) {
112
- const name = repo.slice(repo.indexOf("/") + 1).toLowerCase();
122
+ const name = repoNamespace(repo);
123
+ if (!name)
124
+ return { error: `${repo}: its name makes no namespace name (letters or digits needed).` };
113
125
  const other = byName.get(name);
114
126
  if (other && other.toLowerCase() !== repo.toLowerCase())
115
127
  return { error: `${other} and ${repo} would both write to ${name}-github and ${name}-docs; sync one of them.` };
@@ -48,6 +48,11 @@ export async function syncRepo(opts) {
48
48
  };
49
49
  const next = { ...opts.state };
50
50
  const info = await gh.json(`/repos/${repo}`);
51
+ // The namespaces are named after the repository alone, so another owner's repository of the
52
+ // same name may fill them: its threads and docs would be overwritten and its docs deleted.
53
+ if (opts.namespaces)
54
+ for (const ns of [opts.namespaces.github, opts.namespaces.docs])
55
+ await refuseOtherRepo(ns, info.full_name);
51
56
  // ---- threads ----
52
57
  const since = opts.state.updatedAt;
53
58
  const issues = latestPerThread(await gh.all(`/repos/${repo}/issues?state=all&sort=updated&direction=desc&per_page=100${since ? `&since=${encodeURIComponent(since)}` : ""}`));
@@ -140,6 +145,24 @@ export async function syncRepo(opts) {
140
145
  }
141
146
  return { report, state: next };
142
147
  }
148
+ /** Throws when the namespace's first document names another repository (metadata.repo). */
149
+ async function refuseOtherRepo(ns, fullName) {
150
+ let other;
151
+ try {
152
+ for await (const d of ns.list({ limit: 1 })) {
153
+ other = d.metadata?.repo;
154
+ break;
155
+ }
156
+ }
157
+ catch (err) {
158
+ if (err instanceof ConareError && err.status === 404)
159
+ return;
160
+ throw err;
161
+ }
162
+ if (typeof other === "string" && other.toLowerCase() !== fullName.toLowerCase()) {
163
+ throw new Error(`${ns.name} holds ${other}'s documents, which syncing ${fullName} would overwrite and delete (namespaces are named after the repository alone). Sync it with another key.`);
164
+ }
165
+ }
143
166
  /** One entry per thread number, its newest version (a thread updated mid-listing can appear twice). */
144
167
  export function latestPerThread(issues) {
145
168
  const byNumber = new Map();
package/dist/cli/main.js CHANGED
@@ -8,7 +8,7 @@ import { rmSync } from "node:fs";
8
8
  import { homedir } from "node:os";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { Conare, ConareError, VERSION } from "../index.js";
11
- import { HELP, parseArgs } from "./args.js";
11
+ import { HELP, parseArgs, repoNamespace } from "./args.js";
12
12
  import { 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";
@@ -168,11 +168,17 @@ async function syncSessions(args, paths, apiKey, say, fail) {
168
168
  error = `${report.rejected.length} documents not accepted`;
169
169
  }
170
170
  catch (err) {
171
- if (err instanceof ConareError && (err.status === 401 || err.status === 403)) {
171
+ if (err instanceof ConareError && err.status === 401) {
172
172
  error = `The API key was refused (${err.status} ${err.code}).`;
173
173
  fail(`${error} Save a valid one: npx conare sync --key sk-conare-…`);
174
174
  code = AUTH_FAILED;
175
175
  }
176
+ else if (err instanceof ConareError && err.status === 403) {
177
+ // The key is valid but may not write here (a key scoped to other namespaces).
178
+ error = `The API key may not do this: ${err.message} (403 ${err.code}).`;
179
+ fail(error);
180
+ code = INCOMPLETE;
181
+ }
176
182
  else {
177
183
  const detail = err instanceof ConareError ? `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})` : String(err);
178
184
  error = `Sync stopped: ${detail}`;
@@ -212,7 +218,7 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
212
218
  const state = loadGitHubState(stateFile);
213
219
  for (const repo of args.repos) {
214
220
  const started = Date.now();
215
- const name = repo.slice(repo.indexOf("/") + 1);
221
+ const name = repoNamespace(repo); // parseArgs refused a repository without one
216
222
  // State written for another key or server starts from nothing (a dry run without a key reuses it).
217
223
  const saved = state.repos[repo] ?? {};
218
224
  const repoState = account === undefined || saved.account === account ? saved : {};
@@ -242,7 +248,7 @@ async function syncGitHub(args, paths, apiKey, say, fail) {
242
248
  }
243
249
  }
244
250
  catch (err) {
245
- if (err instanceof ConareError && (err.status === 401 || err.status === 403)) {
251
+ if (err instanceof ConareError && err.status === 401) {
246
252
  fail(`The API key was refused (${err.status} ${err.code}).`);
247
253
  return AUTH_FAILED;
248
254
  }
@@ -29,9 +29,10 @@ export function batches(docs, maxDocs = BATCH_DOCUMENTS, maxBytes = BATCH_BYTES)
29
29
  out.push(current);
30
30
  return out;
31
31
  }
32
- /** A request the API refused because of what one of its documents holds. */
32
+ /** A request the API refused because of what one of its documents holds; a bad namespace is
33
+ * every document's, so sending each alone would only repeat it. */
33
34
  function isDocumentError(err) {
34
- return err instanceof ConareError && (err.status === 400 || err.status === 413 || err.status === 422);
35
+ return err instanceof ConareError && (err.status === 400 || err.status === 413 || err.status === 422) && err.code !== "invalid_namespace";
35
36
  }
36
37
  /**
37
38
  * Write one batch. When the API refuses the batch for its content, each document is sent