conare 0.21.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
@@ -60,9 +60,9 @@ for await (const doc of docs.list()) {} // every document, page by page (
60
60
  await docs.delete("refunds"); // 404 document_not_found if it does not exist
61
61
  await docs.deleteMany(["a", "b"]); // up to 1000 ids in one call; missing ids are skipped. Returns the count
62
62
  await docs.deleteWhere({ team: "support" }); // every document matching the filter, whole documents. Returns the count
63
- await docs.uploadFile(bytes, "report.pdf"); // a PDF (one document per page) or an .xlsx (Markdown tables per sheet),
64
- // up to 20 MiB. The same name (or { id }) again replaces it.
65
- // 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 }:
66
66
  // scanned pages are OCR'd after the answer (ocrPending; { wait: true } reads them first)
67
67
  await docs.getFile("report.pdf"); // that upload's outcome, OCR after the answer included (kept 7 days)
68
68
  await docs.drop(); // delete the namespace and its documents (succeeds if already emptied; 404 namespace_not_found if never written)
@@ -78,7 +78,7 @@ Namespace names: 1-64 characters of `a-z 0-9 _ -`. Ids: up to 256 characters of
78
78
 
79
79
  ```ts
80
80
  await docs.query("how do refunds work?", {
81
- topK: 10, // 1-100, default 10
81
+ topK: 10, // 1-500, default 10
82
82
  filter: { team: "support" }, // optional metadata filter
83
83
  rerank: true, // default true
84
84
  retrievers: ["vector", "keyword"], // default; one of them alone searches with it alone
@@ -91,7 +91,7 @@ fuses: `"vector"` (the embedding model) and `"keyword"` (BM25; alone, BM25 alone
91
91
  rerank window (or of a query not reranked); the two scales do not compare.
92
92
 
93
93
  Filters match metadata values: `{ key: value }` means equals (or, for an array value,
94
- 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`:
95
95
 
96
96
  ```ts
97
97
  { $or: [{ team: "support" }, { year: { $in: [2024, 2025] } }] }
@@ -106,7 +106,7 @@ compare numbers, string bounds compare strings by their UTF-8 bytes, so ISO date
106
106
  { published_at: { $gte: "2025-06-01" } }
107
107
  ```
108
108
 
