@mnemo-ai/client-ts 3.6.0-alpha.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/dist/index.js ADDED
@@ -0,0 +1,2041 @@
1
+ /* @mnemo-ai/client-ts — Apache-2.0 */
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/errors.ts
10
+ var MnemosyneError = class extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = "MnemosyneError";
14
+ Object.setPrototypeOf(this, new.target.prototype);
15
+ }
16
+ };
17
+ var MnemosyneAPIError = class _MnemosyneAPIError extends MnemosyneError {
18
+ /** HTTP status code returned by the server (e.g. 404, 429, 500). */
19
+ status;
20
+ /** Machine-readable error code from the server, when present. */
21
+ code;
22
+ /** Server-generated request id for log correlation, when present. */
23
+ requestId;
24
+ /** Raw parsed JSON body, in case callers need details we didn't surface. */
25
+ body;
26
+ constructor(opts) {
27
+ super(opts.message);
28
+ this.name = "MnemosyneAPIError";
29
+ this.status = opts.status;
30
+ this.code = opts.code;
31
+ this.requestId = opts.requestId;
32
+ this.body = opts.body;
33
+ Object.setPrototypeOf(this, _MnemosyneAPIError.prototype);
34
+ }
35
+ };
36
+ var MnemosyneNetworkError = class _MnemosyneNetworkError extends MnemosyneError {
37
+ /** The original error from fetch (or wherever the failure surfaced). */
38
+ cause;
39
+ constructor(message, cause) {
40
+ super(message);
41
+ this.name = "MnemosyneNetworkError";
42
+ this.cause = cause;
43
+ Object.setPrototypeOf(this, _MnemosyneNetworkError.prototype);
44
+ }
45
+ };
46
+ var MnemosyneTimeoutError = class _MnemosyneTimeoutError extends MnemosyneError {
47
+ /** Configured timeout in milliseconds when the request was abandoned. */
48
+ timeoutMs;
49
+ constructor(timeoutMs) {
50
+ super(`Mnemosyne request exceeded ${timeoutMs}ms timeout`);
51
+ this.name = "MnemosyneTimeoutError";
52
+ this.timeoutMs = timeoutMs;
53
+ Object.setPrototypeOf(this, _MnemosyneTimeoutError.prototype);
54
+ }
55
+ };
56
+
57
+ // src/http.ts
58
+ var DEFAULT_RETRY = {
59
+ attempts: 3,
60
+ initialDelayMs: 200
61
+ };
62
+ var HttpClient = class {
63
+ config;
64
+ constructor(config) {
65
+ this.config = config;
66
+ }
67
+ async request(opts) {
68
+ const url = this.buildUrl(opts.path, opts.query);
69
+ const retryCfg = {
70
+ ...DEFAULT_RETRY,
71
+ ...this.config.retry
72
+ };
73
+ const attempts = retryCfg.attempts ?? DEFAULT_RETRY.attempts;
74
+ const shouldRetry = this.config.retry.shouldRetry ?? defaultShouldRetry;
75
+ let lastError;
76
+ for (let attempt = 1; attempt <= attempts; attempt++) {
77
+ try {
78
+ return await this.executeOnce(url, opts);
79
+ } catch (err) {
80
+ lastError = err;
81
+ if (attempt >= attempts) break;
82
+ if (!shouldRetry(err, attempt)) break;
83
+ await sleep(backoffMs(attempt, retryCfg.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs));
84
+ }
85
+ }
86
+ throw lastError;
87
+ }
88
+ buildUrl(path, query) {
89
+ const base = this.config.baseUrl.replace(/\/+$/, "");
90
+ const cleanPath = path.startsWith("/") ? path : `/${path}`;
91
+ const url = new URL(`${base}${cleanPath}`);
92
+ if (query) {
93
+ for (const [key, value] of Object.entries(query)) {
94
+ if (value === void 0) continue;
95
+ url.searchParams.set(key, String(value));
96
+ }
97
+ }
98
+ return url.toString();
99
+ }
100
+ async executeOnce(url, opts) {
101
+ const controller = new AbortController();
102
+ const timeoutId = setTimeout(() => controller.abort(timeoutReason), this.config.timeoutMs);
103
+ const onExternalAbort = () => controller.abort(opts.signal?.reason);
104
+ if (opts.signal) {
105
+ if (opts.signal.aborted) {
106
+ clearTimeout(timeoutId);
107
+ throw new MnemosyneNetworkError("aborted", opts.signal.reason);
108
+ }
109
+ opts.signal.addEventListener("abort", onExternalAbort, { once: true });
110
+ }
111
+ const headers = {
112
+ Authorization: `Bearer ${this.config.apiKey}`,
113
+ "User-Agent": this.config.userAgent,
114
+ Accept: "application/json",
115
+ // §34.9 — merge extra headers (e.g. Idempotency-Key) after base
116
+ // headers so callers cannot accidentally override Authorization.
117
+ ...opts.extraHeaders
118
+ };
119
+ if (opts.body !== void 0) {
120
+ headers["Content-Type"] = "application/json";
121
+ }
122
+ let response;
123
+ try {
124
+ response = await this.config.fetchImpl(url, {
125
+ method: opts.method,
126
+ headers,
127
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
128
+ signal: controller.signal
129
+ });
130
+ } catch (err) {
131
+ if (controller.signal.aborted && controller.signal.reason === timeoutReason) {
132
+ throw new MnemosyneTimeoutError(this.config.timeoutMs);
133
+ }
134
+ if (opts.signal?.aborted) {
135
+ throw new MnemosyneNetworkError("aborted by caller", opts.signal.reason);
136
+ }
137
+ throw new MnemosyneNetworkError(
138
+ err instanceof Error ? err.message : "fetch failed",
139
+ err
140
+ );
141
+ } finally {
142
+ clearTimeout(timeoutId);
143
+ if (opts.signal) {
144
+ opts.signal.removeEventListener("abort", onExternalAbort);
145
+ }
146
+ }
147
+ if (!response.ok) {
148
+ throw await parseErrorResponse(response);
149
+ }
150
+ if (response.status === 204) return void 0;
151
+ try {
152
+ return await response.json();
153
+ } catch (err) {
154
+ throw new MnemosyneNetworkError("malformed JSON in successful response", err);
155
+ }
156
+ }
157
+ };
158
+ var timeoutReason = /* @__PURE__ */ Symbol("mnemosyne:timeout");
159
+ function defaultShouldRetry(err) {
160
+ if (err instanceof MnemosyneNetworkError) return true;
161
+ if (err instanceof MnemosyneAPIError) return err.status >= 500 && err.status < 600;
162
+ return false;
163
+ }
164
+ function backoffMs(attempt, initialDelayMs) {
165
+ const exp = initialDelayMs * Math.pow(2, attempt - 1);
166
+ return Math.floor(Math.random() * exp);
167
+ }
168
+ function sleep(ms) {
169
+ return new Promise((resolve) => setTimeout(resolve, ms));
170
+ }
171
+ async function parseErrorResponse(response) {
172
+ let body = void 0;
173
+ let message = `HTTP ${response.status}`;
174
+ let code;
175
+ let requestId = response.headers.get("x-request-id") ?? void 0;
176
+ try {
177
+ const text = await response.text();
178
+ if (text) {
179
+ try {
180
+ body = JSON.parse(text);
181
+ if (isErrorBody(body)) {
182
+ if (typeof body.error.message === "string") message = body.error.message;
183
+ if (typeof body.error.code === "string") code = body.error.code;
184
+ if (typeof body.requestId === "string") requestId = body.requestId;
185
+ } else if (typeof body === "object" && body !== null) {
186
+ const b = body;
187
+ if (typeof b["message"] === "string") message = b["message"];
188
+ else if (typeof b["error"] === "string") message = b["error"];
189
+ if (typeof b["code"] === "string") code = b["code"];
190
+ if (typeof b["requestId"] === "string") requestId = b["requestId"];
191
+ } else if (typeof body === "string") {
192
+ message = body;
193
+ }
194
+ } catch {
195
+ message = text.slice(0, 500);
196
+ }
197
+ }
198
+ } catch {
199
+ }
200
+ return new MnemosyneAPIError({
201
+ status: response.status,
202
+ message,
203
+ code,
204
+ requestId,
205
+ body
206
+ });
207
+ }
208
+ function isErrorBody(v) {
209
+ return typeof v === "object" && v !== null && "error" in v && typeof v.error === "object" && v.error !== null;
210
+ }
211
+
212
+ // src/client.ts
213
+ var MnemosyneClient = class {
214
+ http;
215
+ constructor(options) {
216
+ if (!options.url) throw new Error("MnemosyneClient: `url` is required");
217
+ if (!options.apiKey) throw new Error("MnemosyneClient: `apiKey` is required");
218
+ const fetchImpl = options.fetch ?? ((...args) => globalThis.fetch(...args));
219
+ this.http = new HttpClient({
220
+ baseUrl: options.url,
221
+ apiKey: options.apiKey,
222
+ fetchImpl,
223
+ timeoutMs: options.timeout ?? 3e4,
224
+ retry: options.retry ?? {},
225
+ userAgent: options.userAgent ? `mnemosyne-client-ts/2.0.0-alpha.0 (${options.userAgent})` : "mnemosyne-client-ts/2.0.0-alpha.0"
226
+ });
227
+ }
228
+ /**
229
+ * Recall facts relevant to a query.
230
+ *
231
+ * The server returns top-K hits ranked by a blended score (vector
232
+ * similarity + lexical match + recency + pin boost). Don't compare
233
+ * scores across queries — they're only meaningful within a response.
234
+ *
235
+ * Trade-off: we accept an optional pre-embedded `embedding` so the
236
+ * caller can BYO embedder. Most callers should omit it and let the
237
+ * server handle embedding — that's what keeps recall behavior
238
+ * consistent across consumer apps.
239
+ */
240
+ recall(input, signal) {
241
+ return this.http.request({
242
+ method: "POST",
243
+ path: "/recall",
244
+ body: input,
245
+ ...signal ? { signal } : {}
246
+ });
247
+ }
248
+ /**
249
+ * Store a fact via the cognitive engine endpoint (POST /remember).
250
+ * Supports scope/scopeRef for project-namespaced memory — use this instead
251
+ * of createFact when you need to isolate facts by project or context.
252
+ */
253
+ remember(input, signal, idempotencyKey) {
254
+ const body = {
255
+ statement: input.statement,
256
+ ...input.subject ? { subject: input.subject } : {},
257
+ ...input.kind ? { kind: input.kind } : {},
258
+ ...input.confidence !== void 0 ? { confidence: input.confidence } : {},
259
+ ...input.agentId ? { agentId: input.agentId, attribution: input.agentId } : {},
260
+ ...input.conversationId ? { conversationId: input.conversationId } : {},
261
+ ...input.sensitivity ? { sensitivity: input.sensitivity } : {},
262
+ ...input.tags ? { tags: input.tags } : {},
263
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
264
+ ...input.metadata ? { metadata: input.metadata } : {},
265
+ ...input.scope ? { scope: input.scope } : {},
266
+ ...input.scopeRef ? { scopeRef: input.scopeRef } : {},
267
+ ...input.scopeOwner ? { scopeOwner: input.scopeOwner } : {},
268
+ ...input.targetWorkspaceId ? { targetWorkspaceId: input.targetWorkspaceId } : {},
269
+ ...input.vector ? { vector: input.vector } : {}
270
+ };
271
+ return this.http.request({
272
+ method: "POST",
273
+ path: "/remember",
274
+ body,
275
+ ...signal ? { signal } : {},
276
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
277
+ });
278
+ }
279
+ /**
280
+ * Persist a new fact. Idempotent via content-hash on the server —
281
+ * re-sending the same `content` won't duplicate.
282
+ *
283
+ * The wire body is exactly `{ content, attribution, tags }` (see
284
+ * {@link CreateFactInput}). The server responds 201 with the created
285
+ * {@link Fact}.
286
+ */
287
+ createFact(input, signal, idempotencyKey) {
288
+ return this.http.request({
289
+ method: "POST",
290
+ path: "/facts",
291
+ body: input,
292
+ ...signal ? { signal } : {},
293
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
294
+ });
295
+ }
296
+ /** Fetch one fact by id. Returns 404 → MnemosyneAPIError if not found. */
297
+ getFact(id, signal) {
298
+ return this.http.request({
299
+ method: "GET",
300
+ path: `/facts/${encodeURIComponent(id)}`,
301
+ ...signal ? { signal } : {}
302
+ });
303
+ }
304
+ /**
305
+ * Pin a fact — protects it from automated prune/forget and gives it
306
+ * a recall boost. Use for canonical, never-forget knowledge.
307
+ *
308
+ * The server models pin/unpin as a single route that takes a boolean
309
+ * flag (POST /v1/facts/:id/pin with `{ pinned }`) rather than two
310
+ * verbs, so we send `{ pinned: true }`.
311
+ */
312
+ pinFact(id, signal, idempotencyKey) {
313
+ return this.http.request({
314
+ method: "POST",
315
+ path: `/facts/${encodeURIComponent(id)}/pin`,
316
+ body: { pinned: true },
317
+ ...signal ? { signal } : {},
318
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
319
+ });
320
+ }
321
+ /** Inverse of {@link pinFact} — same route, `{ pinned: false }`. */
322
+ unpinFact(id, signal, idempotencyKey) {
323
+ return this.http.request({
324
+ method: "POST",
325
+ path: `/facts/${encodeURIComponent(id)}/pin`,
326
+ body: { pinned: false },
327
+ ...signal ? { signal } : {},
328
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
329
+ });
330
+ }
331
+ /**
332
+ * Forget a fact. This is the server's bitemporal soft-delete:
333
+ * DELETE /v1/facts/:id sets `valid_to = now` rather than hard-deleting,
334
+ * so the fact stays auditable/recoverable. Returns 204 No Content, so
335
+ * this resolves to `void`.
336
+ */
337
+ forgetFact(id, signal, idempotencyKey, reason) {
338
+ const query = reason ? `?reason=${encodeURIComponent(reason)}` : "";
339
+ return this.http.request({
340
+ method: "DELETE",
341
+ path: `/facts/${encodeURIComponent(id)}${query}`,
342
+ ...signal ? { signal } : {},
343
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
344
+ });
345
+ }
346
+ /**
347
+ * P18 — Soft-delete (archive) any cognitive primitive by kind and id.
348
+ * Maps to `DELETE /v1/forget/:kind/:id`.
349
+ * For facts, prefer {@link forgetFact} which also supports idempotency keys.
350
+ */
351
+ forgetPrimitive(kind, id, signal, reason) {
352
+ const query = reason ? `?reason=${encodeURIComponent(reason)}` : "";
353
+ return this.http.request({
354
+ method: "DELETE",
355
+ path: `/forget/${encodeURIComponent(kind)}/${encodeURIComponent(id)}${query}`,
356
+ ...signal ? { signal } : {}
357
+ });
358
+ }
359
+ /**
360
+ * Recent fact-lifecycle events for the workspace (created / pinned /
361
+ * unpinned / closed / updated), newest-first. Useful for diff views
362
+ * ("what did my AI learn this week?") and the Mnemosyne Studio
363
+ * inspector. Paginate with `nextCursor` via the `since` param.
364
+ */
365
+ timeline(input = {}, signal) {
366
+ return this.http.request({
367
+ method: "GET",
368
+ path: "/timeline",
369
+ query: {
370
+ limit: input.limit,
371
+ since: input.since
372
+ },
373
+ ...signal ? { signal } : {}
374
+ });
375
+ }
376
+ /**
377
+ * Liveness + readiness snapshot. Returns more than a binary "ok"
378
+ * so operators can wire it into existing dashboards (db / embedder /
379
+ * queue sub-components are surfaced individually when degraded).
380
+ */
381
+ health(signal) {
382
+ return this.http.request({
383
+ method: "GET",
384
+ path: "/health",
385
+ ...signal ? { signal } : {}
386
+ });
387
+ }
388
+ /**
389
+ * Quick readiness check endpoint. Maps to `GET /health/ready`.
390
+ */
391
+ healthReady(signal) {
392
+ return this.http.request({
393
+ method: "GET",
394
+ path: "/health/ready",
395
+ ...signal ? { signal } : {}
396
+ });
397
+ }
398
+ /**
399
+ * Generic request escape hatch for un-wrapped or dynamic routes.
400
+ */
401
+ request(opts) {
402
+ return this.http.request(opts);
403
+ }
404
+ /**
405
+ * Introspect the current API key — returns workspace, user, tenant,
406
+ * scopes, plan and expiry. Maps to `GET /me`.
407
+ */
408
+ getMe(signal) {
409
+ return this.http.request({
410
+ method: "GET",
411
+ path: "/me",
412
+ ...signal ? { signal } : {}
413
+ });
414
+ }
415
+ /**
416
+ * List workspaces available in the current tenant.
417
+ * Maps to `GET /tenants/:tenantId/workspaces`.
418
+ * Returns empty array when the key has no tenant binding.
419
+ */
420
+ async listWorkspacesForCurrentTenant(signal) {
421
+ const me = await this.getMe(signal).catch(() => null);
422
+ const tenantId = me?.tenantId;
423
+ if (!tenantId) return [];
424
+ const result = await this.http.request({
425
+ method: "GET",
426
+ path: `/tenants/${tenantId}/workspaces`,
427
+ ...signal ? { signal } : {}
428
+ }).catch(() => ({ workspaces: [] }));
429
+ return result.workspaces ?? [];
430
+ }
431
+ /**
432
+ * List workspaces the active user belongs to.
433
+ * Maps to `GET /workspaces/mine`.
434
+ */
435
+ async listMyWorkspaces(signal) {
436
+ const result = await this.http.request({
437
+ method: "GET",
438
+ path: "/workspaces/mine",
439
+ ...signal ? { signal } : {}
440
+ }).catch(() => ({ workspaces: [] }));
441
+ return result.workspaces ?? [];
442
+ }
443
+ /**
444
+ * List members of a workspace.
445
+ * Maps to `GET /workspaces/:workspaceId/members`.
446
+ */
447
+ async listWorkspaceMembers(workspaceId, signal) {
448
+ const result = await this.http.request({
449
+ method: "GET",
450
+ path: `/workspaces/${workspaceId}/members`,
451
+ ...signal ? { signal } : {}
452
+ }).catch(() => ({ members: [] }));
453
+ return result.members ?? [];
454
+ }
455
+ /**
456
+ * Run the 6 server-side operational diagnostic checks (connectivity,
457
+ * app_user_grants, schema_shadows, migration_version, embedding_backlog,
458
+ * workspace_id_valid) and return a structured `DoctorReport`.
459
+ *
460
+ * The `memory_doctor` MCP tool calls this and appends 2 additional
461
+ * client-side checks (env_config, mcp_tools) before returning the merged
462
+ * report to the LLM caller.
463
+ *
464
+ * Maps to `GET /v1/doctor`.
465
+ */
466
+ doctor(signal) {
467
+ return this.http.request({
468
+ method: "GET",
469
+ path: "/doctor",
470
+ ...signal ? { signal } : {}
471
+ });
472
+ }
473
+ /**
474
+ * Aggregate workspace statistics: fact counts (live / closed / pinned /
475
+ * archived / zero-hits), decision count, conflict relations, embedding
476
+ * coverage, recall hit rate, and last activity timestamps.
477
+ *
478
+ * Delegates to `GET /v1/admin/stats` on the Mnemosyne server.
479
+ * No parameters — all stats are scoped to the authenticated workspace
480
+ * by RLS.
481
+ */
482
+ getStats(signal) {
483
+ return this.http.request({
484
+ method: "GET",
485
+ path: "/admin/stats",
486
+ ...signal ? { signal } : {}
487
+ });
488
+ }
489
+ /**
490
+ * Memory Graph snapshot. With no input, returns the workspace's full
491
+ * canonical graph (entities + episodes + decisions, plus typed
492
+ * relations between them). When `focus` is supplied (a cuid2-shaped
493
+ * `ment_*` id), returns only that entity and its 1-hop neighbourhood
494
+ * — cheaper to compute and much cheaper to render.
495
+ *
496
+ * The server caches with `Cache-Control: private, max-age=30`, so
497
+ * repeated calls within that window are short-circuited by any
498
+ * standards-conformant fetch implementation.
499
+ */
500
+ graph(input = {}, signal) {
501
+ return this.http.request({
502
+ method: "GET",
503
+ path: "/graph",
504
+ query: {
505
+ focus: input.focus,
506
+ ...input.includeSemantic ? { includeSemantic: "true" } : {},
507
+ ...input.asOf ? { asOf: input.asOf } : {}
508
+ },
509
+ ...signal ? { signal } : {}
510
+ });
511
+ }
512
+ /**
513
+ * Multi-hop BFS traversal over `mnemo_relation` starting from a root entity.
514
+ * Returns reachable nodes with their minimum hop distance and a relevance
515
+ * score (decay^hop). Supports optional verb filtering and bitemporal as-of
516
+ * reconstruction.
517
+ *
518
+ * Maps to `GET /v1/graph/traverse`.
519
+ */
520
+ graphTraverse(input, signal) {
521
+ return this.http.request({
522
+ method: "GET",
523
+ path: "/graph/traverse",
524
+ query: {
525
+ root: input.root,
526
+ ...input.maxHops !== void 0 ? { maxHops: input.maxHops } : {},
527
+ ...input.relations?.length ? { relations: input.relations.join(",") } : {},
528
+ ...input.asOf ? { asOf: input.asOf } : {}
529
+ },
530
+ ...signal ? { signal } : {}
531
+ });
532
+ }
533
+ /**
534
+ * Low-level BFS relation edge traversal from a root node over `mnemo_relation`.
535
+ * Returns reachable nodes and raw edge objects.
536
+ *
537
+ * Maps to `POST /v1/relations/traverse`.
538
+ */
539
+ relationsTraverse(input, signal) {
540
+ return this.http.request({
541
+ method: "POST",
542
+ path: "/relations/traverse",
543
+ body: input,
544
+ ...signal ? { signal } : {}
545
+ });
546
+ }
547
+ /**
548
+ * Shortest path between two nodes over `mnemo_relation` via a recursive
549
+ * CTE with cycle detection. Returns the node id chain from `from` to `to`
550
+ * and the relation verbs traversed at each step. Returns an empty path
551
+ * when the nodes are unreachable within `maxHops`.
552
+ *
553
+ * Maps to `GET /v1/graph/path`.
554
+ */
555
+ graphPath(input, signal) {
556
+ return this.http.request({
557
+ method: "GET",
558
+ path: "/graph/path",
559
+ query: {
560
+ from: input.from,
561
+ to: input.to,
562
+ ...input.maxHops !== void 0 ? { maxHops: input.maxHops } : {},
563
+ ...input.asOf ? { asOf: input.asOf } : {}
564
+ },
565
+ ...signal ? { signal } : {}
566
+ });
567
+ }
568
+ /**
569
+ * List entities in the workspace (Mnemosyne v1.6 G2 entity browser).
570
+ * Filters by `kind` (one of 6 enum values) and/or `q` (case-insensitive
571
+ * substring across name + aliases). Server-cap on `limit` is 200.
572
+ *
573
+ * Sorted newest-mentioned first (most likely interesting for the
574
+ * inspector header).
575
+ */
576
+ listEntities(input = {}, signal) {
577
+ return this.http.request({
578
+ method: "GET",
579
+ path: "/entities",
580
+ query: {
581
+ kind: input.kind,
582
+ q: input.q,
583
+ limit: input.limit
584
+ },
585
+ ...signal ? { signal } : {}
586
+ });
587
+ }
588
+ /**
589
+ * Fetch a single entity by id plus its active-fact count. The count
590
+ * powers the inspector header chip ("12 linked facts") without
591
+ * forcing a second round-trip. Throws {@link MnemosyneAPIError} (404)
592
+ * when the entity doesn't exist in this workspace.
593
+ */
594
+ getEntity(id, signal) {
595
+ return this.http.request({
596
+ method: "GET",
597
+ path: `/entities/${encodeURIComponent(id)}`,
598
+ ...signal ? { signal } : {}
599
+ });
600
+ }
601
+ /**
602
+ * List the facts the extraction pipeline linked to a given entity
603
+ * (via `mnemo_fact.entity_id`). Active facts only — forgotten/merged
604
+ * stay hidden from the entity-detail view. Server-cap on `limit` is
605
+ * 500. Throws 404 when the entity itself doesn't exist.
606
+ */
607
+ listEntityFacts(id, input = {}, signal) {
608
+ return this.http.request({
609
+ method: "GET",
610
+ path: `/entities/${encodeURIComponent(id)}/facts`,
611
+ query: { limit: input.limit },
612
+ ...signal ? { signal } : {}
613
+ });
614
+ }
615
+ /**
616
+ * List episodes in a date window (Mnemosyne v1.4 timeline). When
617
+ * `from`/`to` are omitted the server defaults to the last 30 days —
618
+ * the inspector rarely cares about older slices unless explicitly
619
+ * requested. `topic` filters via the GIN-indexed `topics` array
620
+ * (single-topic only by design). Server-cap on `limit` is 200.
621
+ *
622
+ * `includeSynthetic` defaults to false — extractor-synthesised
623
+ * episodes are hidden from the inspector view but visible to operator
624
+ * tools that opt in.
625
+ */
626
+ listEpisodes(input = {}, signal) {
627
+ return this.http.request({
628
+ method: "GET",
629
+ path: "/episodes",
630
+ query: {
631
+ from: input.from,
632
+ to: input.to,
633
+ topic: input.topic,
634
+ limit: input.limit,
635
+ includeSynthetic: input.includeSynthetic
636
+ },
637
+ ...signal ? { signal } : {}
638
+ });
639
+ }
640
+ /**
641
+ * Fetch a single episode plus its linked facts. Linked facts that
642
+ * have since been archived are silently filtered out (an episode
643
+ * legitimately outlives some of its constituent facts). Throws 404
644
+ * when the episode itself doesn't exist.
645
+ */
646
+ getEpisode(id, signal) {
647
+ return this.http.request({
648
+ method: "GET",
649
+ path: `/episodes/${encodeURIComponent(id)}`,
650
+ ...signal ? { signal } : {}
651
+ });
652
+ }
653
+ /**
654
+ * Manual entity create. The extraction pipeline auto-creates via
655
+ * `findOrCreate`; this method exists so an operator can bootstrap
656
+ * the entity table before any conversation has happened or
657
+ * backfill an out-of-band mention.
658
+ *
659
+ * The server enforces a `(workspace_id, name, kind)` unique
660
+ * constraint — a duplicate surfaces as a {@link MnemosyneAPIError}
661
+ * with status 409.
662
+ */
663
+ createEntity(input, signal, idempotencyKey) {
664
+ return this.http.request({
665
+ method: "POST",
666
+ path: "/entities",
667
+ body: input,
668
+ ...signal ? { signal } : {},
669
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
670
+ });
671
+ }
672
+ /**
673
+ * Patch an existing entity (rename / alias edits / kind change /
674
+ * canonical merge). An empty patch (every key undefined) gets
675
+ * 400; canonicalId targets that don't exist (or equal the row
676
+ * being patched) get 400. 404 when the row itself doesn't exist.
677
+ */
678
+ updateEntity(id, input, signal) {
679
+ return this.http.request({
680
+ method: "PATCH",
681
+ path: `/entities/${encodeURIComponent(id)}`,
682
+ body: input,
683
+ ...signal ? { signal } : {}
684
+ });
685
+ }
686
+ /**
687
+ * List active-learning queue rows (Mnemosyne v1.3+). Defaults to
688
+ * unresolved only — pass `all:true` to include resolved rows for
689
+ * the full history. Editor-tier surface; the queue is an
690
+ * operational concern.
691
+ */
692
+ listReview(input = {}, signal) {
693
+ return this.http.request({
694
+ method: "GET",
695
+ path: "/review",
696
+ query: {
697
+ reason: input.reason,
698
+ all: input.all,
699
+ limit: input.limit
700
+ },
701
+ ...signal ? { signal } : {}
702
+ });
703
+ }
704
+ /**
705
+ * Cheap COUNT(*) of unresolved queue rows. Powers the inspector
706
+ * header badge ("12 to review") — uses the partial index
707
+ * `idx_mnemo_review_queue_workspace_unresolved` so it's
708
+ * constant-time at queue depths the inspector cares about.
709
+ */
710
+ reviewCount(signal) {
711
+ return this.http.request({
712
+ method: "GET",
713
+ path: "/review/count",
714
+ ...signal ? { signal } : {}
715
+ });
716
+ }
717
+ /**
718
+ * Close a queue row. When `resolution='forgotten'` AND the row is
719
+ * fact-sourced, the server atomically cascades the fact's status
720
+ * to 'forgotten' in the same tx so the fact leaves the recall pool
721
+ * without a follow-up round-trip. The response's `cascaded` field
722
+ * confirms this happened.
723
+ *
724
+ * Throws 404 if the row doesn't exist; 409 if it was already
725
+ * resolved (idempotent re-resolve is intentionally NOT silent so
726
+ * the caller can decide whether to retry or surface a warning).
727
+ */
728
+ resolveReview(id, input, signal) {
729
+ return this.http.request({
730
+ method: "POST",
731
+ path: `/review/${encodeURIComponent(id)}/resolve`,
732
+ body: input,
733
+ ...signal ? { signal } : {}
734
+ });
735
+ }
736
+ /**
737
+ * "Undo log" feed — most recent fact-mutation events. Synthesised
738
+ * from two sources: user-driven Forget (revertible via
739
+ * {@link restoreFact}) and janitor-driven archive (not revertible).
740
+ * Newest first. Powers the inspector's undo surface.
741
+ */
742
+ audit(input = {}, signal) {
743
+ return this.http.request({
744
+ method: "GET",
745
+ path: "/audit",
746
+ query: { limit: input.limit },
747
+ ...signal ? { signal } : {}
748
+ });
749
+ }
750
+ /**
751
+ * Full workspace memory dump (admin-tier surface). Returns the four
752
+ * mnemo_* tables (facts, decisions, relations, citations) in a
753
+ * single buffered JSON payload. Embeddings are excluded.
754
+ *
755
+ * v1.3 caps at 100k rows per resource. Large workspaces should
756
+ * wait for the v1.4 streaming endpoint rather than chunk by hand.
757
+ */
758
+ exportWorkspace(signal) {
759
+ return this.http.request({
760
+ method: "GET",
761
+ path: "/export",
762
+ ...signal ? { signal } : {}
763
+ });
764
+ }
765
+ /**
766
+ * Restore a forgotten fact — flips `status` back to 'active' so the
767
+ * fact rejoins the recall pool. Companion to {@link forgetFact}.
768
+ * Returns the minimal `{id, status}` pair; chain {@link getFact}
769
+ * if you need the full body.
770
+ *
771
+ * 404 when the fact doesn't exist (or RLS hides it).
772
+ */
773
+ restoreFact(id, signal) {
774
+ return this.http.request({
775
+ method: "POST",
776
+ path: `/facts/${encodeURIComponent(id)}/restore`,
777
+ ...signal ? { signal } : {}
778
+ });
779
+ }
780
+ /**
781
+ * List decisions in the workspace (Mnemosyne v1.5). Decisions are
782
+ * durable, audited statements of "we are going to do X because Y"
783
+ * — distinct from facts (transient observations). Newest first.
784
+ */
785
+ listDecisions(input = {}, signal) {
786
+ return this.http.request({
787
+ method: "GET",
788
+ path: "/decisions",
789
+ query: { status: input.status, limit: input.limit },
790
+ ...signal ? { signal } : {}
791
+ });
792
+ }
793
+ /**
794
+ * Fetch a single decision by id. Throws 404 if it doesn't exist.
795
+ *
796
+ * Note: orchester's `/api/mnemo/decisions/[traceId]` route is the
797
+ * Decision BOM (Bill-of-Materials) endpoint, which joins mnemo
798
+ * decision data with orchester's audit_log table — this method
799
+ * returns ONLY the mnemo decision row, not the BOM composition.
800
+ */
801
+ getDecision(id, signal) {
802
+ return this.http.request({
803
+ method: "GET",
804
+ path: `/decisions/${encodeURIComponent(id)}`,
805
+ ...signal ? { signal } : {}
806
+ });
807
+ }
808
+ /**
809
+ * Paginated fact list (rich projection — subject/statement/kind, not
810
+ * the simplified content shape `/facts/:id` returns).
811
+ *
812
+ * Tramo 5 surface:
813
+ * - Filters: kind, scope, scopeRef, status, pinned, asOf (bitemporal).
814
+ * - Search: `q` runs `plainto_tsquery` on the lemmatized column with
815
+ * an ILIKE fallback for facts whose lemma column is null.
816
+ * - Sort: `sortBy` ∈ {created_at, updated_at, relevance, hit_count},
817
+ * `order` ∈ {asc, desc}. Tied rows are broken by id.
818
+ * - Pagination: pass back the previous response's `nextCursor` to
819
+ * keyset-paginate. Cursors are opaque — do not parse them.
820
+ *
821
+ * Response envelope `{ items, nextCursor, total }`. `total` is the
822
+ * COUNT(*) for the filter set (sans cursor) so an inspector header
823
+ * can render "X of Y" without a separate request.
824
+ */
825
+ listFacts(input = {}, signal) {
826
+ return this.http.request({
827
+ method: "GET",
828
+ path: "/facts",
829
+ query: {
830
+ kind: input.kind,
831
+ scope: input.scope,
832
+ scopeRef: input.scopeRef,
833
+ status: input.status,
834
+ pinned: input.pinned,
835
+ q: input.q,
836
+ sortBy: input.sortBy,
837
+ order: input.order,
838
+ cursor: input.cursor,
839
+ asOf: input.asOf,
840
+ limit: input.limit
841
+ },
842
+ ...signal ? { signal } : {}
843
+ });
844
+ }
845
+ /**
846
+ * Patch a fact's editable columns (subject/statement/kind/pinned/
847
+ * confidence/relevance/metadata). An empty patch (every field
848
+ * undefined) returns 400; 404 when the row doesn't exist.
849
+ *
850
+ * Bitemporal note: PATCH does NOT close the interval — `validFrom`
851
+ * stays put, `validTo` stays null. Use {@link forgetFact} to mark
852
+ * the fact as no-longer-valid at a point in time.
853
+ */
854
+ patchFact(id, input, signal) {
855
+ return this.http.request({
856
+ method: "PATCH",
857
+ path: `/facts/${encodeURIComponent(id)}`,
858
+ body: input,
859
+ ...signal ? { signal } : {}
860
+ });
861
+ }
862
+ /**
863
+ * Source-message ids for a fact. Returns just the id list —
864
+ * Mnemosyne doesn't own the message table that orchester joins
865
+ * against, so hosts wanting `{role, content, timestamp}` per message
866
+ * do that join on their side.
867
+ */
868
+ getFactCitations(id, signal) {
869
+ return this.http.request({
870
+ method: "GET",
871
+ path: `/facts/${encodeURIComponent(id)}/citations`,
872
+ ...signal ? { signal } : {}
873
+ });
874
+ }
875
+ /**
876
+ * Create a decision (Mnemosyne v1.5). Topic-key upsert + normalized-
877
+ * hash dedup happen server-side — re-creating a decision with the
878
+ * same (workspace_id, topic_key) returns the existing row (201
879
+ * status either way; the client cannot distinguish first-create
880
+ * from upsert without comparing the returned id).
881
+ */
882
+ createDecision(input, signal, idempotencyKey) {
883
+ return this.http.request({
884
+ method: "POST",
885
+ path: "/decisions",
886
+ body: input,
887
+ ...signal ? { signal } : {},
888
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
889
+ });
890
+ }
891
+ /**
892
+ * Supersede a decision: marks `id` as status='superseded' and
893
+ * points its supersededById at `input.supersededById`. Returns
894
+ * the updated decision. Caller is responsible for the matching
895
+ * `supersedes` relation row (via {@link createRelation}).
896
+ */
897
+ supersedeDecision(id, input, signal) {
898
+ return this.http.request({
899
+ method: "PATCH",
900
+ path: `/decisions/${encodeURIComponent(id)}`,
901
+ body: input,
902
+ ...signal ? { signal } : {}
903
+ });
904
+ }
905
+ /**
906
+ * List relations in the workspace (Mnemosyne v1.0 — LOCKED 9-verb
907
+ * vocabulary). Filter by `judgmentStatus`: typical inspector use is
908
+ * `judgmentStatus: 'pending'` for the judge queue.
909
+ */
910
+ listRelations(input = {}, signal) {
911
+ return this.http.request({
912
+ method: "GET",
913
+ path: "/relations",
914
+ query: { judgmentStatus: input.judgmentStatus, limit: input.limit },
915
+ ...signal ? { signal } : {}
916
+ });
917
+ }
918
+ /**
919
+ * Create a relation between two memory primitives. `relation` MUST
920
+ * be one of the 9 LOCKED verbs; the server 400-rejects unknown verbs.
921
+ *
922
+ * Multi-actor disagreement is captured by creating a SECOND relation
923
+ * row with the same source/target but a different markedBy* —
924
+ * the server has no UNIQUE constraint preventing this (intentional,
925
+ * see migration 0020).
926
+ */
927
+ createRelation(input, signal, idempotencyKey) {
928
+ return this.http.request({
929
+ method: "POST",
930
+ path: "/relations",
931
+ body: input,
932
+ ...signal ? { signal } : {},
933
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
934
+ });
935
+ }
936
+ /**
937
+ * Apply a judgment to a pending relation: replace the verb, flip
938
+ * `judgmentStatus` to 'judged', stamp the marker. Returns the
939
+ * updated row, or throws 404 when the relation does not exist.
940
+ */
941
+ patchRelation(id, input, signal) {
942
+ return this.http.request({
943
+ method: "PATCH",
944
+ path: `/relations/${encodeURIComponent(id)}`,
945
+ body: input,
946
+ ...signal ? { signal } : {}
947
+ });
948
+ }
949
+ /**
950
+ * List citations attached to memory primitives. Filter by
951
+ * `memoryKind` (fact/decision/entity/episode) and/or `memoryId`
952
+ * for a specific row's provenance trail. Newest first.
953
+ */
954
+ listCitations(input = {}, signal) {
955
+ return this.http.request({
956
+ method: "GET",
957
+ path: "/citations",
958
+ query: {
959
+ memoryKind: input.memoryKind,
960
+ memoryId: input.memoryId,
961
+ limit: input.limit
962
+ },
963
+ ...signal ? { signal } : {}
964
+ });
965
+ }
966
+ /**
967
+ * Manually enqueue a fact (or decision) for human review.
968
+ * Idempotent via the server-side partial index: re-enqueuing an
969
+ * open row returns the existing id with `inserted:false` instead
970
+ * of creating a duplicate. Exactly one of `factId`/`decisionId`
971
+ * MUST be supplied; the server 400-rejects both-or-neither.
972
+ */
973
+ enqueueReview(input, signal) {
974
+ return this.http.request({
975
+ method: "POST",
976
+ path: "/review/enqueue",
977
+ body: input,
978
+ ...signal ? { signal } : {}
979
+ });
980
+ }
981
+ /**
982
+ * Create a prospective memory reminder. The reminder will surface during
983
+ * recall when its time condition (`triggerAt`) is met, when the query
984
+ * embedding is semantically close to the reminder's condition, or both.
985
+ *
986
+ * Returns the created reminder with its assigned `id`.
987
+ */
988
+ createReminder(input, signal, idempotencyKey) {
989
+ return this.http.request({
990
+ method: "POST",
991
+ path: "/reminders",
992
+ body: input,
993
+ ...signal ? { signal } : {},
994
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
995
+ });
996
+ }
997
+ /**
998
+ * List reminders for the workspace. Defaults to `status=pending`.
999
+ *
1000
+ * @param status - 'pending' | 'triggered' | 'dismissed' | 'all' (default: 'pending')
1001
+ * @param limit - Max rows to return (default: 50, max: 200)
1002
+ */
1003
+ listReminders(input = {}, signal) {
1004
+ return this.http.request({
1005
+ method: "GET",
1006
+ path: "/reminders",
1007
+ query: { status: input.status, limit: input.limit },
1008
+ ...signal ? { signal } : {}
1009
+ });
1010
+ }
1011
+ /**
1012
+ * Dismiss a reminder by id. Sets status to 'dismissed' (no row deleted).
1013
+ * Throws MnemosyneAPIError (404) when the reminder does not exist.
1014
+ */
1015
+ dismissReminder(id, signal) {
1016
+ return this.http.request({
1017
+ method: "DELETE",
1018
+ path: `/reminders/${encodeURIComponent(id)}`,
1019
+ ...signal ? { signal } : {}
1020
+ });
1021
+ }
1022
+ // ─── Session lifecycle ───────────────────────────────────────────────────────
1023
+ /**
1024
+ * Start a new ephemeral session (episode). Use the returned `id` with
1025
+ * {@link collapseSession} when the conversation ends.
1026
+ *
1027
+ * Maps to `POST /v1/session/start` on the Mnemosyne server.
1028
+ */
1029
+ createSession(input = {}, signal, idempotencyKey) {
1030
+ return this.http.request({
1031
+ method: "POST",
1032
+ path: "/session/start",
1033
+ body: input,
1034
+ ...signal ? { signal } : {},
1035
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
1036
+ });
1037
+ }
1038
+ /**
1039
+ * Collapse an active session into durable knowledge units (facts,
1040
+ * decisions, strategies). The server returns 202 Accepted after the
1041
+ * collapse pipeline completes.
1042
+ *
1043
+ * Throws `MnemosyneAPIError` with status 404 when the session does not
1044
+ * exist or has already been collapsed.
1045
+ *
1046
+ * Maps to `POST /v1/session/:id/collapse` on the Mnemosyne server.
1047
+ */
1048
+ collapseSession(id, input = {}, signal, idempotencyKey) {
1049
+ return this.http.request({
1050
+ method: "POST",
1051
+ path: `/session/${encodeURIComponent(id)}/collapse`,
1052
+ body: input,
1053
+ ...signal ? { signal } : {},
1054
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
1055
+ });
1056
+ }
1057
+ /**
1058
+ * Append a conversation turn to an active session's transcript.
1059
+ *
1060
+ * Both user and assistant turns should be recorded here so the collapse
1061
+ * pipeline can extract facts from the full conversation context.
1062
+ *
1063
+ * Maps to `POST /v1/session/:id/turn`. Returns 204 No Content (void).
1064
+ */
1065
+ appendTurn(id, input, signal) {
1066
+ return this.http.request({
1067
+ method: "POST",
1068
+ path: `/session/${encodeURIComponent(id)}/turn`,
1069
+ body: input,
1070
+ ...signal ? { signal } : {}
1071
+ });
1072
+ }
1073
+ /**
1074
+ * Pin or unpin a specific turn within an active session.
1075
+ *
1076
+ * Pinned turns are given higher weight during the collapse extraction pass
1077
+ * and are more likely to become durable facts.
1078
+ *
1079
+ * Maps to `POST /v1/session/:id/pin`. Returns 204 No Content (void).
1080
+ */
1081
+ pinSessionTurn(id, input, signal) {
1082
+ return this.http.request({
1083
+ method: "POST",
1084
+ path: `/session/${encodeURIComponent(id)}/pin`,
1085
+ body: input,
1086
+ ...signal ? { signal } : {}
1087
+ });
1088
+ }
1089
+ /**
1090
+ * Submit explicit user feedback (thumbs up/down rating) for a session.
1091
+ *
1092
+ * Maps to `POST /v1/session/:id/feedback`. Returns 204 No Content (void).
1093
+ */
1094
+ sessionFeedback(id, rating, signal) {
1095
+ return this.http.request({
1096
+ method: "POST",
1097
+ path: `/session/${encodeURIComponent(id)}/feedback`,
1098
+ body: { rating },
1099
+ ...signal ? { signal } : {}
1100
+ });
1101
+ }
1102
+ /**
1103
+ * Namespaced session helpers — convenience wrapper that satisfies the
1104
+ * spec's chaining example with zero client state.
1105
+ *
1106
+ * @example
1107
+ * ```ts
1108
+ * const { id } = await client.sessions.create();
1109
+ * await client.sessions.addTurn(id, { role: "user", content: "Hello!" });
1110
+ * await client.sessions.pinTurn(id, { turnId: "turn_1", pinned: true });
1111
+ * await client.sessions.collapse(id);
1112
+ * ```
1113
+ */
1114
+ get sessions() {
1115
+ return {
1116
+ create: (input, signal, idempotencyKey) => this.createSession(input, signal, idempotencyKey),
1117
+ addTurn: (id, input, signal) => this.appendTurn(id, input, signal),
1118
+ pinTurn: (id, input, signal) => this.pinSessionTurn(id, input, signal),
1119
+ collapse: (id, input, signal, idempotencyKey) => this.collapseSession(id, input, signal, idempotencyKey),
1120
+ feedback: (id, rating, signal) => this.sessionFeedback(id, rating, signal)
1121
+ };
1122
+ }
1123
+ /**
1124
+ * Write a scratch note (ephemeral working-memory entry) to an active session.
1125
+ *
1126
+ * The `scratch` object is stored under the session's working-memory context.
1127
+ * The `note` key conventionally carries the human-readable text; additional
1128
+ * arbitrary keys are passed through as metadata (e.g. `{ role, metadata }`).
1129
+ *
1130
+ * Maps to `POST /v1/session/:id/scratch` (not `/turn` — they are different
1131
+ * endpoints: `/scratch` is ephemeral working-memory, `/turn` is transcript).
1132
+ * Returns 204 No Content, so this resolves to `void`.
1133
+ */
1134
+ updateSessionScratch(id, scratch, signal) {
1135
+ return this.http.request({
1136
+ method: "POST",
1137
+ path: `/session/${encodeURIComponent(id)}/scratch`,
1138
+ body: { scratch },
1139
+ ...signal ? { signal } : {}
1140
+ });
1141
+ }
1142
+ /**
1143
+ * Discard an active session without collapsing it into durable memory.
1144
+ *
1145
+ * Use when the conversation should be abandoned (e.g. user cancelled or
1146
+ * the context is irrelevant) rather than collapsed into knowledge units.
1147
+ * The server marks the session as discarded; no extraction pass is run.
1148
+ *
1149
+ * Maps to `POST /v1/session/:id/discard`. Returns 204 No Content, so this
1150
+ * resolves to `void`.
1151
+ */
1152
+ discardSession(id, signal) {
1153
+ return this.http.request({
1154
+ method: "POST",
1155
+ path: `/session/${encodeURIComponent(id)}/discard`,
1156
+ ...signal ? { signal } : {}
1157
+ });
1158
+ }
1159
+ /**
1160
+ * Trigger an on-demand consolidation pass for the workspace.
1161
+ *
1162
+ * The background scheduler already runs on its own interval. Use this
1163
+ * method when you want to force a consolidation immediately — e.g. after
1164
+ * a large batch of `remember` calls, or when the `memory_consolidate`
1165
+ * MCP tool is invoked.
1166
+ *
1167
+ * Only `mode: "fast"` (default) with `dryRun: false` is currently
1168
+ * supported and processes a bounded low-worth candidate set. Manual `mode: "deep"`
1169
+ * requests throw `MnemosyneAPIError` with status 422 and code
1170
+ * `deep_mode_not_supported`. Requests with `dryRun: true` throw status 422
1171
+ * with code `dry_run_not_supported`, without running consolidation.
1172
+ *
1173
+ * Throws `MnemosyneAPIError` with status 503 when required server-side
1174
+ * consolidation or storage services are unavailable.
1175
+ *
1176
+ * Maps to `POST /v1/consolidation/trigger`.
1177
+ */
1178
+ triggerConsolidation(input = {}, signal, idempotencyKey) {
1179
+ return this.http.request({
1180
+ method: "POST",
1181
+ path: "/consolidation/trigger",
1182
+ body: input,
1183
+ ...signal ? { signal } : {},
1184
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
1185
+ });
1186
+ }
1187
+ // ── Tasks ─────────────────────────────────────────────────────────────────
1188
+ /** List tasks for the workspace. Maps to `GET /v1/tasks`. */
1189
+ listTasks(params, signal) {
1190
+ return this.http.request({
1191
+ method: "GET",
1192
+ path: "/tasks",
1193
+ query: params ? { ...params } : void 0,
1194
+ ...signal ? { signal } : {}
1195
+ });
1196
+ }
1197
+ /** Create a new task. Maps to `POST /v1/tasks`. */
1198
+ createTask(body, signal, idempotencyKey) {
1199
+ return this.http.request({
1200
+ method: "POST",
1201
+ path: "/tasks",
1202
+ body,
1203
+ ...signal ? { signal } : {},
1204
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
1205
+ });
1206
+ }
1207
+ /** Get a single task by ID. Maps to `GET /v1/tasks/:id`. */
1208
+ getTask(id, signal) {
1209
+ return this.http.request({
1210
+ method: "GET",
1211
+ path: `/tasks/${encodeURIComponent(id)}`,
1212
+ ...signal ? { signal } : {}
1213
+ });
1214
+ }
1215
+ /** Update fields on an existing task. Maps to `PATCH /v1/tasks/:id`. */
1216
+ patchTask(id, body, signal) {
1217
+ return this.http.request({
1218
+ method: "PATCH",
1219
+ path: `/tasks/${encodeURIComponent(id)}`,
1220
+ body,
1221
+ ...signal ? { signal } : {}
1222
+ });
1223
+ }
1224
+ /** Archive (soft-delete) a task. Maps to `DELETE /v1/tasks/:id`. */
1225
+ archiveTask(id, signal) {
1226
+ return this.http.request({
1227
+ method: "DELETE",
1228
+ path: `/tasks/${encodeURIComponent(id)}`,
1229
+ ...signal ? { signal } : {}
1230
+ });
1231
+ }
1232
+ // ── Events ────────────────────────────────────────────────────────────────
1233
+ /** List events for the workspace. Maps to `GET /v1/events`. */
1234
+ listEvents(params, signal) {
1235
+ return this.http.request({
1236
+ method: "GET",
1237
+ path: "/events",
1238
+ query: params ? { ...params } : void 0,
1239
+ ...signal ? { signal } : {}
1240
+ });
1241
+ }
1242
+ /** Create a new event (immutable append). Maps to `POST /v1/events`. */
1243
+ createEvent(body, signal, idempotencyKey) {
1244
+ return this.http.request({
1245
+ method: "POST",
1246
+ path: "/events",
1247
+ body,
1248
+ ...signal ? { signal } : {},
1249
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
1250
+ });
1251
+ }
1252
+ /** Get a single event by ID. Maps to `GET /v1/events/:id`. */
1253
+ getEvent(id, signal) {
1254
+ return this.http.request({
1255
+ method: "GET",
1256
+ path: `/events/${encodeURIComponent(id)}`,
1257
+ ...signal ? { signal } : {}
1258
+ });
1259
+ }
1260
+ /** Archive an event (soft-delete). Maps to `DELETE /v1/events/:id`. */
1261
+ archiveEvent(id, signal) {
1262
+ return this.http.request({
1263
+ method: "DELETE",
1264
+ path: `/events/${encodeURIComponent(id)}`,
1265
+ ...signal ? { signal } : {}
1266
+ });
1267
+ }
1268
+ /** Append a human annotation to an immutable event. Maps to `POST /v1/events/:id/annotations`. */
1269
+ annotateEvent(id, body, signal) {
1270
+ return this.http.request({
1271
+ method: "POST",
1272
+ path: `/events/${encodeURIComponent(id)}/annotations`,
1273
+ body,
1274
+ ...signal ? { signal } : {}
1275
+ });
1276
+ }
1277
+ // ── Workflows ─────────────────────────────────────────────────────────────
1278
+ /** List workflows in the workspace. Maps to `GET /v1/workflows`. */
1279
+ listWorkflows(params, signal) {
1280
+ return this.http.request({
1281
+ method: "GET",
1282
+ path: "/workflows",
1283
+ query: params ? { ...params } : void 0,
1284
+ ...signal ? { signal } : {}
1285
+ });
1286
+ }
1287
+ /** Create a new workflow. Maps to `POST /v1/workflows`. */
1288
+ createWorkflow(body, signal) {
1289
+ return this.http.request({
1290
+ method: "POST",
1291
+ path: "/workflows",
1292
+ body,
1293
+ ...signal ? { signal } : {}
1294
+ });
1295
+ }
1296
+ /** Get a single workflow by ID. Maps to `GET /v1/workflows/:id`. */
1297
+ getWorkflow(id, signal) {
1298
+ return this.http.request({
1299
+ method: "GET",
1300
+ path: `/workflows/${encodeURIComponent(id)}`,
1301
+ ...signal ? { signal } : {}
1302
+ });
1303
+ }
1304
+ // ── Reasoning ─────────────────────────────────────────────────────────────
1305
+ /** List reasoning chains for the workspace. Maps to `GET /v1/reasoning`. */
1306
+ listReasoning(params, signal) {
1307
+ return this.http.request({
1308
+ method: "GET",
1309
+ path: "/reasoning",
1310
+ query: params ? { ...params } : void 0,
1311
+ ...signal ? { signal } : {}
1312
+ });
1313
+ }
1314
+ /** Create a new reasoning chain. Maps to `POST /v1/reasoning`. */
1315
+ createReasoning(body, signal) {
1316
+ return this.http.request({
1317
+ method: "POST",
1318
+ path: "/reasoning",
1319
+ body,
1320
+ ...signal ? { signal } : {}
1321
+ });
1322
+ }
1323
+ /** Get a single reasoning chain by ID. Maps to `GET /v1/reasoning/:id`. */
1324
+ getReasoning(id, signal) {
1325
+ return this.http.request({
1326
+ method: "GET",
1327
+ path: `/reasoning/${encodeURIComponent(id)}`,
1328
+ ...signal ? { signal } : {}
1329
+ });
1330
+ }
1331
+ /** Update fields on an existing reasoning chain. Maps to `PATCH /v1/reasoning/:id`. */
1332
+ patchReasoning(id, body, signal) {
1333
+ return this.http.request({
1334
+ method: "PATCH",
1335
+ path: `/reasoning/${encodeURIComponent(id)}`,
1336
+ body,
1337
+ ...signal ? { signal } : {}
1338
+ });
1339
+ }
1340
+ /** Archive (soft-delete) a reasoning chain. Maps to `DELETE /v1/reasoning/:id`. */
1341
+ archiveReasoning(id, signal) {
1342
+ return this.http.request({
1343
+ method: "DELETE",
1344
+ path: `/reasoning/${encodeURIComponent(id)}`,
1345
+ ...signal ? { signal } : {}
1346
+ });
1347
+ }
1348
+ /** Resolve a reasoning query against the CoT cache. Maps to `POST /v1/reasoning/resolve`. */
1349
+ resolveReasoning(body, signal) {
1350
+ return this.http.request({
1351
+ method: "POST",
1352
+ path: "/reasoning/resolve",
1353
+ body,
1354
+ ...signal ? { signal } : {}
1355
+ });
1356
+ }
1357
+ /** Record a completed reasoning chain into the CoT cache. Maps to `POST /v1/reasoning/record`. */
1358
+ recordReasoning(body, signal) {
1359
+ return this.http.request({
1360
+ method: "POST",
1361
+ path: "/reasoning/record",
1362
+ body,
1363
+ ...signal ? { signal } : {}
1364
+ });
1365
+ }
1366
+ /** Submit outcome feedback for a cached reasoning chain. Maps to `POST /v1/reasoning/feedback`. */
1367
+ reasoningFeedback(body, signal) {
1368
+ return this.http.request({
1369
+ method: "POST",
1370
+ path: "/reasoning/feedback",
1371
+ body,
1372
+ ...signal ? { signal } : {}
1373
+ });
1374
+ }
1375
+ // ── Strategies ────────────────────────────────────────────────────────────
1376
+ /** List strategies for the workspace. */
1377
+ listStrategies(params, signal) {
1378
+ return this.http.request({
1379
+ method: "GET",
1380
+ path: "/strategies",
1381
+ query: { ...params },
1382
+ ...signal ? { signal } : {}
1383
+ });
1384
+ }
1385
+ /** Create a new strategy. */
1386
+ createStrategy(body, signal, idempotencyKey) {
1387
+ return this.http.request({
1388
+ method: "POST",
1389
+ path: "/strategies",
1390
+ body,
1391
+ ...signal ? { signal } : {},
1392
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
1393
+ });
1394
+ }
1395
+ /** Get a single strategy by ID. */
1396
+ getStrategy(id, signal) {
1397
+ return this.http.request({
1398
+ method: "GET",
1399
+ path: `/strategies/${id}`,
1400
+ ...signal ? { signal } : {}
1401
+ });
1402
+ }
1403
+ /** Patch an existing strategy. */
1404
+ patchStrategy(id, body, signal) {
1405
+ return this.http.request({
1406
+ method: "PATCH",
1407
+ path: `/strategies/${id}`,
1408
+ body,
1409
+ ...signal ? { signal } : {}
1410
+ });
1411
+ }
1412
+ /** Archive a strategy (soft-delete). */
1413
+ archiveStrategy(id, signal) {
1414
+ return this.http.request({
1415
+ method: "DELETE",
1416
+ path: `/strategies/${id}`,
1417
+ ...signal ? { signal } : {}
1418
+ });
1419
+ }
1420
+ /**
1421
+ * §24 Record the outcome of executing a strategy.
1422
+ * Triggers a Beta-Bernoulli recompute on the server:
1423
+ * alpha = 2 + successCount, beta = 2 + failureCount, worth = alpha / (alpha + beta).
1424
+ * Not idempotent — each call increments successCount or failureCount.
1425
+ */
1426
+ rateStrategy(id, outcome, signal) {
1427
+ return this.http.request({
1428
+ method: "POST",
1429
+ path: `/strategies/${id}/rate`,
1430
+ body: { outcome },
1431
+ ...signal ? { signal } : {}
1432
+ });
1433
+ }
1434
+ // ── Hyperedges ─────────────────────────────────────────────────────────────
1435
+ /** List hyperedges for this workspace. */
1436
+ listHyperedges(params, signal) {
1437
+ return this.http.request({
1438
+ method: "GET",
1439
+ path: "/hyperedges",
1440
+ query: params ? { ...params } : void 0,
1441
+ ...signal ? { signal } : {}
1442
+ });
1443
+ }
1444
+ /** Create a new hyperedge (n-ary relation with ≥3 members). */
1445
+ createHyperedge(body, signal, idempotencyKey) {
1446
+ return this.http.request({
1447
+ method: "POST",
1448
+ path: "/hyperedges",
1449
+ body,
1450
+ ...signal ? { signal } : {},
1451
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
1452
+ });
1453
+ }
1454
+ /** Get a single hyperedge by ID. */
1455
+ getHyperedge(id, signal) {
1456
+ return this.http.request({
1457
+ method: "GET",
1458
+ path: `/hyperedges/${encodeURIComponent(id)}`,
1459
+ ...signal ? { signal } : {}
1460
+ });
1461
+ }
1462
+ /** Patch an existing hyperedge (label, description, contextQuery). */
1463
+ patchHyperedge(id, body, signal) {
1464
+ return this.http.request({
1465
+ method: "PATCH",
1466
+ path: `/hyperedges/${encodeURIComponent(id)}`,
1467
+ body,
1468
+ ...signal ? { signal } : {}
1469
+ });
1470
+ }
1471
+ /** Archive a hyperedge (soft-delete). */
1472
+ archiveHyperedge(id, signal) {
1473
+ return this.http.request({
1474
+ method: "DELETE",
1475
+ path: `/hyperedges/${encodeURIComponent(id)}`,
1476
+ ...signal ? { signal } : {}
1477
+ });
1478
+ }
1479
+ // ── Meta-cognition (§31) ───────────────────────────────────────────────────
1480
+ /** Return the workspace SelfModel (§31 meta-cognition). */
1481
+ getSelfModel(opts, signal) {
1482
+ const query = new URLSearchParams();
1483
+ if (opts?.aspect) query.set("aspect", opts.aspect);
1484
+ if (opts?.entity) query.set("entity", opts.entity);
1485
+ if (opts?.limit !== void 0) query.set("limit", String(opts.limit));
1486
+ const qs = query.toString();
1487
+ return this.http.request({
1488
+ method: "GET",
1489
+ path: `/metacognition${qs ? `?${qs}` : ""}`,
1490
+ ...signal ? { signal } : {}
1491
+ });
1492
+ }
1493
+ // ── Anticipation (§8) ─────────────────────────────────────────────────────
1494
+ /**
1495
+ * Return ranked anticipated memories (§8 Anticipation Engine).
1496
+ *
1497
+ * The `GET /v1/anticipation` route honors four query params:
1498
+ * - `recentlyRecalledId` — drives the sequential ("when I recall X I
1499
+ * usually recall Y") branch. Without it, only periodicity counts.
1500
+ * - `context` — free-text query context for conditional anticipation
1501
+ * patterns (§30). Server caps length at 500 chars.
1502
+ * - `lookAhead` — minutes to anticipate ahead (§30); shifts the
1503
+ * periodic slot. Server default 30, range 0–10080 (one week).
1504
+ * - `limit` — max items, server default 20, range 1–100.
1505
+ */
1506
+ async getAnticipationFeed(opts) {
1507
+ const query = new URLSearchParams();
1508
+ if (opts?.recentlyRecalledId) query.set("recentlyRecalledId", opts.recentlyRecalledId);
1509
+ if (opts?.context) query.set("context", opts.context);
1510
+ if (opts?.lookAhead != null) query.set("lookAhead", String(opts.lookAhead));
1511
+ if (opts?.limit != null) query.set("limit", String(opts.limit));
1512
+ const qs = query.toString();
1513
+ return this.http.request({
1514
+ method: "GET",
1515
+ path: `/anticipation${qs ? `?${qs}` : ""}`
1516
+ });
1517
+ }
1518
+ // ── Composition (§32) ─────────────────────────────────────────────────────
1519
+ /**
1520
+ * Namespace getter for §32 Compositionality Engine admin routes.
1521
+ *
1522
+ * @example
1523
+ * ```ts
1524
+ * const page = await client.composition.listRules({ isActive: true });
1525
+ * const rule = await client.composition.createRule({ name: "My Rule", ... });
1526
+ * const dryRun = await client.composition.dryRun({ ruleId: "r-1", hits });
1527
+ * ```
1528
+ */
1529
+ get composition() {
1530
+ const http = this.http;
1531
+ return {
1532
+ listRules(opts) {
1533
+ const q = new URLSearchParams();
1534
+ if (opts?.isActive !== void 0) q.set("isActive", String(opts.isActive));
1535
+ if (opts?.offset != null) q.set("offset", String(opts.offset));
1536
+ if (opts?.limit != null) q.set("limit", String(opts.limit));
1537
+ const qs = q.toString();
1538
+ return http.request({
1539
+ method: "GET",
1540
+ path: `/composition/rules${qs ? `?${qs}` : ""}`,
1541
+ ...opts?.signal ? { signal: opts.signal } : {}
1542
+ });
1543
+ },
1544
+ createRule(input, signal) {
1545
+ return http.request({
1546
+ method: "POST",
1547
+ path: "/composition/rules",
1548
+ body: input,
1549
+ ...signal ? { signal } : {}
1550
+ });
1551
+ },
1552
+ getRule(id, signal) {
1553
+ return http.request({
1554
+ method: "GET",
1555
+ path: `/composition/rules/${encodeURIComponent(id)}`,
1556
+ ...signal ? { signal } : {}
1557
+ });
1558
+ },
1559
+ patchRule(id, patch, signal) {
1560
+ return http.request({
1561
+ method: "PATCH",
1562
+ path: `/composition/rules/${encodeURIComponent(id)}`,
1563
+ body: patch,
1564
+ ...signal ? { signal } : {}
1565
+ });
1566
+ },
1567
+ dryRun(input, signal) {
1568
+ return http.request({
1569
+ method: "POST",
1570
+ path: "/composition/dry-run",
1571
+ body: input,
1572
+ ...signal ? { signal } : {}
1573
+ });
1574
+ }
1575
+ };
1576
+ }
1577
+ // ── Wave M2: Self-Editing Memory (spec §13) ───────────────────────────────
1578
+ /**
1579
+ * Edit the agent's own memory using one of seven actions:
1580
+ * append | replace | strengthen | weaken | forget | reflect | link.
1581
+ * `target` is polymorphic: fact_id | "profile" | "strategy:{id}".
1582
+ * `reason` is required policy and log context, but is not durably audited yet.
1583
+ * link: creates an n-ary hyperedge; target=anchor, content=comma-separated co-members (total ≥3).
1584
+ */
1585
+ selfEdit(input, signal, idempotencyKey) {
1586
+ return this.http.request({
1587
+ method: "POST",
1588
+ path: "/self/edit",
1589
+ body: input,
1590
+ ...signal ? { signal } : {},
1591
+ ...idempotencyKey ? { extraHeaders: { "Idempotency-Key": idempotencyKey } } : {}
1592
+ });
1593
+ }
1594
+ /**
1595
+ * Trigger the reflection cycle immediately for an agent.
1596
+ * Returns the episode_id of the synthetic reflection episode plus
1597
+ * the lists of strengthened / weakened strategy ids.
1598
+ */
1599
+ selfReflect(input, signal) {
1600
+ return this.http.request({
1601
+ method: "POST",
1602
+ path: "/self/reflect",
1603
+ body: input ?? {},
1604
+ ...signal ? { signal } : {}
1605
+ });
1606
+ }
1607
+ /**
1608
+ * Retrieve the current agent profile (self-model).
1609
+ * Returns an empty profile (summary: "") when none exists yet.
1610
+ */
1611
+ getSelfProfile(agentId, signal) {
1612
+ const qs = agentId ? `?agentId=${encodeURIComponent(agentId)}` : "";
1613
+ return this.http.request({
1614
+ method: "GET",
1615
+ path: `/self/profile${qs}`,
1616
+ ...signal ? { signal } : {}
1617
+ });
1618
+ }
1619
+ // ── Federation (§20) ──────────────────────────────────────────────────────
1620
+ /**
1621
+ * List all approved peers in the federation mesh.
1622
+ * Maps to `GET /v1/memory/federation/peers`.
1623
+ */
1624
+ listFederationPeers(signal) {
1625
+ return this.http.request({
1626
+ method: "GET",
1627
+ path: "/memory/federation/peers",
1628
+ ...signal ? { signal } : {}
1629
+ });
1630
+ }
1631
+ /**
1632
+ * List peers awaiting approval plus discovery state.
1633
+ * Maps to `GET /v1/memory/federation/peers/pending`.
1634
+ */
1635
+ listPendingFederationPeers(signal) {
1636
+ return this.http.request({
1637
+ method: "GET",
1638
+ path: "/memory/federation/peers/pending",
1639
+ ...signal ? { signal } : {}
1640
+ });
1641
+ }
1642
+ /**
1643
+ * Approve a pending peer (certificate rotation).
1644
+ * Maps to `POST /v1/memory/federation/peers/:id/approve`.
1645
+ */
1646
+ approveFederationPeer(id, input, signal) {
1647
+ return this.http.request({
1648
+ method: "POST",
1649
+ path: `/memory/federation/peers/${encodeURIComponent(id)}/approve`,
1650
+ body: input,
1651
+ ...signal ? { signal } : {}
1652
+ });
1653
+ }
1654
+ /**
1655
+ * Approve a peer's public key specifically.
1656
+ * Maps to `POST /v1/memory/federation/peers/:id/approve-key`.
1657
+ */
1658
+ approveFederationPeerKey(id, input, signal) {
1659
+ return this.http.request({
1660
+ method: "POST",
1661
+ path: `/memory/federation/peers/${encodeURIComponent(id)}/approve-key`,
1662
+ body: input,
1663
+ ...signal ? { signal } : {}
1664
+ });
1665
+ }
1666
+ /**
1667
+ * Remove a peer from the federation mesh.
1668
+ * Maps to `DELETE /v1/memory/federation/peers/:id`.
1669
+ */
1670
+ deleteFederationPeer(id, signal) {
1671
+ return this.http.request({
1672
+ method: "DELETE",
1673
+ path: `/memory/federation/peers/${encodeURIComponent(id)}`,
1674
+ ...signal ? { signal } : {}
1675
+ });
1676
+ }
1677
+ /**
1678
+ * Fetch the federated item log (facts received from peers).
1679
+ * Maps to `GET /v1/memory/federation/items`.
1680
+ */
1681
+ listFederationItems(opts, signal) {
1682
+ return this.http.request({
1683
+ method: "GET",
1684
+ path: "/memory/federation/items",
1685
+ query: { since: opts?.since, limit: opts?.limit },
1686
+ ...signal ? { signal } : {}
1687
+ });
1688
+ }
1689
+ /**
1690
+ * Trigger an immediate sync pull from a peer.
1691
+ * Maps to `POST /v1/memory/federation/sync` (returns 202 Accepted).
1692
+ */
1693
+ triggerFederationSync(input, signal) {
1694
+ return this.http.request({
1695
+ method: "POST",
1696
+ path: "/memory/federation/sync",
1697
+ body: input,
1698
+ ...signal ? { signal } : {}
1699
+ });
1700
+ }
1701
+ /**
1702
+ * Get status of a federation sync job by its jobId.
1703
+ * Maps to `GET /v1/memory/federation/sync/:jobId`.
1704
+ */
1705
+ getFederationSyncJob(jobId, signal) {
1706
+ return this.http.request({
1707
+ method: "GET",
1708
+ path: `/memory/federation/sync/${encodeURIComponent(jobId)}`,
1709
+ ...signal ? { signal } : {}
1710
+ });
1711
+ }
1712
+ /**
1713
+ * Resolve a conflict between federated claims. Accepts either a
1714
+ * two-item pair (`{ itemA, itemB }`) or a batch (`{ items: [...] }`).
1715
+ *
1716
+ * Maps to `POST /v1/memory/federation/resolve`.
1717
+ */
1718
+ resolveFederationConflict(input, signal) {
1719
+ return this.http.request({
1720
+ method: "POST",
1721
+ path: "/memory/federation/resolve",
1722
+ body: input,
1723
+ ...signal ? { signal } : {}
1724
+ });
1725
+ }
1726
+ // ── P4-D: Conflict resolution (memory_judge) ──────────────────────────────
1727
+ /**
1728
+ * List unresolved conflict pairs in the workspace.
1729
+ *
1730
+ * Conflicts are `conflicts_with` relations between active facts that have
1731
+ * not yet been resolved. The list is sorted newest-first. Use
1732
+ * `resolveConflict` to apply a resolution action to each pair.
1733
+ *
1734
+ * @param limit - Max pairs to return. Default 5, max 20.
1735
+ * Maps to `GET /v1/conflicts`.
1736
+ */
1737
+ judge(opts, signal) {
1738
+ return this.http.request({
1739
+ method: "GET",
1740
+ path: "/conflicts",
1741
+ query: opts?.limit != null ? { limit: opts.limit } : void 0,
1742
+ ...signal ? { signal } : {}
1743
+ });
1744
+ }
1745
+ /**
1746
+ * Resolve a specific conflict pair by its `relationId`.
1747
+ *
1748
+ * Four resolution strategies:
1749
+ * - `supersede_a`: forget factA, relation becomes `supersedes`.
1750
+ * - `supersede_b`: forget factB, relation becomes `supersedes`.
1751
+ * - `keep_both`: mark as `not_conflict` (both facts stay active).
1752
+ * - `merge`: forget both, create a new merged fact, relation becomes `supersedes`.
1753
+ * `mergedStatement` is required for this action.
1754
+ *
1755
+ * Maps to `POST /v1/conflicts/:id/resolve`.
1756
+ */
1757
+ resolveConflict(relationId, input, signal) {
1758
+ return this.http.request({
1759
+ method: "POST",
1760
+ path: `/conflicts/${encodeURIComponent(relationId)}/resolve`,
1761
+ body: input,
1762
+ ...signal ? { signal } : {}
1763
+ });
1764
+ }
1765
+ // ── WebSocket subscriptions ────────────────────────────────────────────────
1766
+ /**
1767
+ * Subscribe to a Mnemosyne event channel via WebSocket.
1768
+ *
1769
+ * Opens a WebSocket to `/memory/ws?token=<apiKey>`, sends a subscribe
1770
+ * frame for `channel`, and calls `handler` for each matching event.
1771
+ *
1772
+ * Requires a `WebSocket` global (native in Node ≥ 22 and browsers; inject
1773
+ * via `opts.WebSocketImpl` for older environments):
1774
+ *
1775
+ * ```ts
1776
+ * import WebSocket from "ws"; // npm install ws
1777
+ * const handle = client.subscribe("facts.*", console.log, { WebSocketImpl: WebSocket });
1778
+ * ```
1779
+ *
1780
+ * Live server integration requires Wave Q WS wiring to be confirmed.
1781
+ * Tests are skipped until then.
1782
+ *
1783
+ * @param channel - Glob channel, e.g. `"facts.*"`, `"session.abc123"`.
1784
+ * @param handler - Called with each raw bus event payload (JSON).
1785
+ * @param opts - Optional filter / disconnect / WebSocketImpl.
1786
+ */
1787
+ // UNSKIP after Wave Q server wiring is confirmed.
1788
+ subscribe(channel, handler, opts) {
1789
+ const base = this.http["config"].baseUrl.replace(/^http/, "ws");
1790
+ const url = `${base}/memory/ws?token=${encodeURIComponent(this.http["config"].apiKey)}`;
1791
+ const WS = opts?.WebSocketImpl ?? (typeof WebSocket !== "undefined" ? WebSocket : void 0);
1792
+ if (!WS) {
1793
+ throw new Error(
1794
+ "MnemosyneClient.subscribe: no WebSocket implementation available. Pass `opts.WebSocketImpl` (e.g. from the `ws` npm package) or use Node \u2265 22."
1795
+ );
1796
+ }
1797
+ const ws = new WS(url);
1798
+ let _connected = false;
1799
+ ws.addEventListener("open", () => {
1800
+ _connected = true;
1801
+ ws.send(
1802
+ JSON.stringify({
1803
+ subscribe: {
1804
+ channel,
1805
+ ...opts?.filter ? { filter: opts.filter } : {}
1806
+ }
1807
+ })
1808
+ );
1809
+ });
1810
+ ws.addEventListener("message", (ev) => {
1811
+ try {
1812
+ const data = typeof ev.data === "string" ? JSON.parse(ev.data) : ev.data;
1813
+ if (data && typeof data === "object" && !("subscribe" in data) && !("unsubscribe" in data)) {
1814
+ handler(data);
1815
+ }
1816
+ } catch {
1817
+ }
1818
+ });
1819
+ ws.addEventListener("close", (ev) => {
1820
+ _connected = false;
1821
+ if (opts?.onDisconnect) {
1822
+ opts.onDisconnect(String(ev.reason ?? ev.code));
1823
+ }
1824
+ });
1825
+ return {
1826
+ close() {
1827
+ _connected = false;
1828
+ ws.close(1e3, "client closed");
1829
+ },
1830
+ get connected() {
1831
+ return _connected;
1832
+ }
1833
+ };
1834
+ }
1835
+ // ── gRPC / ConnectRPC transport ────────────────────────────────────────────
1836
+ // ── Passive capture (P4-C) ────────────────────────────────────────────────
1837
+ /**
1838
+ * Passive capture — send subagent or pipeline output to Mnemosyne for
1839
+ * automatic fact extraction.
1840
+ *
1841
+ * The server extracts 0-3 durable facts from `content`. When an LLM is
1842
+ * configured server-side it uses guided extraction; otherwise regex
1843
+ * heuristics detect decision/bugfix/config patterns. Identical content
1844
+ * within the same workspace is deduplicated via content-hash.
1845
+ *
1846
+ * Designed for fire-and-forget use from Claude Code hooks:
1847
+ * ```ts
1848
+ * await client.capture({ content: agentStdout, source: "subagent-stop" });
1849
+ * ```
1850
+ *
1851
+ * Maps to `POST /v1/capture`.
1852
+ */
1853
+ capture(opts, signal) {
1854
+ return this.http.request({
1855
+ method: "POST",
1856
+ path: "/capture",
1857
+ body: opts,
1858
+ ...signal ? { signal } : {}
1859
+ });
1860
+ }
1861
+ // ── P5-C: Hard-delete / purge ─────────────────────────────────────────────
1862
+ /**
1863
+ * Hard-delete a single fact by ID (GDPR / test-workspace cleanup).
1864
+ *
1865
+ * Performs a physical DELETE on `mnemo_fact`. The row is permanently removed —
1866
+ * this bypasses the bitemporal model and cannot be undone. Use only in
1867
+ * test workspaces or when legally required.
1868
+ *
1869
+ * Requires `memory:hard_delete` scope on the API key. Returns 403 when the
1870
+ * key lacks that scope.
1871
+ *
1872
+ * Maps to `DELETE /v1/facts/:id/hard`.
1873
+ */
1874
+ purgeFact(id, signal) {
1875
+ return this.http.request({
1876
+ method: "DELETE",
1877
+ path: `/facts/${encodeURIComponent(id)}/hard`,
1878
+ ...signal ? { signal } : {}
1879
+ });
1880
+ }
1881
+ /**
1882
+ * Bulk hard-delete all closed (forgotten) facts in the workspace.
1883
+ *
1884
+ * Deletes every fact whose `status = 'forgotten'` (i.e. facts that were
1885
+ * soft-deleted via `memory_forget`). Useful for reclaiming space in test
1886
+ * workspaces after a test run.
1887
+ *
1888
+ * Requires `memory:hard_delete` scope on the API key. Returns 403 when the
1889
+ * key lacks that scope.
1890
+ *
1891
+ * Maps to `DELETE /v1/facts/purge`.
1892
+ */
1893
+ purgeClosedFacts(signal) {
1894
+ return this.http.request({
1895
+ method: "DELETE",
1896
+ path: "/facts/purge",
1897
+ ...signal ? { signal } : {}
1898
+ });
1899
+ }
1900
+ // ── P7: Key management ────────────────────────────────────────────────────────
1901
+ /**
1902
+ * List API keys for the current workspace.
1903
+ * Requires `admin:keys` scope.
1904
+ */
1905
+ listKeys(options, signal) {
1906
+ const path = options?.expired ? "/admin/keys?expired=true" : "/admin/keys";
1907
+ return this.http.request({
1908
+ method: "GET",
1909
+ path,
1910
+ ...signal ? { signal } : {}
1911
+ });
1912
+ }
1913
+ /**
1914
+ * Create a new API key for the current workspace.
1915
+ * Plaintext key is returned ONCE in the response.
1916
+ * Requires `admin:keys` scope.
1917
+ */
1918
+ createKey(input, signal) {
1919
+ return this.http.request({
1920
+ method: "POST",
1921
+ path: "/admin/keys",
1922
+ body: input,
1923
+ ...signal ? { signal } : {}
1924
+ });
1925
+ }
1926
+ /**
1927
+ * Get metadata for a single API key (secret is never returned).
1928
+ * Requires `admin:keys` scope.
1929
+ */
1930
+ getKey(keyId, signal) {
1931
+ return this.http.request({
1932
+ method: "GET",
1933
+ path: `/admin/keys/${encodeURIComponent(keyId)}`,
1934
+ ...signal ? { signal } : {}
1935
+ });
1936
+ }
1937
+ /**
1938
+ * Revoke an API key by ID.
1939
+ * Requires `admin:keys` scope.
1940
+ */
1941
+ revokeKey(keyId, signal) {
1942
+ return this.http.request({
1943
+ method: "DELETE",
1944
+ path: `/admin/keys/${encodeURIComponent(keyId)}`,
1945
+ ...signal ? { signal } : {}
1946
+ });
1947
+ }
1948
+ /**
1949
+ * Rotate an API key by ID. Generates a new key with 7 days sunset grace for the old key.
1950
+ * Requires `admin:keys` scope.
1951
+ */
1952
+ rotateKey(keyId, input, signal) {
1953
+ return this.http.request({
1954
+ method: "POST",
1955
+ path: `/admin/keys/${encodeURIComponent(keyId)}/rotate`,
1956
+ ...input ? { body: input } : {},
1957
+ ...signal ? { signal } : {}
1958
+ });
1959
+ }
1960
+ // ── B6.11: Skill primitive ───────────────────────────────────────────────────
1961
+ /**
1962
+ * Create a new Skill (stored prompt template).
1963
+ * Maps to `POST /v1/skills`.
1964
+ */
1965
+ createSkill(input, signal) {
1966
+ return this.http.request({
1967
+ method: "POST",
1968
+ path: "/skills",
1969
+ body: input,
1970
+ ...signal ? { signal } : {}
1971
+ });
1972
+ }
1973
+ /**
1974
+ * List skills for the current workspace.
1975
+ * Maps to `GET /v1/skills`.
1976
+ */
1977
+ listSkills(options, signal) {
1978
+ const params = new URLSearchParams();
1979
+ if (options?.offset !== void 0) params.set("offset", String(options.offset));
1980
+ if (options?.limit !== void 0) params.set("limit", String(options.limit));
1981
+ const query = params.toString();
1982
+ return this.http.request({
1983
+ method: "GET",
1984
+ path: query ? `/skills?${query}` : "/skills",
1985
+ ...signal ? { signal } : {}
1986
+ });
1987
+ }
1988
+ /**
1989
+ * Get a single skill by ID.
1990
+ * Maps to `GET /v1/skills/:id`.
1991
+ */
1992
+ getSkill(id, signal) {
1993
+ return this.http.request({
1994
+ method: "GET",
1995
+ path: `/skills/${encodeURIComponent(id)}`,
1996
+ ...signal ? { signal } : {}
1997
+ });
1998
+ }
1999
+ // ── B6.12: Task delegation ───────────────────────────────────────────────────
2000
+ /**
2001
+ * Delegate a task to another agent, setting delegatedBy and delegatedAt provenance fields.
2002
+ * Maps to `POST /v1/tasks/:id/delegate`.
2003
+ */
2004
+ delegateTask(id, input, signal) {
2005
+ return this.http.request({
2006
+ method: "POST",
2007
+ path: `/tasks/${encodeURIComponent(id)}/delegate`,
2008
+ body: input,
2009
+ ...signal ? { signal } : {}
2010
+ });
2011
+ }
2012
+ /**
2013
+ * Create a gRPC/ConnectRPC transport for typed streaming calls.
2014
+ *
2015
+ * **This is a stub.** The real implementation requires the optional peer
2016
+ * dependency `@connectrpc/connect`. Install it with:
2017
+ *
2018
+ * ```sh
2019
+ * npm install @connectrpc/connect @connectrpc/connect-web
2020
+ * ```
2021
+ *
2022
+ * Once installed, replace this stub by importing and returning
2023
+ * `createConnectTransport(...)` from `@connectrpc/connect-web`.
2024
+ *
2025
+ * @throws Error — always, until `@connectrpc/connect` is installed.
2026
+ */
2027
+ createGrpcTransport() {
2028
+ try {
2029
+ __require("@connectrpc/connect");
2030
+ } catch {
2031
+ throw new Error(
2032
+ "MnemosyneClient.createGrpcTransport: optional dependency `@connectrpc/connect` is not installed.\nInstall it with: npm install @connectrpc/connect @connectrpc/connect-web\nThen use createConnectTransport() from @connectrpc/connect-web directly."
2033
+ );
2034
+ }
2035
+ throw new Error("MnemosyneClient.createGrpcTransport: stub \u2014 install @connectrpc/connect.");
2036
+ }
2037
+ };
2038
+
2039
+ export { MnemosyneAPIError, MnemosyneClient, MnemosyneError, MnemosyneNetworkError, MnemosyneTimeoutError };
2040
+ //# sourceMappingURL=index.js.map
2041
+ //# sourceMappingURL=index.js.map