conare 0.25.1 → 0.26.1
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 +15 -2
- package/dist/cli/config.js +5 -2
- package/dist/cli/github/api.js +3 -0
- package/dist/cli/github/sync.js +4 -1
- package/dist/cli/main.js +6 -2
- package/dist/cli/sync.js +30 -4
- package/dist/cli/upload.js +10 -7
- package/dist/index.d.ts +62 -6
- package/dist/index.js +27 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ new Conare({ organization: "org_…" }) // acts for that one (X-Conare-
|
|
|
36
36
|
new Conare({ gzip: false }) // JSON bodies of 8 KiB or more go gzip by default
|
|
37
37
|
```
|
|
38
38
|
|
|
39
|
-
Every method also takes `{ signal, timeout }` as its last option.
|
|
39
|
+
Every method also takes `{ signal, timeout }` as its last option. The default timeout is 60 s, and 120 s for a write of documents.
|
|
40
40
|
|
|
41
41
|
A key acts for its own organization. A multi-organization key (made in the console by an admin of
|
|
42
42
|
each organization it names) acts for any of them: make one client per organization with
|
|
@@ -112,6 +112,18 @@ compare numbers, string bounds compare strings by their UTF-8 bytes, so ISO date
|
|
|
112
112
|
|
|
113
113
|
`$ne` and `$nin` work in queries; a delete by filter with one answers 400 `invalid_filter`.
|
|
114
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
|
+
|
|
115
127
|
### Embed and rerank
|
|
116
128
|
|
|
117
129
|
```ts
|
|
@@ -278,7 +290,8 @@ await sessions.query("why did we drop the Redis cache?", { filter: { project: "s
|
|
|
278
290
|
|
|
279
291
|
It reads `~/.claude/projects` (or `$CLAUDE_CONFIG_DIR`) and `~/.codex/sessions` (or `$CODEX_HOME`).
|
|
280
292
|
The key comes from `--key`, else `CONARE_API_KEY`, else `~/.conare/sync.json`. What the server
|
|
281
|
-
already has is kept in `~/.conare/sync-state.json
|
|
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`.
|
|
282
295
|
`--install` copies the command to `~/.conare/sync/<version>/`, checks the copy file by file, runs
|
|
283
296
|
it once, and only then adds a launchd agent (`ai.conare.sync`) on macOS or a systemd user timer on
|
|
284
297
|
Linux. Every run adds a line to `~/.conare/sync.log` (uploaded, skipped and failed counts, duration).
|
package/dist/cli/config.js
CHANGED
|
@@ -36,8 +36,11 @@ export function readExcluded(file) {
|
|
|
36
36
|
try {
|
|
37
37
|
text = readFileSync(file, "utf8");
|
|
38
38
|
}
|
|
39
|
-
catch {
|
|
40
|
-
|
|
39
|
+
catch (err) {
|
|
40
|
+
// Only an absent file means none: an unreadable one would upload what it excludes.
|
|
41
|
+
if (err.code === "ENOENT")
|
|
42
|
+
return new Set();
|
|
43
|
+
throw err;
|
|
41
44
|
}
|
|
42
45
|
return new Set(text.split(/\r?\n/).map((l) => l.replace(/#.*/, "").trim()).filter(Boolean));
|
|
43
46
|
}
|
package/dist/cli/github/api.js
CHANGED
|
@@ -76,6 +76,9 @@ export class GitHub {
|
|
|
76
76
|
for (const item of (await res.json()))
|
|
77
77
|
yield item;
|
|
78
78
|
url = nextLink(res.headers.get("link"));
|
|
79
|
+
// Every request carries the token: a next page goes nowhere else.
|
|
80
|
+
if (url && new URL(url).origin !== new URL(this.base).origin)
|
|
81
|
+
throw new GitHubError(0, `GitHub's next page is on another host: ${new URL(url).host}`);
|
|
79
82
|
}
|
|
80
83
|
}
|
|
81
84
|
async all(path) {
|
package/dist/cli/github/sync.js
CHANGED
|
@@ -264,7 +264,10 @@ async function fetchDocs(gh, repo, commit, files) {
|
|
|
264
264
|
for (const [j, f] of chunk.entries()) {
|
|
265
265
|
const blob = data.repository[`b${j}`];
|
|
266
266
|
const node = data.repository.head?.[`h${j}`]?.nodes?.[0];
|
|
267
|
-
|
|
267
|
+
// No blob is not a binary file: recorded as one, it is never fetched again and its document goes.
|
|
268
|
+
if (!blob)
|
|
269
|
+
throw new Error(`${repo}: GitHub answered no blob for ${f.path}`);
|
|
270
|
+
if (blob.isBinary) {
|
|
268
271
|
out.set(f.path, "binary");
|
|
269
272
|
continue;
|
|
270
273
|
}
|
package/dist/cli/main.js
CHANGED
|
@@ -166,9 +166,13 @@ async function syncSessions(args, paths, apiKey, say, fail) {
|
|
|
166
166
|
say(report.documents > 0 || report.deleted > 0
|
|
167
167
|
? `Synced ${report.sessions} sessions: ${report.documents} documents, ${formatBytes(report.bytes)}. ${report.unchanged} unchanged.`
|
|
168
168
|
: `Up to date: ${report.unchanged} sessions.`);
|
|
169
|
-
|
|
169
|
+
if (report.unread > 0)
|
|
170
|
+
say(`${report.unread} transcripts hold no message this version can read; they are read again next run.`);
|
|
171
|
+
for (const path of report.unreadable)
|
|
172
|
+
fail(`Could not read, tried again next run: ${path}`);
|
|
173
|
+
code = report.rejected.length > 0 || report.unreadable.length > 0 ? INCOMPLETE : 0;
|
|
170
174
|
if (code)
|
|
171
|
-
error = `${report.rejected.length} documents not accepted`;
|
|
175
|
+
error = `${report.rejected.length} documents not accepted, ${report.unreadable.length} transcripts not read`;
|
|
172
176
|
}
|
|
173
177
|
catch (err) {
|
|
174
178
|
if (err instanceof ConareError && err.status === 401) {
|
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) })),
|
|
@@ -18,7 +18,7 @@ export async function runSync(opts) {
|
|
|
18
18
|
const ns = opts.client?.namespace(NAMESPACE);
|
|
19
19
|
const log = opts.log ?? (() => { });
|
|
20
20
|
const state = loadState(opts.stateFile, opts.account);
|
|
21
|
-
const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, excluded: 0, deleted: 0, rejected: [], planned: [] };
|
|
21
|
+
const report = { sessions: 0, documents: 0, bytes: 0, unchanged: 0, excluded: 0, unread: 0, unreadable: [], deleted: 0, rejected: [], planned: [] };
|
|
22
22
|
// The layout the server holds for a session: what the state said this tool stored last;
|
|
23
23
|
// on a fresh state (the first sync, after the migration of older history), or for a session
|
|
24
24
|
// whose upload an earlier run cut short after some of its documents were accepted (0: any
|
|
@@ -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);
|
|
@@ -124,15 +128,22 @@ export async function runSync(opts) {
|
|
|
124
128
|
const transcript = file.read();
|
|
125
129
|
const project = projectName(transcript.cwd);
|
|
126
130
|
// Not stamped: taken off the list, the project's sessions upload on the next run.
|
|
127
|
-
|
|
131
|
+
// With a list, a session of no known project may be on it: held back too.
|
|
132
|
+
if (project === undefined ? opts.exclude?.size : opts.exclude?.has(project)) {
|
|
128
133
|
report.excluded++;
|
|
129
134
|
return;
|
|
130
135
|
}
|
|
136
|
+
// A new record format reads as no messages, and a stamp would keep the file from the CLI that can read it.
|
|
137
|
+
if (transcript.messages.length === 0) {
|
|
138
|
+
report.unread++;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
131
141
|
base = baseId(transcript);
|
|
132
|
-
docs =
|
|
142
|
+
docs = toDocuments(transcript, project);
|
|
133
143
|
}
|
|
134
144
|
catch (err) {
|
|
135
145
|
log(`Skipped ${file.path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
146
|
+
report.unreadable.push(file.path);
|
|
136
147
|
return;
|
|
137
148
|
}
|
|
138
149
|
// Two files of one session (a session copied between projects), even in different
|
|
@@ -202,6 +213,21 @@ async function settle(ns, state, entry, report, held) {
|
|
|
202
213
|
}
|
|
203
214
|
state.files[entry.path] = entry.stamp;
|
|
204
215
|
}
|
|
216
|
+
/** Drop what the server no longer holds from the state; every file is then read again, as its stamp says nothing of that. */
|
|
217
|
+
function forgetGone(state, listed) {
|
|
218
|
+
let gone = false;
|
|
219
|
+
for (const id of Object.keys(state.documents)) {
|
|
220
|
+
const { base, part } = splitPart(id);
|
|
221
|
+
const held = listed.get(base);
|
|
222
|
+
if (part === undefined ? held?.whole : held?.parts.includes(part))
|
|
223
|
+
continue;
|
|
224
|
+
delete state.documents[id];
|
|
225
|
+
state.parts[base] = 0;
|
|
226
|
+
gone = true;
|
|
227
|
+
}
|
|
228
|
+
if (gone)
|
|
229
|
+
state.files = {};
|
|
230
|
+
}
|
|
205
231
|
/** Stat every file (skipping ones that vanished) and order newest first, so a cut-short run keeps the recent work. */
|
|
206
232
|
function newestFirst(files) {
|
|
207
233
|
const out = [];
|
package/dist/cli/upload.js
CHANGED
|
@@ -9,7 +9,6 @@ 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
|
-
const WRITE_TIMEOUT_MS = 120_000;
|
|
13
12
|
/** Groups documents in order into batches within both limits. */
|
|
14
13
|
export function batches(docs, maxDocs = BATCH_DOCUMENTS, maxBytes = BATCH_BYTES) {
|
|
15
14
|
const out = [];
|
|
@@ -41,7 +40,7 @@ function isDocumentError(err) {
|
|
|
41
40
|
export async function sendBatch(ns, batch) {
|
|
42
41
|
const unchanged = (results) => results.filter((r) => r.result === "unchanged").length;
|
|
43
42
|
try {
|
|
44
|
-
return { accepted: batch, unchanged: unchanged(await ns.write(batch
|
|
43
|
+
return { accepted: batch, unchanged: unchanged(await ns.write(batch)), rejected: [] };
|
|
45
44
|
}
|
|
46
45
|
catch (err) {
|
|
47
46
|
if (!isDocumentError(err))
|
|
@@ -52,7 +51,7 @@ export async function sendBatch(ns, batch) {
|
|
|
52
51
|
const result = { accepted: [], unchanged: 0, rejected: [] };
|
|
53
52
|
for (const doc of batch) {
|
|
54
53
|
try {
|
|
55
|
-
result.unchanged += unchanged(await ns.write(doc
|
|
54
|
+
result.unchanged += unchanged(await ns.write(doc));
|
|
56
55
|
result.accepted.push(doc);
|
|
57
56
|
}
|
|
58
57
|
catch (err) {
|
|
@@ -78,16 +77,20 @@ async function deleteIfPresent(ns, id) {
|
|
|
78
77
|
/** Loop guard for the part probe; a session in parts of PART_BYTES would need to exceed 25 GB. */
|
|
79
78
|
const MAX_PARTS = 100_000;
|
|
80
79
|
const PART_ID = /^(.+):part:(\d{6})$/;
|
|
80
|
+
/** A document id as its session and, for one stored in parts, its part. */
|
|
81
|
+
export function splitPart(id) {
|
|
82
|
+
const m = PART_ID.exec(id);
|
|
83
|
+
return m ? { base: m[1], part: Number(m[2]) } : { base: id };
|
|
84
|
+
}
|
|
81
85
|
/** List every id in the namespace once and group them by session; an absent namespace holds nothing. */
|
|
82
86
|
export async function listLayouts(ns) {
|
|
83
87
|
const layouts = new Map();
|
|
84
88
|
try {
|
|
85
89
|
for await (const doc of ns.list({ limit: 100 })) {
|
|
86
|
-
const
|
|
87
|
-
const base = m ? m[1] : doc.id;
|
|
90
|
+
const { base, part } = splitPart(doc.id);
|
|
88
91
|
const held = layouts.get(base) ?? { whole: false, parts: [] };
|
|
89
|
-
if (
|
|
90
|
-
held.parts.push(
|
|
92
|
+
if (part !== undefined)
|
|
93
|
+
held.parts.push(part);
|
|
91
94
|
else
|
|
92
95
|
held.whole = true;
|
|
93
96
|
layouts.set(base, held);
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
1
|
+
export declare const VERSION = "0.26.1";
|
|
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
|
|
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;
|
|
@@ -200,7 +224,8 @@ 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
|
|
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
231
|
/** The files source of the namespace (and user): the file's document is `<sourceId>:<fileId>`. */
|
|
@@ -272,6 +297,28 @@ export interface QueryOptions extends RequestOptions {
|
|
|
272
297
|
/** 2 searches again from the best results, for answers that span documents (not with `queryPages`). */
|
|
273
298
|
hops?: 1 | 2;
|
|
274
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
|
+
}
|
|
275
322
|
/** One page of `Namespace.queryPages`. */
|
|
276
323
|
export interface QueryPage {
|
|
277
324
|
results: QueryResult[];
|
|
@@ -481,7 +528,7 @@ export interface ConareOptions {
|
|
|
481
528
|
apiKey?: string;
|
|
482
529
|
/** Defaults to CONARE_BASE_URL, then https://api.conare.ai. */
|
|
483
530
|
baseURL?: string;
|
|
484
|
-
/** Per-request timeout in milliseconds. Default 60000. */
|
|
531
|
+
/** Per-request timeout in milliseconds. Default 60000, and 120000 for a write of documents, which the API may take 110 s over. */
|
|
485
532
|
timeout?: number;
|
|
486
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. */
|
|
487
534
|
maxRetries?: number;
|
|
@@ -553,6 +600,7 @@ export declare class Conare {
|
|
|
553
600
|
readonly organization: string | undefined;
|
|
554
601
|
private readonly apiKey;
|
|
555
602
|
private readonly timeout;
|
|
603
|
+
readonly writeTimeout: number;
|
|
556
604
|
private readonly maxRetries;
|
|
557
605
|
private readonly fetchFn;
|
|
558
606
|
private gzip;
|
|
@@ -615,10 +663,12 @@ export declare class Namespace {
|
|
|
615
663
|
* Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
|
|
616
664
|
* (one of your organization's models from `GET /models`) needs this: a write creates one with the
|
|
617
665
|
* default model. Its model never changes: creating it again with another one is a 409. Returns
|
|
618
|
-
* the model that embeds it.
|
|
666
|
+
* the model that embeds it. `regexIndex` makes `grep` and `$text` filters answer from an index,
|
|
667
|
+
* chosen once: over a namespace that exists without one it is a 409.
|
|
619
668
|
*/
|
|
620
669
|
create(options?: RequestOptions & {
|
|
621
670
|
embeddingModel?: string;
|
|
671
|
+
regexIndex?: boolean;
|
|
622
672
|
}): Promise<{
|
|
623
673
|
embeddingModel: string;
|
|
624
674
|
}>;
|
|
@@ -673,6 +723,12 @@ export declare class Namespace {
|
|
|
673
723
|
* `userPrefix` is a 400, never "every user". `excludeIds` keeps those documents out.
|
|
674
724
|
*/
|
|
675
725
|
query(query: string, options?: QueryOptions): Promise<QueryResult[]>;
|
|
726
|
+
/**
|
|
727
|
+
* The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
|
|
728
|
+
* with the lines that match, in id order. A match lies inside one passage. Pass `nextCursor` as `cursor`
|
|
729
|
+
* to go on; a namespace created without `regexIndex` reads its passages, so a page can stop short of `limit`.
|
|
730
|
+
*/
|
|
731
|
+
grep(pattern: string | FuzzyText, options?: GrepOptions): Promise<GrepPage>;
|
|
676
732
|
/**
|
|
677
733
|
* A deep search, page by page: ranks `maxResults` documents once (at least `topK`; at most 1,000,
|
|
678
734
|
* 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,7 +1,9 @@
|
|
|
1
1
|
// conare: TypeScript client for the Conare API. Zero dependencies; uses global fetch.
|
|
2
|
-
export const VERSION = "0.
|
|
2
|
+
export const VERSION = "0.26.1";
|
|
3
3
|
const DEFAULT_BASE_URL = "https://api.conare.ai";
|
|
4
4
|
const BATCH_SIZE = 100;
|
|
5
|
+
/** Above the API's 110 s deadline for a write: a call given up sooner is retried while the first still runs. */
|
|
6
|
+
const WRITE_TIMEOUT_MS = 120_000;
|
|
5
7
|
// A JSON body this long or longer goes gzip-encoded: past the first ~14 KB a new connection may send,
|
|
6
8
|
// each doubling of the window costs a round trip, and JSON of documents is 3-4x smaller in gzip.
|
|
7
9
|
const GZIP_MIN_BYTES = 8 * 1024;
|
|
@@ -127,6 +129,7 @@ export class Conare {
|
|
|
127
129
|
organization;
|
|
128
130
|
apiKey;
|
|
129
131
|
timeout;
|
|
132
|
+
writeTimeout;
|
|
130
133
|
maxRetries;
|
|
131
134
|
fetchFn;
|
|
132
135
|
gzip;
|
|
@@ -143,6 +146,7 @@ export class Conare {
|
|
|
143
146
|
end--;
|
|
144
147
|
this.baseURL = baseURL.slice(0, end);
|
|
145
148
|
this.timeout = options.timeout ?? 60_000;
|
|
149
|
+
this.writeTimeout = options.timeout ?? WRITE_TIMEOUT_MS;
|
|
146
150
|
this.maxRetries = options.maxRetries ?? 2;
|
|
147
151
|
this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
|
|
148
152
|
this.organization = options.organization || undefined;
|
|
@@ -330,10 +334,11 @@ export class Namespace {
|
|
|
330
334
|
* Create the namespace before its first write. Only a namespace embedded by `embeddingModel`
|
|
331
335
|
* (one of your organization's models from `GET /models`) needs this: a write creates one with the
|
|
332
336
|
* default model. Its model never changes: creating it again with another one is a 409. Returns
|
|
333
|
-
* the model that embeds it.
|
|
337
|
+
* the model that embeds it. `regexIndex` makes `grep` and `$text` filters answer from an index,
|
|
338
|
+
* chosen once: over a namespace that exists without one it is a 409.
|
|
334
339
|
*/
|
|
335
340
|
async create(options = {}) {
|
|
336
|
-
const body = await this.client.request("POST", "/namespaces", { name: this.name, embedding_model: options.embeddingModel }, options);
|
|
341
|
+
const body = await this.client.request("POST", "/namespaces", { name: this.name, embedding_model: options.embeddingModel, regex_index: options.regexIndex }, options);
|
|
337
342
|
return { embeddingModel: body.embedding_model };
|
|
338
343
|
}
|
|
339
344
|
/**
|
|
@@ -368,7 +373,7 @@ export class Namespace {
|
|
|
368
373
|
seq: d.seq,
|
|
369
374
|
if_version: d.ifVersion,
|
|
370
375
|
})),
|
|
371
|
-
}, { ...options, idempotencyKey: stepKey(key, i / BATCH_SIZE) });
|
|
376
|
+
}, { timeout: this.client.writeTimeout, ...options, idempotencyKey: stepKey(key, i / BATCH_SIZE) });
|
|
372
377
|
body.ids.forEach((id, j) => {
|
|
373
378
|
const r = body.results?.[j];
|
|
374
379
|
const result = { id, version: body.versions?.[j] ?? null };
|
|
@@ -433,6 +438,22 @@ export class Namespace {
|
|
|
433
438
|
const body = await this.client.request("POST", this.path("/query"), queryBody(query, options), options);
|
|
434
439
|
return body.results;
|
|
435
440
|
}
|
|
441
|
+
/**
|
|
442
|
+
* The documents whose text matches a regular expression, or a near spelling (`{ query, max_distance }`),
|
|
443
|
+
* with the lines that match, in id order. A match lies inside one passage. Pass `nextCursor` as `cursor`
|
|
444
|
+
* to go on; a namespace created without `regexIndex` reads its passages, so a page can stop short of `limit`.
|
|
445
|
+
*/
|
|
446
|
+
async grep(pattern, options = {}) {
|
|
447
|
+
const body = await this.client.request("POST", this.path("/grep"), {
|
|
448
|
+
...(typeof pattern === "string" ? { pattern } : { fuzzy: pattern }),
|
|
449
|
+
filter: options.filter,
|
|
450
|
+
user: options.user,
|
|
451
|
+
user_prefix: options.userPrefix,
|
|
452
|
+
limit: options.limit,
|
|
453
|
+
cursor: options.cursor,
|
|
454
|
+
}, options);
|
|
455
|
+
return { matches: body.matches, nextCursor: body.next_cursor ?? null };
|
|
456
|
+
}
|
|
436
457
|
/**
|
|
437
458
|
* A deep search, page by page: ranks `maxResults` documents once (at least `topK`; at most 1,000,
|
|
438
459
|
* or 5,000 on a custom model's engine) and yields them `topK` at a time. Later pages are read from
|
|
@@ -493,7 +514,7 @@ export class Namespace {
|
|
|
493
514
|
* does not exist throws ConareError 404 `namespace_not_found`. Returns how many were deleted.
|
|
494
515
|
*/
|
|
495
516
|
async deleteMany(ids, options) {
|
|
496
|
-
const out = await this.client.request("POST", this.path("/documents/delete"), { ids }, options);
|
|
517
|
+
const out = await this.client.request("POST", this.path("/documents/delete"), { ids }, { timeout: this.client.writeTimeout, ...options });
|
|
497
518
|
return out.deleted;
|
|
498
519
|
}
|
|
499
520
|
/** Delete every document matching filter (at least one condition), calling until none match. Returns how many were deleted. */
|
|
@@ -502,7 +523,7 @@ export class Namespace {
|
|
|
502
523
|
const key = options?.idempotencyKey;
|
|
503
524
|
for (let round = 0;; round++) {
|
|
504
525
|
// Each round is its own call (the same body deletes the next batch): its own key.
|
|
505
|
-
const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { ...options, idempotencyKey: stepKey(key, round) });
|
|
526
|
+
const out = await this.client.request("POST", this.path("/documents/delete"), { filter }, { timeout: this.client.writeTimeout, ...options, idempotencyKey: stepKey(key, round) });
|
|
506
527
|
deleted += out.deleted;
|
|
507
528
|
if (!out.more)
|
|
508
529
|
return deleted;
|