109
- 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`.
110
110
 
111
111
  ### Embed and rerank
112
112
 
@@ -189,6 +189,26 @@ await conare.events.list({ cursor: "0", types: ["run.*"] }); // { data: [{ seq,
189
189
  `sources.list()` and `sources.get()` answer custom sources too, with `kind: "custom"`. These
190
190
  calls send an `Idempotency-Key` when they create or delete something, so their retries are safe.
191
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.
211
+
192
212
  ### Errors
193
213
 
194
214
  Every failure is a `ConareError` with `status`, `code`, `message` and `requestId`
@@ -276,7 +296,10 @@ review comments; bots other than `greptile-apps[bot]` and `claude[bot]` are left
276
296
  the default branch into `<repo>-docs` (id: the path with `/` as `:`; metadata `kind: "doc"`,
277
297
  `path`, `title`, `author`, `date`, `url`). Later runs read only threads updated since the last one
278
298
  and files whose content changed; docs whose file was deleted are deleted. `--state <file>` sets
279
- 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.
280
303
 
281
304
  ## Development
282
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
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.21.0";
1
+ export declare const VERSION = "0.22.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>;
@@ -70,18 +70,27 @@ export interface WriteResult {
70
70
  chunksEmbedded?: number;
71
71
  storedSeq?: number;
72
72
  }
73
+ /** A file type `uploadFile` can declare: the file is read as that type (`jpg` and `tif` are accepted too). */
74
+ export type FileType = "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "png" | "jpeg" | "webp" | "tiff";
73
75
  /** What `uploadFile` stored. */
74
76
  export interface FileUpload {
75
77
  fileId: string;
76
- type: "pdf" | "xlsx";
78
+ /** The type it was read as: an image of any format is `image`. */
79
+ type: "pdf" | "xlsx" | "docx" | "pptx" | "csv" | "tsv" | "txt" | "md" | "image";
77
80
  /** The documents it made, in reading order. */
78
81
  ids: string[];
79
- /** A PDF's pages (null for a workbook). */
82
+ /** A PDF's pages (null for any other file). */
80
83
  pages: number | null;
81
- /** A workbook's sheets (null for a PDF). */
84
+ /** A workbook's sheets (null for any other file). */
82
85
  sheets: number | null;
83
- /** PDF pages read by OCR before the answer (`wait: true`); stored like the rest. */
86
+ /** A deck's slides (null for any other file). */
87
+ slides: number | null;
88
+ /** A deck's slides with no text (pictures only): not stored. */
89
+ slidesWithoutText: number[];
90
+ /** PDF or image pages read by OCR before the answer (`wait: true`); stored like the rest. */
84
91
  pagesOcr: number;
92
+ /** Pictures of a Word document or deck read by OCR before the answer (`wait: true`), each a document of its own. */
93
+ imagesOcr: number;
85
94
  /** PDF pages with no text even after OCR (blank, or OCR could not read them): not stored. */
86
95
  pagesWithoutText: number[];
87
96
  /**
@@ -392,6 +401,71 @@ export declare class ConareError extends Error {
392
401
  readonly requestId: string | null;
393
402
  constructor(status: number, code: string, message: string, requestId?: string | null);
394
403
  }
404
+ /** A file of `files.upload`, as `files.status` reads it. */
405
+ export interface StoredFile {
406
+ /** The file's id in its namespace (and user). */
407
+ id: string;
408
+ name: string;
409
+ namespace: string;
410
+ user: string | null;
411
+ /** The namespace's files source: the file's documents are `<sourceId>:<id>:<part>`. */
412
+ sourceId: string;
413
+ /** What it was parsed as: pdf, xlsx, docx, pptx, csv, tsv, txt, md or image. */
414
+ type: string | null;
415
+ /** Whether the type was declared rather than recognized. */
416
+ declared: boolean;
417
+ bytes: number;
418
+ sha256: string | null;
419
+ metadata: Metadata;
420
+ /** `ocr`: pages are being read by OCR, or wait to be tried again. */
421
+ state: "queued" | "parsing" | "ocr" | "ready" | "failed";
422
+ /** PDF pages, sheets, slides, Word parts or image frames. */
423
+ pages: number;
424
+ /** Pages stored from their text layer. */
425
+ pagesText: number;
426
+ /** Pages read by OCR with text. */
427
+ pagesOcr: number;
428
+ /** Blank pages, and pages OCR read as empty. */
429
+ pagesWithoutText: number[];
430
+ /** Pages waiting for OCR. */
431
+ ocrPending: number;
432
+ /** Pages OCR could not read after its retries; each keeps what an earlier upload stored for it. */
433
+ ocrFailed: number[];
434
+ documents: number;
435
+ /** Parts the write refused, each with why. */
436
+ rejected: {
437
+ id: string;
438
+ code: string;
439
+ message: string;
440
+ }[];
441
+ /** The locator fields its documents carry: page, sheet, rows, slide, heading, part, frame. */
442
+ locators: string[];
443
+ chunksEmbedded: number;
444
+ /** The file's latest parse. */
445
+ run: {
446
+ id: string;
447
+ kind: "parse" | "reparse";
448
+ state: string;
449
+ phase: string | null;
450
+ error: unknown;
451
+ retryAt?: Date;
452
+ };
453
+ /** When `failed`: `{ code, message }`. */
454
+ error: {
455
+ code: string;
456
+ message: string;
457
+ } | null;
458
+ updatedAt: Date;
459
+ }
460
+ /** What `files.upload` and `files.reparse` answer. */
461
+ export interface FileQueued {
462
+ /** `unchanged`: the same bytes and metadata as the file's last parse; nothing was queued. */
463
+ result?: "unchanged";
464
+ file: StoredFile;
465
+ run?: Run;
466
+ }
467
+ /** The largest file `files.upload` sends in one request; a larger one (up to 512 MiB) goes in parts. */
468
+ export declare const MAX_FILE_REQUEST_BYTES: number;
395
469
  /**
396
470
  * The Conare client.
397
471
  *
@@ -405,6 +479,8 @@ export declare class Conare {
405
479
  readonly runs: Runs;
406
480
  /** Files of documents written into a custom source. */
407
481
  readonly imports: Imports;
482
+ /** Files (PDF, Word, PowerPoint, Excel, CSV, text, images) kept as documents, a page each. */
483
+ readonly files: Files;
408
484
  /** Delete everything Conare holds of one of your users. */
409
485
  readonly users: Users;
410
486
  /** What changed, in order. */
@@ -484,9 +560,16 @@ export declare class Namespace {
484
560
  */
485
561
  write(documents: DocumentInput | DocumentInput[], options?: RequestOptions): Promise<WriteResult[]>;
486
562
  /**
487
- * Store a PDF or an Excel workbook (.xlsx), at most 20 MiB: one document per PDF page with a
488
- * text layer (`<fileId>:page-3`) and Markdown tables per worksheet (`<fileId>:Sheet1-1`), each
489
- * with `file`, `file_id`, `file_type` and `page` or `sheet` metadata. `fileId` defaults to the
563
+ * Store a PDF, a Word document (.docx), a PowerPoint deck (.pptx), an Excel workbook (.xlsx), a CSV or
564
+ * TSV, a text or Markdown file, or an image (PNG, JPEG, WebP, TIFF), at most 20 MiB. Say its type with
565
+ * `type`: it is read as that type, and bytes of another type are refused (415) rather than misread;
566
+ * without it the type comes from the bytes, then the name. One document per PDF page with a text
567
+ * layer (`<fileId>:page-3`), per image page (read by OCR), a CSV as Markdown tables with its header
568
+ * on every part and the rows each holds in `rows` metadata, a Word document as
569
+ * Markdown (`<fileId>:part-1`, more parts past 240 KiB), one per slide with text (`<fileId>:slide-2`:
570
+ * title, shapes in reading order, tables, speaker notes) and Markdown tables per worksheet
571
+ * (`<fileId>:Sheet1-1`), each with `file`, `file_id`, `file_type` and `page`, `part`, `slide` or
572
+ * `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
490
573
  * name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
