@olivia-db/client 0.0.0-stage → 0.1.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 +39 -2
- package/dist/index.d.ts +200 -0
- package/dist/index.js +239 -0
- package/dist/native.d.ts +216 -0
- package/dist/native.js +1200 -0
- package/package.json +36 -4
- package/src/index.ts +361 -0
- package/src/native.ts +1254 -0
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@olivia-db/client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Client for OliviaDB's network API: agent memory and layer-1 reads, and the native protocol (Node.js)",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./native": {
|
|
15
|
+
"types": "./dist/native.d.ts",
|
|
16
|
+
"default": "./dist/native.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"src",
|
|
22
|
+
"README.md"
|
|
23
|
+
],
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/OliviaDB/oliviadb-js.git",
|
|
27
|
+
"directory": "oliviadb-client"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=18"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "tsc -p tsconfig.build.json",
|
|
34
|
+
"prepack": "npm run build",
|
|
35
|
+
"typecheck": "tsc -p .",
|
|
36
|
+
"test": "node --test test/*.test.ts"
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Client for OliviaDB's network API (spec/oliviadb-api.openapi.json): agent memory and layer-1
|
|
4
|
+
* reads over HTTPS. Uses the platform's fetch (Node 18+, Deno, Bun, browsers, edge).
|
|
5
|
+
*
|
|
6
|
+
* const oliviadb = new OliviaDbClient({ baseUrl: "https://oliviadb.example:8443", token });
|
|
7
|
+
* await oliviadb.remember({ thread: "t1", text: "Ann works at Acme.", step_id: "s1",
|
|
8
|
+
* facts: [{ entity: "Ann", attr: "employer", value: "Acme" }] });
|
|
9
|
+
* const pack = await oliviadb.recall({ query: "Where does Ann work?", budget: 500 });
|
|
10
|
+
*
|
|
11
|
+
* Arguments and results are those of the MCP tools of the same name; failures throw
|
|
12
|
+
* OliviaDbError (an RFC 9457 problem document), retried when the server says retryable.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export type Json = Record<string, unknown>;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A transaction time, fact id or cursor. The server sends values above 2^53 - 1 as decimal
|
|
19
|
+
* strings (a JavaScript number would round them); pass them back as received, as a
|
|
20
|
+
* string or a bigint (sent as a string), never through Number().
|
|
21
|
+
*/
|
|
22
|
+
export type U64 = number | string | bigint;
|
|
23
|
+
|
|
24
|
+
/** A U64 from a result as a bigint (exact). */
|
|
25
|
+
export function u64(v: U64): bigint {
|
|
26
|
+
return typeof v === "bigint" ? v : BigInt(v);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface Fact {
|
|
30
|
+
entity: string;
|
|
31
|
+
attr: string;
|
|
32
|
+
value: string;
|
|
33
|
+
valid_from?: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface RememberArgs {
|
|
37
|
+
thread: string;
|
|
38
|
+
text: string;
|
|
39
|
+
step_id?: string;
|
|
40
|
+
entities?: string[];
|
|
41
|
+
facts?: Fact[];
|
|
42
|
+
durability?: "durable" | "session";
|
|
43
|
+
visibility?: "private" | "tenant";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface RecallArgs {
|
|
47
|
+
query: string;
|
|
48
|
+
budget?: number;
|
|
49
|
+
thread?: string;
|
|
50
|
+
valid_at?: U64;
|
|
51
|
+
known_at?: U64;
|
|
52
|
+
min_ts?: U64;
|
|
53
|
+
already?: string[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface RecallItem {
|
|
57
|
+
ref: string;
|
|
58
|
+
kind: string;
|
|
59
|
+
tokens: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface RecallResult {
|
|
63
|
+
text: string;
|
|
64
|
+
pack: string;
|
|
65
|
+
tokens: number;
|
|
66
|
+
prefix_hash?: string;
|
|
67
|
+
items: RecallItem[];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface StateItem {
|
|
71
|
+
namespace: string[];
|
|
72
|
+
key: string;
|
|
73
|
+
value: unknown;
|
|
74
|
+
version: number;
|
|
75
|
+
created_ms: number;
|
|
76
|
+
updated_ms: number;
|
|
77
|
+
expires_ms?: number;
|
|
78
|
+
visibility: "private" | "tenant";
|
|
79
|
+
score?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface WatchEvent {
|
|
83
|
+
id: string;
|
|
84
|
+
data: Json;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface ClientOptions {
|
|
88
|
+
/** The server, or every node of a high-availability pair: a refused connection or a
|
|
89
|
+
* retryable 503 moves the client to the node the answer names (`oliviadb-primary`), else
|
|
90
|
+
* to the next one. */
|
|
91
|
+
baseUrl: string | string[];
|
|
92
|
+
/** OAuth access token for this server. */
|
|
93
|
+
token?: string;
|
|
94
|
+
/** API key (development, Mem0-style clients). */
|
|
95
|
+
apiKey?: string;
|
|
96
|
+
retries?: number;
|
|
97
|
+
traceparent?: string;
|
|
98
|
+
fetch?: typeof fetch;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export class OliviaDbError extends Error {
|
|
102
|
+
readonly status: number;
|
|
103
|
+
readonly type: string;
|
|
104
|
+
readonly detail: string;
|
|
105
|
+
readonly retryable: boolean;
|
|
106
|
+
readonly problem: Json;
|
|
107
|
+
constructor(status: number, problem: Json) {
|
|
108
|
+
const text = (v: unknown) => (typeof v === "string" ? v : "");
|
|
109
|
+
super(`${status} ${text(problem.type)}: ${text(problem.detail)}`);
|
|
110
|
+
this.status = status;
|
|
111
|
+
this.problem = problem;
|
|
112
|
+
this.type = text(problem.type);
|
|
113
|
+
this.detail = text(problem.detail);
|
|
114
|
+
this.retryable = problem.retryable === true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function clean(o: object): Json {
|
|
119
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export class OliviaDbClient {
|
|
123
|
+
private readonly bases: string[];
|
|
124
|
+
private cur = 0;
|
|
125
|
+
private readonly auth: string;
|
|
126
|
+
private readonly retries: number;
|
|
127
|
+
private readonly traceparent?: string;
|
|
128
|
+
private readonly f: typeof fetch;
|
|
129
|
+
|
|
130
|
+
constructor(o: ClientOptions) {
|
|
131
|
+
if ((o.token === undefined) === (o.apiKey === undefined)) throw new Error("give either token or apiKey");
|
|
132
|
+
this.bases = (Array.isArray(o.baseUrl) ? o.baseUrl : [o.baseUrl]).map((u) => u.replace(/\/+$/, ""));
|
|
133
|
+
if (this.bases.length === 0) throw new Error("no base URL");
|
|
134
|
+
this.auth = o.token !== undefined ? `Bearer ${o.token}` : `Token ${o.apiKey}`;
|
|
135
|
+
this.retries = o.retries ?? 3;
|
|
136
|
+
this.traceparent = o.traceparent;
|
|
137
|
+
this.f = o.fetch ?? fetch;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private headers(extra?: Record<string, string>): Record<string, string> {
|
|
141
|
+
const h: Record<string, string> = { authorization: this.auth, accept: "application/json", ...extra };
|
|
142
|
+
if (this.traceparent) h.traceparent = this.traceparent;
|
|
143
|
+
return h;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private get base(): string {
|
|
147
|
+
return this.bases[this.cur];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private next(primary: string | null): void {
|
|
151
|
+
const p = primary?.replace(/\/+$/, "");
|
|
152
|
+
const i = p ? this.bases.indexOf(p) : -1;
|
|
153
|
+
this.cur = i >= 0 ? i : (this.cur + 1) % this.bases.length;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private async send(method: string, path: string, body?: object, extra?: Record<string, string>): Promise<Response> {
|
|
157
|
+
const n = this.bases.length;
|
|
158
|
+
// With several nodes every one gets its turn before the retries run out.
|
|
159
|
+
const budget = this.retries * n;
|
|
160
|
+
for (let attempt = 0; ;) {
|
|
161
|
+
const h = this.headers(body ? { "content-type": "application/json", ...extra } : extra);
|
|
162
|
+
let r: Response;
|
|
163
|
+
try {
|
|
164
|
+
r = await this.f(this.base + path, {
|
|
165
|
+
method,
|
|
166
|
+
headers: h,
|
|
167
|
+
body: body
|
|
168
|
+
? JSON.stringify(clean(body), (_k, v: unknown) => (typeof v === "bigint" ? v.toString() : v))
|
|
169
|
+
: undefined,
|
|
170
|
+
});
|
|
171
|
+
} catch (err) {
|
|
172
|
+
// A node that is down: the next one (only when there is another).
|
|
173
|
+
if (n === 1 || attempt >= budget) throw err;
|
|
174
|
+
attempt++;
|
|
175
|
+
this.next(null);
|
|
176
|
+
if (attempt % n === 0) await new Promise((res) => setTimeout(res, 200 * attempt));
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (r.ok) return r;
|
|
180
|
+
const text = await r.text();
|
|
181
|
+
let p: Json;
|
|
182
|
+
try {
|
|
183
|
+
p = JSON.parse(text) as Json;
|
|
184
|
+
} catch {
|
|
185
|
+
p = { type: "about:blank", detail: text, retryable: false };
|
|
186
|
+
}
|
|
187
|
+
const e = new OliviaDbError(r.status, p);
|
|
188
|
+
if (e.retryable && attempt < budget) {
|
|
189
|
+
attempt++;
|
|
190
|
+
this.next(r.headers.get("oliviadb-primary"));
|
|
191
|
+
// A move to another node is tried at once; the same node after its Retry-After.
|
|
192
|
+
if (n === 1 || attempt % n === 0) {
|
|
193
|
+
await new Promise((res) =>
|
|
194
|
+
setTimeout(res, 1000 * Number(r.headers.get("retry-after") ?? 1) * Math.max(1, Math.floor(attempt / n))),
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
throw e;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private async json<T = Json>(
|
|
204
|
+
method: string,
|
|
205
|
+
path: string,
|
|
206
|
+
body?: object,
|
|
207
|
+
extra?: Record<string, string>,
|
|
208
|
+
): Promise<T> {
|
|
209
|
+
const r = await this.send(method, path, body, extra);
|
|
210
|
+
const t = await r.text();
|
|
211
|
+
return (t ? JSON.parse(t) : {}) as T;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
remember(a: RememberArgs): Promise<Json> {
|
|
215
|
+
return this.json("POST", "/v1/memory/remember", a);
|
|
216
|
+
}
|
|
217
|
+
recall(a: RecallArgs): Promise<RecallResult> {
|
|
218
|
+
return this.json("POST", "/v1/memory/recall", a);
|
|
219
|
+
}
|
|
220
|
+
expand(pack: string, ref: string): Promise<Json> {
|
|
221
|
+
return this.json("POST", "/v1/memory/expand", { pack, ref });
|
|
222
|
+
}
|
|
223
|
+
feedback(a: {
|
|
224
|
+
pack: string;
|
|
225
|
+
used_refs?: string[];
|
|
226
|
+
answer?: string;
|
|
227
|
+
outcome?: "success" | "failure" | "unknown";
|
|
228
|
+
}): Promise<Json> {
|
|
229
|
+
return this.json("POST", "/v1/memory/feedback", a);
|
|
230
|
+
}
|
|
231
|
+
assertFact(a: {
|
|
232
|
+
entity: string;
|
|
233
|
+
attr: string;
|
|
234
|
+
value: string;
|
|
235
|
+
evidence?: string;
|
|
236
|
+
expected_version?: U64;
|
|
237
|
+
}): Promise<Json> {
|
|
238
|
+
return this.json("POST", "/v1/memory/facts", a);
|
|
239
|
+
}
|
|
240
|
+
retract(fact_id: U64, reason?: string): Promise<Json> {
|
|
241
|
+
return this.json("POST", "/v1/memory/facts/retract", { fact_id, reason });
|
|
242
|
+
}
|
|
243
|
+
consolidate(cool_after_days?: number): Promise<Json> {
|
|
244
|
+
return this.json("POST", "/v1/memory/consolidate", { cool_after_days });
|
|
245
|
+
}
|
|
246
|
+
exportSubject(entity: string): Promise<Json> {
|
|
247
|
+
return this.json("POST", "/v1/admin/subjects/export", { entity });
|
|
248
|
+
}
|
|
249
|
+
/** First call: {input_required, request_state}; after the confirmation, call again with request_state. */
|
|
250
|
+
eraseSubject(entity: string, request_state?: string): Promise<Json> {
|
|
251
|
+
return this.json("POST", "/v1/admin/subjects/erase", { entity, request_state });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
path(p: string): Promise<Json> {
|
|
255
|
+
return this.json("GET", `/v1/path?p=${encodeURIComponent(p)}`);
|
|
256
|
+
}
|
|
257
|
+
catalog(): Promise<Json> {
|
|
258
|
+
return this.json("GET", "/v1/data/catalog");
|
|
259
|
+
}
|
|
260
|
+
dataRecall(query: string, budget = 1000, collection?: string): Promise<Json> {
|
|
261
|
+
return this.json("POST", "/v1/data/recall", { query, budget, collection });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---- agent state (namespaced documents) ----
|
|
265
|
+
statePut(a: {
|
|
266
|
+
namespace: string[];
|
|
267
|
+
key: string;
|
|
268
|
+
value: unknown;
|
|
269
|
+
ttl_ms?: number;
|
|
270
|
+
expected_version?: number;
|
|
271
|
+
index?: string[] | false;
|
|
272
|
+
vector?: number[];
|
|
273
|
+
visibility?: "private" | "tenant";
|
|
274
|
+
}): Promise<{ version: number }> {
|
|
275
|
+
return this.json("POST", "/v1/state/put", a);
|
|
276
|
+
}
|
|
277
|
+
/** Change one document atomically (an optimistic transaction on the server): inc, set, remove, merge. */
|
|
278
|
+
stateUpdate(a: {
|
|
279
|
+
namespace: string[];
|
|
280
|
+
key: string;
|
|
281
|
+
ops: Array<{ op: "inc" | "set" | "remove" | "merge"; path?: string; by?: number; value?: unknown }>;
|
|
282
|
+
create?: boolean;
|
|
283
|
+
visibility?: "private" | "tenant";
|
|
284
|
+
}): Promise<{ value: unknown; version: number; attempts: number; pessimistic: boolean }> {
|
|
285
|
+
return this.json("POST", "/v1/state/update", a);
|
|
286
|
+
}
|
|
287
|
+
stateAppend(a: { namespace: string[]; value: unknown; ttl_ms?: number }): Promise<{ key: string; version: number }> {
|
|
288
|
+
return this.json("POST", "/v1/state/append", a);
|
|
289
|
+
}
|
|
290
|
+
async stateGet(namespace: string[], key: string): Promise<StateItem | null> {
|
|
291
|
+
try {
|
|
292
|
+
return await this.json<StateItem>("POST", "/v1/state/get", { namespace, key });
|
|
293
|
+
} catch (e) {
|
|
294
|
+
if (e instanceof OliviaDbError && e.status === 404) return null;
|
|
295
|
+
throw e;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async stateDelete(namespace: string[], key?: string, prefix = false): Promise<number> {
|
|
299
|
+
return (
|
|
300
|
+
await this.json<{ deleted: number }>("POST", "/v1/state/delete", { namespace, key, prefix: prefix || undefined })
|
|
301
|
+
).deleted;
|
|
302
|
+
}
|
|
303
|
+
async stateList(
|
|
304
|
+
namespace: string[],
|
|
305
|
+
o: { after?: string; limit?: number; reverse?: boolean } = {},
|
|
306
|
+
): Promise<StateItem[]> {
|
|
307
|
+
return (await this.json<{ items: StateItem[] }>("POST", "/v1/state/list", { namespace, ...o })).items;
|
|
308
|
+
}
|
|
309
|
+
async stateNamespaces(
|
|
310
|
+
o: { prefix?: string[]; suffix?: string[]; max_depth?: number; limit?: number; offset?: number } = {},
|
|
311
|
+
): Promise<string[][]> {
|
|
312
|
+
return (await this.json<{ namespaces: string[][] }>("POST", "/v1/state/namespaces", o)).namespaces;
|
|
313
|
+
}
|
|
314
|
+
async stateSearch(
|
|
315
|
+
namespace_prefix: string[],
|
|
316
|
+
o: { query?: string; vector?: number[]; filter?: Json; limit?: number; offset?: number } = {},
|
|
317
|
+
): Promise<StateItem[]> {
|
|
318
|
+
return (await this.json<{ items: StateItem[] }>("POST", "/v1/state/search", { namespace_prefix, ...o })).items;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async watch(w: { entities?: string[]; paths?: string[] }): Promise<string> {
|
|
322
|
+
return (await this.json<{ id: string }>("POST", "/v1/watches", w)).id;
|
|
323
|
+
}
|
|
324
|
+
watchRead(id: string): Promise<Json> {
|
|
325
|
+
return this.json("GET", `/v1/watches/${encodeURIComponent(id)}`);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Server-sent events of a watch; stop with the signal or by breaking the loop. */
|
|
329
|
+
async *events(id: string, o: { lastEventId?: string; signal?: AbortSignal } = {}): AsyncGenerator<WatchEvent> {
|
|
330
|
+
const extra: Record<string, string> = { accept: "text/event-stream" };
|
|
331
|
+
if (o.lastEventId !== undefined) extra["last-event-id"] = o.lastEventId;
|
|
332
|
+
const r = await this.f(this.base + `/v1/watches/${encodeURIComponent(id)}/events`, {
|
|
333
|
+
headers: this.headers(extra),
|
|
334
|
+
signal: o.signal,
|
|
335
|
+
});
|
|
336
|
+
if (!r.ok || !r.body) throw new OliviaDbError(r.status, (await r.json().catch(() => ({}))) as Json);
|
|
337
|
+
const reader = r.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
338
|
+
let buf = "";
|
|
339
|
+
try {
|
|
340
|
+
for (;;) {
|
|
341
|
+
const { value, done } = await reader.read();
|
|
342
|
+
if (done) return;
|
|
343
|
+
buf += value;
|
|
344
|
+
let i: number;
|
|
345
|
+
while ((i = buf.indexOf("\n\n")) >= 0) {
|
|
346
|
+
const block = buf.slice(0, i);
|
|
347
|
+
buf = buf.slice(i + 2);
|
|
348
|
+
let eid = "";
|
|
349
|
+
const data: string[] = [];
|
|
350
|
+
for (const line of block.split("\n")) {
|
|
351
|
+
if (line.startsWith("id:")) eid = line.slice(3).trim();
|
|
352
|
+
else if (line.startsWith("data:")) data.push(line.slice(5).trim());
|
|
353
|
+
}
|
|
354
|
+
if (data.length) yield { id: eid, data: JSON.parse(data.join("\n")) as Json };
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
} finally {
|
|
358
|
+
await reader.cancel().catch(() => {});
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|