@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 CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ <!-- SPDX-License-Identifier: Apache-2.0 -->
2
+ # @olivia-db/client
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ The TypeScript client of [OliviaDB](https://olivia-db.com/)'s network API: agent memory
5
+ (remember, recall), agent state, layer-1 reads and writes of aggregates, change streams, and
6
+ the native protocol (`@olivia-db/client/native`, Node.js: one connection, many requests,
7
+ rows decoded only when a field is read). A list of node URLs fails over to the primary.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @olivia-db/client
13
+ ```
14
+
15
+ Node.js 22.18 or later.
16
+
17
+ ## Example
18
+
19
+ A server from the core image (`docker run -d -p 8443:8443 -v oliviadb-data:/data
20
+ ghcr.io/oliviadb/oliviadb`), its API key in `OLIVIADB_API_KEY` and its certificate in
21
+ `NODE_EXTRA_CA_CERTS`:
22
+
23
+ ```ts
24
+ import { OliviaDbClient } from "@olivia-db/client";
25
+
26
+ const db = new OliviaDbClient({ baseUrl: "https://localhost:8443", apiKey: process.env.OLIVIADB_API_KEY });
27
+ await db.remember({ thread: "t1", step_id: "ann-1", text: "Ann works at Acme.",
28
+ facts: [{ entity: "Ann", attr: "employer", value: "Acme" }] });
29
+ console.log((await db.recall({ query: "Where does Ann work?", budget: 300 })).text);
30
+ ```
31
+
32
+ Failures throw `OliviaDbError` (an RFC 9457 problem document); retryable ones are retried as
33
+ the network API defines.
34
+
35
+ ## Links
36
+
37
+ * Documentation: <https://docs.olivia-db.com/>
38
+ * Repository: <https://github.com/OliviaDB/oliviadb-js>
39
+
40
+ Licence: Apache-2.0.
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Client for OliviaDB's network API (spec/oliviadb-api.openapi.json): agent memory and layer-1
3
+ * reads over HTTPS. Uses the platform's fetch (Node 18+, Deno, Bun, browsers, edge).
4
+ *
5
+ * const oliviadb = new OliviaDbClient({ baseUrl: "https://oliviadb.example:8443", token });
6
+ * await oliviadb.remember({ thread: "t1", text: "Ann works at Acme.", step_id: "s1",
7
+ * facts: [{ entity: "Ann", attr: "employer", value: "Acme" }] });
8
+ * const pack = await oliviadb.recall({ query: "Where does Ann work?", budget: 500 });
9
+ *
10
+ * Arguments and results are those of the MCP tools of the same name; failures throw
11
+ * OliviaDbError (an RFC 9457 problem document), retried when the server says retryable.
12
+ */
13
+ export type Json = Record<string, unknown>;
14
+ /**
15
+ * A transaction time, fact id or cursor. The server sends values above 2^53 - 1 as decimal
16
+ * strings (a JavaScript number would round them); pass them back as received, as a
17
+ * string or a bigint (sent as a string), never through Number().
18
+ */
19
+ export type U64 = number | string | bigint;
20
+ /** A U64 from a result as a bigint (exact). */
21
+ export declare function u64(v: U64): bigint;
22
+ export interface Fact {
23
+ entity: string;
24
+ attr: string;
25
+ value: string;
26
+ valid_from?: number;
27
+ }
28
+ export interface RememberArgs {
29
+ thread: string;
30
+ text: string;
31
+ step_id?: string;
32
+ entities?: string[];
33
+ facts?: Fact[];
34
+ durability?: "durable" | "session";
35
+ visibility?: "private" | "tenant";
36
+ }
37
+ export interface RecallArgs {
38
+ query: string;
39
+ budget?: number;
40
+ thread?: string;
41
+ valid_at?: U64;
42
+ known_at?: U64;
43
+ min_ts?: U64;
44
+ already?: string[];
45
+ }
46
+ export interface RecallItem {
47
+ ref: string;
48
+ kind: string;
49
+ tokens: number;
50
+ }
51
+ export interface RecallResult {
52
+ text: string;
53
+ pack: string;
54
+ tokens: number;
55
+ prefix_hash?: string;
56
+ items: RecallItem[];
57
+ }
58
+ export interface StateItem {
59
+ namespace: string[];
60
+ key: string;
61
+ value: unknown;
62
+ version: number;
63
+ created_ms: number;
64
+ updated_ms: number;
65
+ expires_ms?: number;
66
+ visibility: "private" | "tenant";
67
+ score?: number;
68
+ }
69
+ export interface WatchEvent {
70
+ id: string;
71
+ data: Json;
72
+ }
73
+ export interface ClientOptions {
74
+ /** The server, or every node of a high-availability pair: a refused connection or a
75
+ * retryable 503 moves the client to the node the answer names (`oliviadb-primary`), else
76
+ * to the next one. */
77
+ baseUrl: string | string[];
78
+ /** OAuth access token for this server. */
79
+ token?: string;
80
+ /** API key (development, Mem0-style clients). */
81
+ apiKey?: string;
82
+ retries?: number;
83
+ traceparent?: string;
84
+ fetch?: typeof fetch;
85
+ }
86
+ export declare class OliviaDbError extends Error {
87
+ readonly status: number;
88
+ readonly type: string;
89
+ readonly detail: string;
90
+ readonly retryable: boolean;
91
+ readonly problem: Json;
92
+ constructor(status: number, problem: Json);
93
+ }
94
+ export declare class OliviaDbClient {
95
+ private readonly bases;
96
+ private cur;
97
+ private readonly auth;
98
+ private readonly retries;
99
+ private readonly traceparent?;
100
+ private readonly f;
101
+ constructor(o: ClientOptions);
102
+ private headers;
103
+ private get base();
104
+ private next;
105
+ private send;
106
+ private json;
107
+ remember(a: RememberArgs): Promise<Json>;
108
+ recall(a: RecallArgs): Promise<RecallResult>;
109
+ expand(pack: string, ref: string): Promise<Json>;
110
+ feedback(a: {
111
+ pack: string;
112
+ used_refs?: string[];
113
+ answer?: string;
114
+ outcome?: "success" | "failure" | "unknown";
115
+ }): Promise<Json>;
116
+ assertFact(a: {
117
+ entity: string;
118
+ attr: string;
119
+ value: string;
120
+ evidence?: string;
121
+ expected_version?: U64;
122
+ }): Promise<Json>;
123
+ retract(fact_id: U64, reason?: string): Promise<Json>;
124
+ consolidate(cool_after_days?: number): Promise<Json>;
125
+ exportSubject(entity: string): Promise<Json>;
126
+ /** First call: {input_required, request_state}; after the confirmation, call again with request_state. */
127
+ eraseSubject(entity: string, request_state?: string): Promise<Json>;
128
+ path(p: string): Promise<Json>;
129
+ catalog(): Promise<Json>;
130
+ dataRecall(query: string, budget?: number, collection?: string): Promise<Json>;
131
+ statePut(a: {
132
+ namespace: string[];
133
+ key: string;
134
+ value: unknown;
135
+ ttl_ms?: number;
136
+ expected_version?: number;
137
+ index?: string[] | false;
138
+ vector?: number[];
139
+ visibility?: "private" | "tenant";
140
+ }): Promise<{
141
+ version: number;
142
+ }>;
143
+ /** Change one document atomically (an optimistic transaction on the server): inc, set, remove, merge. */
144
+ stateUpdate(a: {
145
+ namespace: string[];
146
+ key: string;
147
+ ops: Array<{
148
+ op: "inc" | "set" | "remove" | "merge";
149
+ path?: string;
150
+ by?: number;
151
+ value?: unknown;
152
+ }>;
153
+ create?: boolean;
154
+ visibility?: "private" | "tenant";
155
+ }): Promise<{
156
+ value: unknown;
157
+ version: number;
158
+ attempts: number;
159
+ pessimistic: boolean;
160
+ }>;
161
+ stateAppend(a: {
162
+ namespace: string[];
163
+ value: unknown;
164
+ ttl_ms?: number;
165
+ }): Promise<{
166
+ key: string;
167
+ version: number;
168
+ }>;
169
+ stateGet(namespace: string[], key: string): Promise<StateItem | null>;
170
+ stateDelete(namespace: string[], key?: string, prefix?: boolean): Promise<number>;
171
+ stateList(namespace: string[], o?: {
172
+ after?: string;
173
+ limit?: number;
174
+ reverse?: boolean;
175
+ }): Promise<StateItem[]>;
176
+ stateNamespaces(o?: {
177
+ prefix?: string[];
178
+ suffix?: string[];
179
+ max_depth?: number;
180
+ limit?: number;
181
+ offset?: number;
182
+ }): Promise<string[][]>;
183
+ stateSearch(namespace_prefix: string[], o?: {
184
+ query?: string;
185
+ vector?: number[];
186
+ filter?: Json;
187
+ limit?: number;
188
+ offset?: number;
189
+ }): Promise<StateItem[]>;
190
+ watch(w: {
191
+ entities?: string[];
192
+ paths?: string[];
193
+ }): Promise<string>;
194
+ watchRead(id: string): Promise<Json>;
195
+ /** Server-sent events of a watch; stop with the signal or by breaking the loop. */
196
+ events(id: string, o?: {
197
+ lastEventId?: string;
198
+ signal?: AbortSignal;
199
+ }): AsyncGenerator<WatchEvent>;
200
+ }
package/dist/index.js ADDED
@@ -0,0 +1,239 @@
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
+ /** A U64 from a result as a bigint (exact). */
15
+ export function u64(v) {
16
+ return typeof v === "bigint" ? v : BigInt(v);
17
+ }
18
+ export class OliviaDbError extends Error {
19
+ status;
20
+ type;
21
+ detail;
22
+ retryable;
23
+ problem;
24
+ constructor(status, problem) {
25
+ const text = (v) => (typeof v === "string" ? v : "");
26
+ super(`${status} ${text(problem.type)}: ${text(problem.detail)}`);
27
+ this.status = status;
28
+ this.problem = problem;
29
+ this.type = text(problem.type);
30
+ this.detail = text(problem.detail);
31
+ this.retryable = problem.retryable === true;
32
+ }
33
+ }
34
+ function clean(o) {
35
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
36
+ }
37
+ export class OliviaDbClient {
38
+ bases;
39
+ cur = 0;
40
+ auth;
41
+ retries;
42
+ traceparent;
43
+ f;
44
+ constructor(o) {
45
+ if ((o.token === undefined) === (o.apiKey === undefined))
46
+ throw new Error("give either token or apiKey");
47
+ this.bases = (Array.isArray(o.baseUrl) ? o.baseUrl : [o.baseUrl]).map((u) => u.replace(/\/+$/, ""));
48
+ if (this.bases.length === 0)
49
+ throw new Error("no base URL");
50
+ this.auth = o.token !== undefined ? `Bearer ${o.token}` : `Token ${o.apiKey}`;
51
+ this.retries = o.retries ?? 3;
52
+ this.traceparent = o.traceparent;
53
+ this.f = o.fetch ?? fetch;
54
+ }
55
+ headers(extra) {
56
+ const h = { authorization: this.auth, accept: "application/json", ...extra };
57
+ if (this.traceparent)
58
+ h.traceparent = this.traceparent;
59
+ return h;
60
+ }
61
+ get base() {
62
+ return this.bases[this.cur];
63
+ }
64
+ next(primary) {
65
+ const p = primary?.replace(/\/+$/, "");
66
+ const i = p ? this.bases.indexOf(p) : -1;
67
+ this.cur = i >= 0 ? i : (this.cur + 1) % this.bases.length;
68
+ }
69
+ async send(method, path, body, extra) {
70
+ const n = this.bases.length;
71
+ // With several nodes every one gets its turn before the retries run out.
72
+ const budget = this.retries * n;
73
+ for (let attempt = 0;;) {
74
+ const h = this.headers(body ? { "content-type": "application/json", ...extra } : extra);
75
+ let r;
76
+ try {
77
+ r = await this.f(this.base + path, {
78
+ method,
79
+ headers: h,
80
+ body: body
81
+ ? JSON.stringify(clean(body), (_k, v) => (typeof v === "bigint" ? v.toString() : v))
82
+ : undefined,
83
+ });
84
+ }
85
+ catch (err) {
86
+ // A node that is down: the next one (only when there is another).
87
+ if (n === 1 || attempt >= budget)
88
+ throw err;
89
+ attempt++;
90
+ this.next(null);
91
+ if (attempt % n === 0)
92
+ await new Promise((res) => setTimeout(res, 200 * attempt));
93
+ continue;
94
+ }
95
+ if (r.ok)
96
+ return r;
97
+ const text = await r.text();
98
+ let p;
99
+ try {
100
+ p = JSON.parse(text);
101
+ }
102
+ catch {
103
+ p = { type: "about:blank", detail: text, retryable: false };
104
+ }
105
+ const e = new OliviaDbError(r.status, p);
106
+ if (e.retryable && attempt < budget) {
107
+ attempt++;
108
+ this.next(r.headers.get("oliviadb-primary"));
109
+ // A move to another node is tried at once; the same node after its Retry-After.
110
+ if (n === 1 || attempt % n === 0) {
111
+ await new Promise((res) => setTimeout(res, 1000 * Number(r.headers.get("retry-after") ?? 1) * Math.max(1, Math.floor(attempt / n))));
112
+ }
113
+ continue;
114
+ }
115
+ throw e;
116
+ }
117
+ }
118
+ async json(method, path, body, extra) {
119
+ const r = await this.send(method, path, body, extra);
120
+ const t = await r.text();
121
+ return (t ? JSON.parse(t) : {});
122
+ }
123
+ remember(a) {
124
+ return this.json("POST", "/v1/memory/remember", a);
125
+ }
126
+ recall(a) {
127
+ return this.json("POST", "/v1/memory/recall", a);
128
+ }
129
+ expand(pack, ref) {
130
+ return this.json("POST", "/v1/memory/expand", { pack, ref });
131
+ }
132
+ feedback(a) {
133
+ return this.json("POST", "/v1/memory/feedback", a);
134
+ }
135
+ assertFact(a) {
136
+ return this.json("POST", "/v1/memory/facts", a);
137
+ }
138
+ retract(fact_id, reason) {
139
+ return this.json("POST", "/v1/memory/facts/retract", { fact_id, reason });
140
+ }
141
+ consolidate(cool_after_days) {
142
+ return this.json("POST", "/v1/memory/consolidate", { cool_after_days });
143
+ }
144
+ exportSubject(entity) {
145
+ return this.json("POST", "/v1/admin/subjects/export", { entity });
146
+ }
147
+ /** First call: {input_required, request_state}; after the confirmation, call again with request_state. */
148
+ eraseSubject(entity, request_state) {
149
+ return this.json("POST", "/v1/admin/subjects/erase", { entity, request_state });
150
+ }
151
+ path(p) {
152
+ return this.json("GET", `/v1/path?p=${encodeURIComponent(p)}`);
153
+ }
154
+ catalog() {
155
+ return this.json("GET", "/v1/data/catalog");
156
+ }
157
+ dataRecall(query, budget = 1000, collection) {
158
+ return this.json("POST", "/v1/data/recall", { query, budget, collection });
159
+ }
160
+ // ---- agent state (namespaced documents) ----
161
+ statePut(a) {
162
+ return this.json("POST", "/v1/state/put", a);
163
+ }
164
+ /** Change one document atomically (an optimistic transaction on the server): inc, set, remove, merge. */
165
+ stateUpdate(a) {
166
+ return this.json("POST", "/v1/state/update", a);
167
+ }
168
+ stateAppend(a) {
169
+ return this.json("POST", "/v1/state/append", a);
170
+ }
171
+ async stateGet(namespace, key) {
172
+ try {
173
+ return await this.json("POST", "/v1/state/get", { namespace, key });
174
+ }
175
+ catch (e) {
176
+ if (e instanceof OliviaDbError && e.status === 404)
177
+ return null;
178
+ throw e;
179
+ }
180
+ }
181
+ async stateDelete(namespace, key, prefix = false) {
182
+ return (await this.json("POST", "/v1/state/delete", { namespace, key, prefix: prefix || undefined })).deleted;
183
+ }
184
+ async stateList(namespace, o = {}) {
185
+ return (await this.json("POST", "/v1/state/list", { namespace, ...o })).items;
186
+ }
187
+ async stateNamespaces(o = {}) {
188
+ return (await this.json("POST", "/v1/state/namespaces", o)).namespaces;
189
+ }
190
+ async stateSearch(namespace_prefix, o = {}) {
191
+ return (await this.json("POST", "/v1/state/search", { namespace_prefix, ...o })).items;
192
+ }
193
+ async watch(w) {
194
+ return (await this.json("POST", "/v1/watches", w)).id;
195
+ }
196
+ watchRead(id) {
197
+ return this.json("GET", `/v1/watches/${encodeURIComponent(id)}`);
198
+ }
199
+ /** Server-sent events of a watch; stop with the signal or by breaking the loop. */
200
+ async *events(id, o = {}) {
201
+ const extra = { accept: "text/event-stream" };
202
+ if (o.lastEventId !== undefined)
203
+ extra["last-event-id"] = o.lastEventId;
204
+ const r = await this.f(this.base + `/v1/watches/${encodeURIComponent(id)}/events`, {
205
+ headers: this.headers(extra),
206
+ signal: o.signal,
207
+ });
208
+ if (!r.ok || !r.body)
209
+ throw new OliviaDbError(r.status, (await r.json().catch(() => ({}))));
210
+ const reader = r.body.pipeThrough(new TextDecoderStream()).getReader();
211
+ let buf = "";
212
+ try {
213
+ for (;;) {
214
+ const { value, done } = await reader.read();
215
+ if (done)
216
+ return;
217
+ buf += value;
218
+ let i;
219
+ while ((i = buf.indexOf("\n\n")) >= 0) {
220
+ const block = buf.slice(0, i);
221
+ buf = buf.slice(i + 2);
222
+ let eid = "";
223
+ const data = [];
224
+ for (const line of block.split("\n")) {
225
+ if (line.startsWith("id:"))
226
+ eid = line.slice(3).trim();
227
+ else if (line.startsWith("data:"))
228
+ data.push(line.slice(5).trim());
229
+ }
230
+ if (data.length)
231
+ yield { id: eid, data: JSON.parse(data.join("\n")) };
232
+ }
233
+ }
234
+ }
235
+ finally {
236
+ await reader.cancel().catch(() => { });
237
+ }
238
+ }
239
+ }