491
574
  * such names do not collide); uploading the same one again replaces every document it made, and two
492
575
  * uploads of one id run one at a time. Pages
@@ -497,6 +580,7 @@ export declare class Namespace {
497
580
  uploadFile(file: Blob | Uint8Array | ArrayBuffer, name: string, options?: RequestOptions & {
498
581
  id?: string;
499
582
  wait?: boolean;
583
+ type?: FileType;
500
584
  }): Promise<FileUpload>;
501
585
  /**
502
586
  * An upload's outcome: the last upload of `fileId` here in the last 7 days. While OCR reads after the
@@ -507,7 +591,7 @@ export declare class Namespace {
507
591
  /**
508
592
  * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
509
593
  * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
510
- * retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-500) is how many of the
594
+ * retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-1000) is how many of the
511
595
  * first passages the reranker ranks; unset, the first 20. `user` keeps the search to one user's documents and
512
596
  * `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
513
597
  * `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
@@ -709,6 +793,50 @@ export declare class Imports {
709
793
  filename?: string;
710
794
  }, options?: RequestOptions): Promise<Run>;
711
795
  }
796
+ export declare class Files {
797
+ private readonly client;
798
+ constructor(client: Conare);
799
+ /**
800
+ * Upload a file: it is stored and parsed in the background into a document per page, sheet part,
801
+ * slide or Word part, each citing where it came from; pages without text are read by OCR. Declare
802
+ * its `type` when you know it: it is then parsed as that type, and bytes of another type are a
803
+ * ConareError 415 `type_mismatch`. Up to 64 MiB goes in one request, larger files (up to 512 MiB)
804
+ * in parts of 16 MiB. `wait` (seconds, at most 100) holds the answer until the file is ready.
805
+ */
806
+ upload(params: {
807
+ file: Blob | Uint8Array | ArrayBuffer | string;
808
+ name: string;
809
+ namespace: string;
810
+ user?: string;
811
+ id?: string;
812
+ type?: FileType;
813
+ metadata?: Metadata;
814
+ wait?: number;
815
+ }, options?: RequestOptions): Promise<FileQueued>;
816
+ /** The files `ids` of a namespace (and user), or, without ids, its first 100 files. */
817
+ status(params: {
818
+ namespace: string;
819
+ user?: string;
820
+ ids?: string[];
821
+ }, options?: RequestOptions): Promise<StoredFile[]>;
822
+ /** Parse a file again from its stored original. */
823
+ reparse(id: string, params: {
824
+ namespace: string;
825
+ user?: string;
826
+ wait?: number;
827
+ }, options?: RequestOptions): Promise<FileQueued>;
828
+ /**
829
+ * Wait until every file of `ids` is ready or failed (polling `status` every `interval` ms), at most
830
+ * `timeout` ms (10 minutes by default): the files as they ended, or a ConareError `timeout`.
831
+ */
832
+ waitUntilReady(params: {
833
+ namespace: string;
834
+ user?: string;
835
+ ids: string[];
836
+ timeout?: number;
837
+ interval?: number;
838
+ }, options?: RequestOptions): Promise<StoredFile[]>;
839
+ }
712
840
  export declare class Users {
713
841
  private readonly client;
714
842
  constructor(client: Conare);
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.21.0";
2
+ export const VERSION = "0.22.0";
3
3
  const DEFAULT_BASE_URL = "https://api.conare.ai";
4
4
  const BATCH_SIZE = 100;
5
5
  const CHECK_BATCH = 1000;
@@ -10,7 +10,10 @@ function toFileUpload(body) {
10
10
  ids: body.ids,
11
11
  pages: body.pages ?? null,
12
12
  sheets: body.sheets ?? null,
13
+ slides: body.slides ?? null,
14
+ slidesWithoutText: body.slides_without_text ?? [],
13
15
  pagesOcr: body.pages_ocr ?? 0,
16
+ imagesOcr: body.images_ocr ?? 0,
14
17
  pagesWithoutText: body.pages_without_text ?? [],
15
18
  ocrPending: body.ocr_pending ?? [],
16
19
  };
@@ -59,6 +62,22 @@ function queryBody(query, options) {
59
62
  exclude_ids: options.excludeIds,
60
63
  };
61
64
  }
