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