conare 0.18.0 → 0.19.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
@@ -112,7 +112,7 @@ await conare.rerank("refund window", ["a", "b"], { topK: 1 }); // [{ index, sc
112
112
 
113
113
  `rerank` takes 1-100 documents of 1-24,000 characters each (the query at most 8,192 characters, all
114
114
  together at most 256,000); more than 100 is a 400 `invalid_request`. More than 20 go through a
115
- tournament of 20-document windows that settles the exact order of the best `topK` (at most 20). A
115
+ tournament: windows of 20 documents, then one final window that reads the best 20 together and sets their order. A
116
116
  document no window read before the one-second budget ended, or whose window failed, is listed by
117
117
  index in `.unscored` and is not in the results; its score from another call would not compare.
118
118
 
@@ -142,9 +142,11 @@ await conare.sources.delete(source.id, { deleteDocuments: true });
142
142
 
143
143
  Every failure is a `ConareError` with `status`, `code`, `message` and `requestId`
144
144
  (`status` is 0 when no response arrived: `timeout`, `connection_error`). 429, 5xx and network
145
- errors are retried twice with backoff, honouring `Retry-After`. `sources.connect()` is retried only
146
- on 429 and 503, and `add()` gives every document without an id one of its own first, so a retry
147
- never creates anything twice.
145
+ errors are retried twice with backoff, honouring `Retry-After`. Every write carries an
146
+ `Idempotency-Key`, the same on each of its retries: the API answers a retry with the first answer
147
+ and does nothing again, so a retry never creates anything twice and a conditional write's retry is
148
+ not a `version_conflict`. Pass `{ idempotencyKey }` to make a call you repeat later (a restarted
149
+ job) the same call; within 24 hours its repeat gets the first answer.
148
150
 
149
151
  ```ts
150
152
  import { ConareError } from "conare";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.18.0";
1
+ export declare const VERSION = "0.19.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>;
@@ -145,6 +145,8 @@ export interface Source {
145
145
  documents: number;
146
146
  lastSyncedAt: Date | null;
147
147
  createdAt: Date;
148
+ /** While syncing: records read from the app so far in the run in flight. */
149
+ recordsPulled?: number;
148
150
  }
149
151
  export interface SourceType {
150
152
  type: string;
@@ -167,6 +169,16 @@ export interface RequestOptions {
167
169
  signal?: AbortSignal;
168
170
  /** Overrides the client timeout for this call, in milliseconds. */
169
171
  timeout?: number;
172
+ /**
173
+ * The `Idempotency-Key` sent with every request but a GET (the write routes honour it). By
174
+ * default the SDK makes one per call and sends it on each retry of the call; pass your own to make a call you repeat later (a
175
+ * job restarted after a crash) the same call: within 24 hours its repeat gets the first answer and
176
+ * writes nothing. A key is 1-255 visible ASCII characters, kept per API key; `write()` and `add()`
177
+ * send batch `n` after the first as `<key>:<n>` and leave documents without an id to the API, which
178
+ * derives their ids from the key; `deleteWhere()` sends round `n` after the first as `<key>:<n>`.
179
+ * The same key with another request is a 422 `idempotency_key_reused`.
180
+ */
181
+ idempotencyKey?: string;
170
182
  }
171
183
  /** Every failure the SDK throws. `status` is 0 when no response arrived. */
172
184
  export declare class ConareError extends Error {
@@ -230,15 +242,16 @@ export declare class Namespace {
230
242
  }>;
231
243
  /**
232
244
  * Add or replace documents. Accepts one or many; sends them in batches of 100. Returns the ids.
233
- * A document without an id gets one here, so a retried batch replaces instead of duplicating.
245
+ * A document without an id gets one here, and each batch carries an `Idempotency-Key` reused on
246
+ * its retries, so a retried batch never writes twice.
234
247
  */
235
248
  add(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<string[]>;
236
249
  /**
237
250
  * `add` that returns what the write did with each document: its new version, to pass as
238
251
  * `ifVersion` on its next write, and its `result` (`unchanged` when Conare already held it as
239
- * sent: nothing was embedded or written). A conditional write retried after a lost response can
240
- * answer 409 `version_conflict` for its own first attempt: `get()` the document to tell.
241
- * `version` is null when the server did not answer one (a server older than versions): never
252
+ * sent: nothing was embedded or written). A conditional write retried after a lost response gets
253
+ * its first answer (the retry carries the batch's `Idempotency-Key`), not a `version_conflict`
254
+ * from its own first attempt. `version` is null when the server did not answer one (a server older than versions): never
242
255
  * pass it as `ifVersion`.
243
256
  */
244
257
  write(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<WriteResult[]>;
@@ -259,8 +272,8 @@ export declare class Namespace {
259
272
  * Hybrid search, reranked. One result per document: its best passage. `retrievers` picks what
260
273
  * the search fuses (default `["vector", "keyword"]`); `"sparse"` needs a namespace created with
261
274
  * a sparse index. `rerankDepth` (1-100) has the reranker rank every passage among the first
262
- * that many in a tournament of 20-passage windows (exact order for the first `topK`, at most
263
- * 20); unset, it reads one window of 20. `user` keeps the search to one user's documents and
275
+ * that many in windows of 20 passages, then reads the best 20 of them together in one final
276
+ * window that sets their order; unset, it reads one window of 20. `user` keeps the search to one user's documents and
264
277
  * `userPrefix` (ending in `:`) to a group's; both combine with `filter`.
265
278
  */
266
279
  query(query: string, options?: RequestOptions & {
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.19.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,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -26,6 +26,6 @@
26
26
  "engines": { "node": ">=18" },
27
27
  "devDependencies": {
28
28
  "@types/bun": "1.4.2",
29
- "typescript": "5.9.3"
29
+ "typescript": "6.0.3"
30
30
  }
31
31
  }