65
+ /** The largest file `files.upload` sends in one request; a larger one (up to 512 MiB) goes in parts. */
66
+ export const MAX_FILE_REQUEST_BYTES = 64 * 1024 * 1024;
67
+ function toStoredFile(f) {
68
+ return {
69
+ id: f.id, name: f.name, namespace: f.namespace, user: f.user, sourceId: f.source_id, type: f.type, declared: f.declared,
70
+ bytes: f.bytes, sha256: f.sha256, metadata: f.metadata ?? {}, state: f.state, pages: f.pages, pagesText: f.pages_text,
71
+ pagesOcr: f.pages_ocr, pagesWithoutText: f.pages_without_text ?? [], ocrPending: f.ocr_pending, ocrFailed: f.ocr_failed ?? [],
72
+ documents: f.documents, rejected: f.rejected ?? [], locators: f.locators ?? [], chunksEmbedded: f.chunks_embedded ?? 0,
73
+ run: { id: f.run.id, kind: f.run.kind, state: f.run.state, phase: f.run.phase, error: f.run.error,
74
+ ...(f.run.retry_at ? { retryAt: new Date(f.run.retry_at) } : {}) },
75
+ error: f.error ?? null, updatedAt: new Date(f.updated_at),
76
+ };
77
+ }
78
+ function toFileQueued(body) {
79
+ return { ...(body.result ? { result: body.result } : {}), file: toStoredFile(body.file), ...(body.run ? { run: toRun(body.run) } : {}) };
80
+ }
62
81
  // ---- Client ----------------------------------------------------------------
63
82
  /**
64
83
  * The Conare client.
@@ -73,6 +92,8 @@ export class Conare {
73
92
  runs;
74
93
  /** Files of documents written into a custom source. */
75
94
  imports;
95
+ /** Files (PDF, Word, PowerPoint, Excel, CSV, text, images) kept as documents, a page each. */
96
+ files;
76
97
  /** Delete everything Conare holds of one of your users. */
77
98
  users;
78
99
  /** What changed, in order. */
@@ -102,6 +123,7 @@ export class Conare {
102
123
  this.sources = new Sources(this);
103
124
  this.runs = new Runs(this);
104
125
  this.imports = new Imports(this);
126
+ this.files = new Files(this);
105
127
  this.users = new Users(this);
106
128
  this.events = new Events(this);
107
129
  }
