conare 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.18.0";
2
+ export const VERSION = "0.20.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  // ---- Errors ----------------------------------------------------------------
@@ -74,7 +74,7 @@ export class Conare {
74
74
  }
75
75
  /** Embed texts. Use type "query" for search queries and "document" (default) for stored text. */
76
76
  async embed(input, options = {}) {
77
- const body = await this.request("POST", "/embed", { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" }, options, true);
77
+ const body = await this.request("POST", "/embed", { input: Array.isArray(input) ? input : [input], type: options.type ?? "document" }, options);
78
78
  return body.embeddings;
79
79
  }
80
80
  /**
@@ -83,24 +83,26 @@ export class Conare {
83
83
  * Check `unscored`: documents left unread are missing from the results.
84
84
  */
85
85
  async rerank(query, documents, options = {}) {
86
- const body = await this.request("POST", "/rerank", { query, documents, top_k: options.topK }, options, true);
86
+ const body = await this.request("POST", "/rerank", { query, documents, top_k: options.topK }, options);
87
87
  const results = body.results.map((r) => ({ index: r.index, score: r.score, document: documents[r.index] ?? "" }));
88
88
  return Object.assign(results, { unscored: body.unscored ?? [] });
89
89
  }
90
90
  /**
91
- * @internal Sends one API request. An idempotent request (every GET and DELETE, and the POSTs
92
- * that cannot create anything twice) is retried on 429, 5xx and network errors; any other only
93
- * on 429 and 503, where the API did not act on it.
91
+ * @internal Sends one API request. Every request but a GET carries an `Idempotency-Key` (the
92
+ * caller's, or one made here), the same on each of its attempts: the API answers a repeat with
93
+ * the first answer and does nothing again. So every request is retried on 429, 5xx, 409
94
+ * `idempotency_in_progress` (the first attempt is still running) and network errors.
94
95
  */
95
- async request(method, path, body, options = {}, idempotent = method !== "POST") {
96
+ async request(method, path, body, options = {}) {
97
+ const key = method === "GET" ? undefined : (options.idempotencyKey ?? newIdempotencyKey());
96
98
  for (let attempt = 0;; attempt++) {
97
99
  let res;
98
100
  let text;
99
101
  try {
100
- [res, text] = await this.send(method, path, body, options);
102
+ [res, text] = await this.send(method, path, body, options, key);
101
103
  }
102
104
  catch (err) {
103
- if (err instanceof ConareError && idempotent && attempt < this.maxRetries) {
105
+ if (err instanceof ConareError && attempt < this.maxRetries) {
104
106
  await sleep(retryDelay(attempt, null), options.signal);
105
107
  continue;
106
108
  }
@@ -114,16 +116,17 @@ export class Conare {
114
116
  throw new ConareError(res.status, "invalid_response", "The response was not JSON.", res.headers.get("x-request-id"));
115
117
  }
116
118
  }
117
- const retryable = res.status === 429 || res.status === 503 || (idempotent && res.status >= 500);
119
+ const err = toError(res, text);
120
+ const retryable = res.status === 429 || res.status >= 500 || err.code === "idempotency_in_progress";
118
121
  if (retryable && attempt < this.maxRetries) {
119
122
  await sleep(retryDelay(attempt, res.headers.get("retry-after")), options.signal);
120
123
  continue;
121
124
  }
122
- throw toError(res, text);
125
+ throw err;
123
126
  }
124
127
  }
125
128
  // One attempt, body included, under the timeout and the caller's signal.
126
- async send(method, path, body, options) {
129
+ async send(method, path, body, options, idempotencyKey) {
127
130
  const controller = new AbortController();
128
131
  const timeout = options.timeout ?? this.timeout;
129
132
  const timer = setTimeout(() => controller.abort(), timeout);
@@ -140,6 +143,7 @@ export class Conare {
140
143
  Authorization: `Bearer ${this.apiKey}`,
141
144
  Accept: "application/json",
142
145
  ...(body === undefined ? {} : { "Content-Type": raw ? "application/octet-stream" : "application/json" }),
146
+ ...(idempotencyKey === undefined ? {} : { "Idempotency-Key": idempotencyKey }),
143
147
  },
144
148
  body: body === undefined ? undefined : raw ? body : JSON.stringify(body),
145
149
  signal: controller.signal,
@@ -178,12 +182,13 @@ export class Namespace {
178
182
  * other setting is a 409. Returns whether it has a sparse index.
179
183
  */
180
184
  async create(options = {}) {
181
- const body = await this.client.request("POST", "/namespaces", { name: this.name, sparse: options.sparse ?? false }, options, true);
185
+ const body = await this.client.request("POST", "/namespaces", { name: this.name, sparse: options.sparse ?? false }, options);
182
186
  return { sparse: body.sparse };
183
187
  }
184
188
  /**
185
189
  * Add or replace documents. Accepts one or many; sends them in batches of 100. Returns the ids.
186
- * A document without an id gets one here, so a retried batch replaces instead of duplicating.
190
+ * A document without an id gets one here, and each batch carries an `Idempotency-Key` reused on
191
+ * its retries, so a retried batch never writes twice.
187
192
  */
188
193
  async add(documents, options) {
189
194
  return (await this.write(documents, options)).map((d) => d.id);
@@ -191,9 +196,9 @@ export class Namespace {
191
196
  /**
192
197
  * `add` that returns what the write did with each document: its new version, to pass as
193
198
  * `ifVersion` on its next write, and its `result` (`unchanged` when Conare already held it as
194
- * sent: nothing was embedded or written). A conditional write retried after a lost response can
195
- * answer 409 `version_conflict` for its own first attempt: `get()` the document to tell.
196
- * `version` is null when the server did not answer one (a server older than versions): never
199
+ * sent: nothing was embedded or written). A conditional write retried after a lost response gets
200
+ * its first answer (the retry carries the batch's `Idempotency-Key`), not a `version_conflict`
201
+ * from its own first attempt. `version` is null when the server did not answer one (a server older than versions): never
197
202
  * pass it as `ifVersion`.
198
203
  */
199
204
  async write(documents, options) {
@@ -201,16 +206,18 @@ export class Namespace {
201
206
  const out = [];
202
207
  for (let i = 0; i < all.length; i += BATCH_SIZE) {
203
208
  const batch = all.slice(i, i + BATCH_SIZE);
209
+ const key = options?.idempotencyKey;
210
+ // With the caller's key, the API derives a missing id from it: the same on a repeat of the call.
204
211
  const body = await this.client.request("POST", this.path("/documents"), {
205
212
  documents: batch.map((d) => ({
206
- id: d.id ?? newDocumentId(),
213
+ id: d.id ?? (key ? undefined : newDocumentId()),
207
214
  text: d.text,
208
215
  metadata: d.metadata,
209
216
  user: d.user,
210
217
  seq: d.seq,
211
218
  if_version: d.ifVersion,
212
219
  })),
213
- }, options, true);
220
+ }, { ...options, idempotencyKey: key && i > 0 ? `${key}:${i / BATCH_SIZE}` : key });
214
221
  body.ids.forEach((id, j) => {
215
222
  const r = body.results?.[j];
216
223
  const result = { id, version: body.versions?.[j] ?? null };
@@ -241,7 +248,7 @@ export class Namespace {
241
248
  ...(options.id ? { id: options.id } : {}),
242
249
  ...(options.wait ? { wait: "true" } : {}),
243
250
  });
244
- const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout: 120_000, ...options }, true);
251
+ const body = await this.client.request("POST", this.path(`/files?${query}`), file, { timeout: 120_000, ...options });
245
252
  return {
246
253
  fileId: body.file_id,
247
254
  type: body.type,
@@ -257,8 +264,8 @@ export class Namespace {
257
264
  * Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what
258
265
  * the search fuses (default `["vector", "keyword"]`); `"sparse"` needs a namespace created with
259
266
  * a sparse index. `rerankDepth` (1-100) has the reranker rank every passage among the first
260
- * that many in a tournament of 20-passage windows (exact order for the first `topK`, at most
261
- * 20); unset, it reads one window of 20. `user` keeps the search to one user's documents and
267
+ * that many in windows of 20 passages, then reads the best 20 of them together in one final
268
+ * window that sets their order; unset, it reads one window of 20. `user` keeps the search to one user's documents and
262
269
  * `userPrefix` (ending in `:`) to a group's; both combine with `filter`.
263
270
  */
264
271
  async query(query, options = {}) {
@@ -271,7 +278,7 @@ export class Namespace {
271
278
  retrievers: options.retrievers,
272
279
  user: options.user,
273
280
  user_prefix: options.userPrefix,
274
- }, options, true);
281
+ }, options);
275
282
  return body.results;
276
283
  }
277
284
  /** One document by id, or null if it does not exist. */
@@ -315,8 +322,10 @@ export class Namespace {
315
322
  /** Delete every document matching filter (at least one condition), calling until none match. Returns how many were deleted. */
316
323
  async deleteWhere(filter, options) {
317
324
  let deleted = 0;
318
- for (;;) {
319
- const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, options);
325
+ const key = options?.idempotencyKey;
326
+ for (let round = 0;; round++) {
327
+ // Each round is its own call (the same body deletes the next batch): its own key.
328
+ const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { ...options, idempotencyKey: key && round > 0 ? `${key}:${round}` : key });
320
329
  deleted += out.deleted;
321
330
  if (!out.more)
322
331
  return deleted;
@@ -353,7 +362,7 @@ export class Sources {
353
362
  }
354
363
  /** Start a sync now. */
355
364
  async sync(id, options) {
356
- return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, undefined, options, true));
365
+ return toSource(await this.client.request("POST", `/sources/${segment(id)}/sync`, undefined, options));
357
366
  }
358
367
  /** Disconnect a source. Pass `deleteDocuments: true` to also delete what it synced. */
359
368
  async delete(id, options = {}) {
@@ -377,6 +386,7 @@ function toSource(s) {
377
386
  documents: s.documents,
378
387
  lastSyncedAt: s.last_synced_at ? new Date(s.last_synced_at) : null,
379
388
  createdAt: new Date(s.created_at),
389
+ ...(s.progress ? { recordsPulled: s.progress.records_pulled } : {}),
380
390
  };
381
391
  }
382
392
  function toError(res, text) {
@@ -391,6 +401,12 @@ function toError(res, text) {
391
401
  return new ConareError(res.status, error?.code ?? `http_${res.status}`, error?.message ?? (res.statusText || `HTTP ${res.status}`), error?.request_id ?? requestId);
392
402
  }
393
403
  const ID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
404
+ /** "idk_" and 32 random hex characters: one write call's Idempotency-Key. */
405
+ function newIdempotencyKey() {
406
+ const bytes = new Uint8Array(16);
407
+ globalThis.crypto.getRandomValues(bytes);
408
+ return "idk_" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
409
+ }
394
410
  /** "doc_" and 20 random base62 characters, the shape the API generates. */
395
411
  function newDocumentId() {
396
412
  const bytes = new Uint8Array(20);
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.18.0",
3
+ "version": "0.20.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
+ "bin": { "conare": "./dist/cli/main.js" },
8
9
  "exports": {
9
10
  ".": {
10
11
  "types": "./dist/index.d.ts",
@@ -14,8 +15,8 @@
14
15
  "files": ["dist"],
15
16
  "sideEffects": false,
16
17
  "scripts": {
17
- "build": "rm -rf dist && tsc -p tsconfig.json",
18
- "typecheck": "tsc -p tsconfig.json --noEmit",
18
+ "build": "rm -rf dist && tsc -p tsconfig.json && tsc -p tsconfig.cli.json && chmod +x dist/cli/main.js",
19
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.cli.json --noEmit",
19
20
  "test": "bun test",
20
21
  "prepublishOnly": "bun run build"
21
22
  },
@@ -26,6 +27,6 @@
26
27
  "engines": { "node": ">=18" },
27
28
  "devDependencies": {
28
29
  "@types/bun": "1.4.2",
29
- "typescript": "5.9.3"
30
+ "typescript": "6.0.3"
30
31
  }
31
32
  }