@@ -301,9 +323,16 @@ export class Namespace {
301
323
  return out;
302
324
  }
303
325
  /**
304
- * Store a PDF or an Excel workbook (.xlsx), at most 20 MiB: one document per PDF page with a
305
- * text layer (`<fileId>:page-3`) and Markdown tables per worksheet (`<fileId>:Sheet1-1`), each
306
- * with `file`, `file_id`, `file_type` and `page` or `sheet` metadata. `fileId` defaults to the
326
+ * Store a PDF, a Word document (.docx), a PowerPoint deck (.pptx), an Excel workbook (.xlsx), a CSV or
327
+ * TSV, a text or Markdown file, or an image (PNG, JPEG, WebP, TIFF), at most 20 MiB. Say its type with
328
+ * `type`: it is read as that type, and bytes of another type are refused (415) rather than misread;
329
+ * without it the type comes from the bytes, then the name. One document per PDF page with a text
330
+ * layer (`<fileId>:page-3`), per image page (read by OCR), a CSV as Markdown tables with its header
331
+ * on every part and the rows each holds in `rows` metadata, a Word document as
332
+ * Markdown (`<fileId>:part-1`, more parts past 240 KiB), one per slide with text (`<fileId>:slide-2`:
333
+ * title, shapes in reading order, tables, speaker notes) and Markdown tables per worksheet
334
+ * (`<fileId>:Sheet1-1`), each with `file`, `file_id`, `file_type` and `page`, `part`, `slide` or
335
+ * `sheet` metadata. Slides with no text are listed in `slidesWithoutText`. `fileId` defaults to the
307
336
  * name in id characters (a name with characters outside ASCII also gets 8 hex digits of its hash, so
308
337
  * such names do not collide); uploading the same one again replaces every document it made, and two
309
338
  * uploads of one id run one at a time. Pages
@@ -314,6 +343,7 @@ export class Namespace {
314
343
  async uploadFile(file, name, options = {}) {
315
344
  const query = new URLSearchParams({
316
345
  name,
346
+ ...(options.type ? { type: options.type } : {}),
317
347
  ...(options.id ? { id: options.id } : {}),
318
348
  ...(options.wait ? { wait: "true" } : {}),
319
349
  });
@@ -332,7 +362,7 @@ export class Namespace {
332
362
  /**
333
363
  * Hybrid search, reranked. One result per document: its best passage; `topK` documents when that
334
364
  * many match. `retrievers` picks what the search fuses (default `["vector", "keyword"]`; listed
335
- * retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-500) is how many of the
365
+ * retrievers run as listed, also on a vector-only custom model). `rerankDepth` (1-1000) is how many of the
336
366
  * first passages the reranker ranks; unset, the first 20. `user` keeps the search to one user's documents and
337
367
  * `userPrefix` (ending in `:`) to a group's; both combine with `filter`. An empty `user` or
338
368
  * `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
@@ -661,13 +691,95 @@ export class Imports {
661
691
  const key = options.idempotencyKey;
662
692
  for (let n = 1; n <= upload.parts; n++) {
663
693
  const part = bytes.subarray((n - 1) * upload.part_size, n * upload.part_size);
664
- await this.client.request("PUT", `/uploads/${segment(upload.id)}/parts/${n}`, part, { timeout: 300_000, ...options, idempotencyKey: stepKey(key, `part-${n}`) }, { "Content-MD5": base64(md5(part)) });
694
+ await this.client.request("PUT", `/uploads/${segment(upload.id)}/parts/${n}`, part, { timeout: 300_000, ...options, idempotencyKey: stepKey(key, `part-${n}`) }, { "Content-MD5": contentMd5(part) });
665
695
  }
666
696
  await this.client.request("POST", `/uploads/${segment(upload.id)}/complete`, { purpose: "import" }, { ...options, idempotencyKey: stepKey(key, "complete") });
667
697
  const body = await this.client.request("POST", `/sources/${segment(sourceId)}/imports`, { upload: upload.id, mode: params.mode ?? "delta", expected: params.expected, allow_mass_delete: params.allowMassDelete }, { ...options, idempotencyKey: stepKey(key, "import") });
668
698
  return toRun(body.run);
669
699
  }
670
700
  }
701
+ export class Files {
702
+ client;
703
+ constructor(client) {
704
+ this.client = client;
705
+ }
706
+ /**
707
+ * Upload a file: it is stored and parsed in the background into a document per page, sheet part,
708
+ * slide or Word part, each citing where it came from; pages without text are read by OCR. Declare
709
+ * its `type` when you know it: it is then parsed as that type, and bytes of another type are a
710
+ * ConareError 415 `type_mismatch`. Up to 64 MiB goes in one request, larger files (up to 512 MiB)
711
+ * in parts of 16 MiB. `wait` (seconds, at most 100) holds the answer until the file is ready.
712
+ */
713
+ async upload(params, options = {}) {
714
+ const f = params.file;
715
+ const bytes = typeof f === "string"
716
+ ? new TextEncoder().encode(f)
717
+ : f instanceof Uint8Array
718
+ ? f
719
+ : f instanceof ArrayBuffer
720
+ ? new Uint8Array(f)
721
+ : new Uint8Array(await f.arrayBuffer());
722
+ const timeout = options.timeout ?? 300_000;
723
+ if (bytes.length <= MAX_FILE_REQUEST_BYTES) {
724
+ const q = new URLSearchParams({ namespace: params.namespace, name: params.name });
725
+ if (params.user)
726
+ q.set("user", params.user);
727
+ if (params.id)
728
+ q.set("id", params.id);
729
+ if (params.type)
730
+ q.set("type", params.type);
731
+ if (params.metadata)
732
+ q.set("metadata", JSON.stringify(params.metadata));
733
+ if (params.wait !== undefined)
734
+ q.set("wait", String(params.wait));
735
+ return toFileQueued(await this.client.request("POST", `/files?${q}`, bytes, { ...options, timeout }));
736
+ }
737
+ const upload = await this.client.request("POST", "/uploads", { bytes: bytes.length, filename: params.name, purpose: "file" }, options);
738
+ const key = options.idempotencyKey;
739
+ for (let n = 1; n <= upload.parts; n++) {
740
+ const part = bytes.subarray((n - 1) * upload.part_size, n * upload.part_size);
741
+ await this.client.request("PUT", `/uploads/${segment(upload.id)}/parts/${n}`, part, { timeout: 300_000, ...options, idempotencyKey: stepKey(key, `part-${n}`) }, { "Content-MD5": contentMd5(part) });
742
+ }
743
+ return toFileQueued(await this.client.request("POST", `/uploads/${segment(upload.id)}/complete`, { purpose: "file", namespace: params.namespace, user: params.user, id: params.id, type: params.type, name: params.name,
744
+ metadata: params.metadata, wait: params.wait }, { ...options, timeout, idempotencyKey: stepKey(key, "complete") }));
745
+ }
746
+ /** The files `ids` of a namespace (and user), or, without ids, its first 100 files. */
747
+ async status(params, options = {}) {
748
+ const q = new URLSearchParams({ namespace: params.namespace });
749
+ if (params.user)
750
+ q.set("user", params.user);
751
+ if (params.ids)
752
+ q.set("ids", params.ids.join(","));
753
+ else
754
+ q.set("limit", "100");
755
+ const body = await this.client.request("GET", `/files/status?${q}`, undefined, options);
756
+ return body.data.map(toStoredFile);
757
+ }
758
+ /** Parse a file again from its stored original. */
759
+ async reparse(id, params, options = {}) {
760
+ const q = new URLSearchParams({ namespace: params.namespace });
761
+ if (params.user)
762
+ q.set("user", params.user);
763
+ if (params.wait !== undefined)
764
+ q.set("wait", String(params.wait));
765
+ return toFileQueued(await this.client.request("POST", `/files/${segment(id)}/reparse?${q}`, undefined, { timeout: 300_000, ...options }));
766
+ }
767
+ /**
768
+ * Wait until every file of `ids` is ready or failed (polling `status` every `interval` ms), at most
769
+ * `timeout` ms (10 minutes by default): the files as they ended, or a ConareError `timeout`.
770
+ */
771
+ async waitUntilReady(params, options = {}) {
772
+ const deadline = Date.now() + (params.timeout ?? 600_000);
773
+ for (;;) {
774
+ const files = await this.status(params, options);
775
+ if (files.length === params.ids.length && files.every((f) => f.state === "ready" || f.state === "failed"))
776
+ return files;
777
+ if (Date.now() >= deadline)
778
+ throw new ConareError(0, "timeout", `Files still parsing after ${params.timeout ?? 600_000} ms.`);
779
+ await sleep(params.interval ?? 2_000, options.signal);
780
+ }
781
+ }
782
+ }
671
783
  export class Users {
672
784
  client;
673
785
  constructor(client) {
@@ -819,7 +931,20 @@ function base64(bytes) {
819
931
  bin += String.fromCharCode(b);
820
932
  return btoa(bin);
821
933
  }
822
- // MD5 (RFC 1321), for an upload part's Content-MD5: WebCrypto has no MD5, and the SDK imports nothing.
934
+ let nodeCrypto;
935
+ function contentMd5(data) {
936
+ if (nodeCrypto === undefined) {
937
+ try {
938
+ const p = globalThis.process;
939
+ nodeCrypto = p?.getBuiltinModule?.("node:crypto") ?? null;
940
+ }
941
+ catch {
942
+ nodeCrypto = null;
943
+ }
944
+ }
945
+ return nodeCrypto ? nodeCrypto.createHash("md5").update(data).digest("base64") : base64(md5(data));
946
+ }
947
+ // MD5 (RFC 1321) in JS, for runtimes without node:crypto.
823
948
  const MD5_S = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
824
949
  const MD5_K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
825
950
  function md5(data) {
@@ -836,18 +961,29 @@ function md5(data) {
836
961
  m[j] = view.getUint32(off + j * 4, true);
837
962
  let a = a0, b = b0, c = c0, d = d0;
838
963
  for (let i = 0; i < 64; i++) {
964
+ // Plain assignments: destructuring allocates two arrays a round.
839
965
  let f, g;
840
- if (i < 16)
841
- [f, g] = [(b & c) | (~b & d), i];
842
- else if (i < 32)
843
- [f, g] = [(d & b) | (~d & c), (5 * i + 1) % 16];
844
- else if (i < 48)
845
- [f, g] = [b ^ c ^ d, (3 * i + 5) % 16];
846
- else
847
- [f, g] = [c ^ (b | ~d), (7 * i) % 16];
966
+ if (i < 16) {
967
+ f = (b & c) | (~b & d);
968
+ g = i;
969
+ }
970
+ else if (i < 32) {
971
+ f = (d & b) | (~d & c);
972
+ g = (5 * i + 1) % 16;
973
+ }
974
+ else if (i < 48) {
975
+ f = b ^ c ^ d;
976
+ g = (3 * i + 5) % 16;
977
+ }
978
+ else {
979
+ f = c ^ (b | ~d);
980
+ g = (7 * i) % 16;
981
+ }
848
982
  const sum = (a + f + MD5_K[i] + m[g]) >>> 0;
849
983
  const shift = MD5_S[(i >> 4) * 4 + (i % 4)];
850
- [a, d, c] = [d, c, b];
984
+ a = d;
985
+ d = c;
986
+ c = b;
851
987
  b = (b + ((sum << shift) | (sum >>> (32 - shift)))) >>> 0;
852
988
  }
853
989
  a0 = (a0 + a) >>> 0;
@@ -942,11 +1078,16 @@ function sleep(ms, signal) {
942
1078
  return new Promise((resolve, reject) => {
943
1079
  if (signal?.aborted)
944
1080
  return reject(signal.reason);
945
- const timer = setTimeout(resolve, ms);
946
- signal?.addEventListener("abort", () => {
1081
+ const onAbort = () => {
947
1082
  clearTimeout(timer);
948
1083
  reject(signal.reason);
949
- }, { once: true });
1084
+ };
1085
+ // The caller's signal may live for the whole process: its listener goes when the timer fires.
1086
+ const timer = setTimeout(() => {
1087
+ signal?.removeEventListener("abort", onAbort);
1088
+ resolve();
1089
+ }, ms);
1090
+ signal?.addEventListener("abort", onAbort, { once: true });
950
1091
  });
951
1092
  }
952
1093
  function env(name) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "conare",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "TypeScript client for Conare: add documents, query them, connect apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",