@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.
@@ -0,0 +1,2904 @@
1
+ /**
2
+ * Type contracts for the Mnemosyne HTTP API.
3
+ *
4
+ * These shapes mirror the zod schemas that @mnemo-ai/server validates
5
+ * incoming/outgoing payloads against. They are duplicated here (rather
6
+ * than imported as a runtime dependency) so that:
7
+ * 1. The client SDK has ZERO runtime dependencies — installing it
8
+ * doesn't pull in the entire server graph (Drizzle, pg, pgvector
9
+ * bindings, etc.).
10
+ * 2. The client can be used in browsers, Cloudflare Workers, Bun,
11
+ * Deno, etc. — environments where the server package would refuse
12
+ * to install.
13
+ *
14
+ * If you bump a server schema, update the matching type here. We rely
15
+ * on the API contract test (`packages/server/__tests__/contract.test.ts`)
16
+ * to catch drift between the two copies.
17
+ *
18
+ * For type-only sharing of richer domain types (e.g. Attribution, Kind),
19
+ * users can `import type` from @mnemo-ai/core — it's an optional peer.
20
+ */
21
+ /**
22
+ * Provenance bag attached to a fact. The server stores this as a free-form
23
+ * record (recommended fields: source, actor, message_id, timestamp), so we
24
+ * type it loosely rather than freezing a union that would drift from the
25
+ * server's `z.record(z.unknown())`.
26
+ */
27
+ type Attribution = Record<string, unknown>;
28
+ /** Sensitivity classification for a memory element. */
29
+ type Sensitivity = "public" | "internal" | "confidential" | "restricted";
30
+ /**
31
+ * The canonical fact shape returned by the API.
32
+ *
33
+ * Mirrors the server's `FactSchema` (packages/server/src/routes/facts.ts)
34
+ * exactly: bitemporal facts are never hard-deleted — `validTo` is set to
35
+ * the close time instead, so it's nullable.
36
+ */
37
+ interface Fact {
38
+ id: string;
39
+ workspaceId: string;
40
+ content: string;
41
+ attribution: Attribution;
42
+ tags: string[];
43
+ pinned: boolean;
44
+ /** ISO 8601 string — JSON has no native Date. */
45
+ validFrom: string;
46
+ /** ISO 8601 string, or null while the fact is still open. */
47
+ validTo: string | null;
48
+ /** ISO 8601 string — JSON has no native Date. */
49
+ createdAt: string;
50
+ }
51
+ /**
52
+ * Input shape for `client.recall(...)`.
53
+ *
54
+ * Mirrors the server's `POST /v1/recall` request schema EXACTLY (see
55
+ * packages/server/src/routes/recall.ts → RecallRequestSchema). The wire
56
+ * body is this object verbatim — field names must not drift or the
57
+ * server rejects with a 400.
58
+ */
59
+ interface RecallInput {
60
+ /** Free-text query — used for lexical match and (if no vector) embedding. */
61
+ query: string;
62
+ /**
63
+ * Optional pre-embedded query vector. When supplied, the server skips
64
+ * its own embedding pass and uses this directly — no LLM round-trip,
65
+ * deterministic. Useful when the caller already has the vector cached.
66
+ */
67
+ vector?: number[];
68
+ /** Max number of hits to return. Server default 10, clamps to 100. */
69
+ topK?: number;
70
+ /**
71
+ * Time-travel (bitemporal) recall. When provided, the server returns
72
+ * what memory knew at that instant — not what it knows now. ISO 8601.
73
+ */
74
+ asOf?: string;
75
+ /** B5.1 Explicit search mode: "lexical" | "semantic" | "hybrid" | "auto". */
76
+ mode?: "lexical" | "semantic" | "hybrid" | "auto";
77
+ /**
78
+ * Blend factor: 0 = pure lexical, 1 = pure vector. Server default 0.5. Deprecated in favor of mode.
79
+ */
80
+ vectorWeight?: number;
81
+ /** Filter recall to facts with this scope. */
82
+ scope?: "global" | "conversation" | "employee" | "team" | "personal";
83
+ /** Filter recall to facts with this scopeRef (e.g. 'mnemosyne', 'project:abc'). */
84
+ scopeRef?: string;
85
+ /** Filter recall to facts stored by this actorId (userId of the key owner). */
86
+ actorId?: string;
87
+ }
88
+ /**
89
+ * One hit from a recall response. Mirrors the server's `RecallHitSchema`
90
+ * (packages/server/src/routes/recall.ts) EXACTLY.
91
+ *
92
+ * `score` is the blended ranking score (higher = more relevant); it
93
+ * combines vector similarity and lexical match per `vectorWeight`. Don't
94
+ * compare scores across queries — they're only meaningful within a single
95
+ * response. `lexicalScore` / `vectorScore` expose the two un-blended
96
+ * components for debugging recall quality.
97
+ */
98
+ interface RecallHit {
99
+ id: string;
100
+ content: string;
101
+ score: number;
102
+ /** Un-blended lexical (BM25) component, when available. */
103
+ lexicalScore?: number;
104
+ /** Un-blended vector-similarity component, when available. */
105
+ vectorScore?: number;
106
+ /** Valid-time start (bitemporal). ISO 8601. */
107
+ validFrom: string;
108
+ /** Valid-time end, or null if still valid. ISO 8601. */
109
+ validTo: string | null;
110
+ attribution?: Attribution;
111
+ tags?: string[];
112
+ /** The userId of the key owner who stored this fact (P11 attribution). */
113
+ actorId?: string | null;
114
+ }
115
+ /**
116
+ * Wire response from `POST /v1/recall`. Mirrors the server's
117
+ * `RecallResponseSchema`.
118
+ */
119
+ interface RecallResponse {
120
+ hits: RecallHit[];
121
+ /** Present when the server had to embed the query (no `vector` supplied). */
122
+ debug?: {
123
+ embedded: boolean;
124
+ latencyMs?: number;
125
+ };
126
+ }
127
+ /**
128
+ * Input shape for `client.createFact(...)`.
129
+ *
130
+ * Matches the server's `CreateFactSchema` (POST /v1/facts) exactly:
131
+ * `{ content, attribution, tags }`. There is no statement/subject/kind/
132
+ * confidence on the wire — friendlier names belong to higher layers
133
+ * (e.g. the MCP `memory_remember` tool) which map onto these fields
134
+ * before calling this method.
135
+ */
136
+ interface CreateFactInput {
137
+ /** The fact content. Free-form text; keep it atomic — one claim per fact. */
138
+ content: string;
139
+ /** Provenance bag. Recommended fields: source, actor, message_id, timestamp. */
140
+ attribution?: Attribution;
141
+ /** Optional tags for filtering and rollups. Server defaults to []. */
142
+ tags?: string[];
143
+ }
144
+ /**
145
+ * Input shape for `client.remember(...)`.
146
+ *
147
+ * Calls POST /memory/remember — the cognitive engine endpoint that supports
148
+ * scope/scopeRef for project-namespaced memory.
149
+ */
150
+ interface RememberInput {
151
+ statement: string;
152
+ subject?: string;
153
+ kind?: string;
154
+ confidence?: number;
155
+ agentId?: string;
156
+ conversationId?: string;
157
+ sensitivity?: Sensitivity;
158
+ tags?: string[];
159
+ sessionId?: string;
160
+ metadata?: Record<string, unknown>;
161
+ /** Scope of the fact — default 'global'. */
162
+ scope?: "global" | "conversation" | "employee" | "team" | "personal";
163
+ /** Project/entity ref for scoped recall (e.g. 'mnemosyne', 'project:abc'). */
164
+ scopeRef?: string;
165
+ /** Ownership level: 'workspace:<id>' | 'user:<id>' | 'tenant:<id>'. Default: workspace. */
166
+ scopeOwner?: string;
167
+ /**
168
+ * Write to a different workspace than the one in the API key.
169
+ * The key's user must be a member (write/admin/owner) of the target workspace.
170
+ * Use memory_context to discover available workspace IDs.
171
+ */
172
+ targetWorkspaceId?: string;
173
+ /**
174
+ * Host-side pre-computed embedding. When supplied, the server skips its own
175
+ * LLM embed pass and stores this vector directly. Must match the workspace's
176
+ * recall embedding model (default: text-embedding-3-small, 1536 dims).
177
+ */
178
+ vector?: number[];
179
+ }
180
+ /** Response from POST /memory/remember. */
181
+ interface RememberResponse {
182
+ id: string;
183
+ workspaceId: string;
184
+ actorId?: string;
185
+ statement: string;
186
+ status: string;
187
+ [key: string]: unknown;
188
+ }
189
+ /**
190
+ * Response from `POST /v1/facts`.
191
+ *
192
+ * The server returns the freshly created `Fact` (201) — same shape as
193
+ * {@link Fact}. Aliased for call-site readability.
194
+ */
195
+ type CreateFactResponse = Fact;
196
+ /**
197
+ * Input shape for `client.timeline(...)`.
198
+ *
199
+ * Mirrors the server's `TimelineQuerySchema` (GET /v1/timeline), which
200
+ * only reads `since` + `limit`. The server does NOT support kind/status
201
+ * filters on this route, so we don't advertise no-op params.
202
+ */
203
+ interface TimelineInput {
204
+ /** Server defaults to 100, caps at 500. */
205
+ limit?: number;
206
+ /** ISO 8601 — returns events strictly after this instant. Defaults to 24h ago. */
207
+ since?: string;
208
+ }
209
+ /**
210
+ * One event from `client.timeline()`.
211
+ *
212
+ * Mirrors the server's `TimelineEventSchema`: a fact-lifecycle event
213
+ * (created / pinned / unpinned / closed / updated), NOT a fact snapshot.
214
+ */
215
+ interface TimelineEvent {
216
+ id: string;
217
+ /** ISO 8601 string — when the event happened. */
218
+ at: string;
219
+ kind: "created" | "pinned" | "unpinned" | "closed" | "updated";
220
+ factId: string;
221
+ actor?: string;
222
+ summary?: string;
223
+ /** The userId of the key owner who originally stored the underlying fact (P11 attribution). */
224
+ actorId?: string | null;
225
+ }
226
+ /** Response from `GET /v1/timeline`. */
227
+ interface TimelineResponse {
228
+ events: TimelineEvent[];
229
+ /** Opaque cursor for the next page — may be a timestamp or an id, or null. */
230
+ nextCursor: string | null;
231
+ }
232
+ /**
233
+ * Snapshot from `GET /v1/health`. Includes more than a binary "ok" so
234
+ * that operators can wire it into existing dashboards without a
235
+ * separate metrics endpoint.
236
+ */
237
+ interface HealthSnapshot {
238
+ status: "ok" | "degraded" | "down";
239
+ version: string;
240
+ /** Server-side time at response generation. ISO 8601. */
241
+ timestamp: string;
242
+ /** Optional sub-component statuses (db, embedder, queue, …). */
243
+ components?: Record<string, "ok" | "degraded" | "down">;
244
+ }
245
+ /**
246
+ * Response from `POST /v1/facts/:id/pin`.
247
+ *
248
+ * The server returns the updated `Fact` (with the new `pinned` value),
249
+ * not a minimal {id, pinned} pair — match it.
250
+ */
251
+ type PinResponse = Fact;
252
+ /**
253
+ * Result of `client.forgetFact(...)`.
254
+ *
255
+ * Forget maps to the server's soft-delete: DELETE /v1/facts/:id, which
256
+ * returns 204 No Content (empty body). There is nothing to parse, so the
257
+ * method resolves to `void`.
258
+ */
259
+ type ForgetResponse = void;
260
+ /** Retry configuration for transient failures. */
261
+ interface RetryConfig {
262
+ /** Number of attempts INCLUDING the original. Default 3. */
263
+ attempts?: number;
264
+ /** Initial backoff in ms (doubles each attempt + jitter). Default 200. */
265
+ initialDelayMs?: number;
266
+ /**
267
+ * Optional override of which errors are retryable. Default: 5xx and
268
+ * network errors retry; 4xx and timeouts do not.
269
+ */
270
+ shouldRetry?: (error: unknown, attempt: number) => boolean;
271
+ }
272
+ /**
273
+ * Input shape for `client.graph(...)`.
274
+ *
275
+ * Mirrors the server's `GraphQuerySchema` (GET /v1/graph). When `focus`
276
+ * is supplied, the server filters the returned set to that entity plus
277
+ * its 1-hop neighbours (and the edges between them). Without it, the
278
+ * full canonical workspace graph comes back.
279
+ */
280
+ interface GraphInput {
281
+ /**
282
+ * Optional entity id to centre the graph on. Must be a cuid2-shaped
283
+ * `mnemo_entity.id` (e.g. `ment_a23bcdef0123456789ghijkl`). Anything
284
+ * else is rejected with 400 by the server.
285
+ */
286
+ focus?: string;
287
+ /** Overlay precomputed semantic-neighbor edges onto the graph. */
288
+ includeSemantic?: boolean;
289
+ /**
290
+ * ISO 8601 timestamp. When supplied, returns the graph as it stood at
291
+ * that instant — nodes and relations are filtered bitemporally so only
292
+ * those that existed at `asOf` are included.
293
+ */
294
+ asOf?: string;
295
+ }
296
+ /** Input for `graphTraverse` — multi-hop BFS from a root node. */
297
+ interface GraphTraverseInput {
298
+ /** Entity/node id to start BFS traversal from. */
299
+ root: string;
300
+ /** Maximum hops (default 3, capped server-side at 5). */
301
+ maxHops?: number;
302
+ /** Restrict to these relation verbs; omit for all. */
303
+ relations?: string[];
304
+ /**
305
+ * ISO 8601 timestamp for bitemporal reconstruction — only edges live at
306
+ * this instant are followed.
307
+ */
308
+ asOf?: string;
309
+ }
310
+ /** One hit from a multi-hop traversal. */
311
+ interface TraverseHit {
312
+ /** Node id. */
313
+ id: string;
314
+ /** Minimum hop count from the root. */
315
+ hop: number;
316
+ /** decay^hop relevance score (default decay = 0.6). */
317
+ relevance: number;
318
+ }
319
+ /** Input for `graphPath` — shortest path between two nodes. */
320
+ interface GraphPathInput {
321
+ /** Source node id. */
322
+ from: string;
323
+ /** Target node id. */
324
+ to: string;
325
+ /** Maximum hops to search (default 4, capped server-side at 6). */
326
+ maxHops?: number;
327
+ /** ISO 8601 timestamp for bitemporal reconstruction. */
328
+ asOf?: string;
329
+ }
330
+ /** Response from `graphPath`. */
331
+ interface GraphPathResponse {
332
+ /** Node ids from `from` to `to` inclusive. Empty array if unreachable. */
333
+ path: string[];
334
+ /** The relation verb traversed for each consecutive pair on the path. */
335
+ edges: Array<{
336
+ source: string;
337
+ target: string;
338
+ relation: string;
339
+ }>;
340
+ }
341
+ /** One node in the Memory Graph. Mirrors `GraphNodeSchema`. */
342
+ interface GraphNode {
343
+ id: string;
344
+ kind: "entity" | "episode" | "decision";
345
+ entityKind?: "person" | "organization" | "project" | "concept" | "place" | "other";
346
+ label: string;
347
+ description?: string | null;
348
+ /** Total mentions across conversation history. Drives node radius in the UI. */
349
+ mentionCount: number;
350
+ /** Linked-fact count. Drives the aura intensity in the UI. */
351
+ factCount: number;
352
+ /**
353
+ * Average `memory_strength` across this node's facts (Hebbian
354
+ * potentiation). Higher = more salient.
355
+ */
356
+ avgMemoryStrength: number;
357
+ createdAt: string;
358
+ }
359
+ /** One edge in the Memory Graph. Mirrors `GraphEdgeSchema`. */
360
+ interface GraphEdge {
361
+ id: string;
362
+ source: string;
363
+ target: string;
364
+ /** Relation verb: related / conflicts_with / derived_from / supersedes / part_of / member_of / scoped / compatible / not_conflict. */
365
+ relation: string;
366
+ confidence: number;
367
+ /** Free-form provenance string. May be null for system-inferred edges. */
368
+ provenance: string | null;
369
+ }
370
+ /** Response from `GET /v1/graph`. Mirrors `GraphResponseSchema`. */
371
+ interface GraphResponse {
372
+ nodes: GraphNode[];
373
+ edges: GraphEdge[];
374
+ meta: {
375
+ entityCount: number;
376
+ episodeCount: number;
377
+ decisionCount: number;
378
+ relationCount: number;
379
+ };
380
+ }
381
+ /**
382
+ * The 6 entity kinds enforced by `mnemo_entity.kind` (Mnemosyne v1.6 G2).
383
+ * Mirrors the server's `EntityKindEnum`. Intentionally narrow — broader
384
+ * taxonomies (employee / vendor / customer / …) belong on the host side.
385
+ */
386
+ type EntityKind = "person" | "organization" | "project" | "concept" | "place" | "other";
387
+ /**
388
+ * Canonical entity row. Mirrors `EntitySchema` in
389
+ * `packages/server/src/routes/entities.ts`. Timestamps are ISO 8601
390
+ * strings — JSON has no native Date.
391
+ */
392
+ interface MnemoEntity {
393
+ id: string;
394
+ workspaceId: string;
395
+ name: string;
396
+ kind: EntityKind;
397
+ aliases: string[];
398
+ /** Self-reference for merge. NULL = this row is canonical. */
399
+ canonicalId: string | null;
400
+ description: string | null;
401
+ metadata: Record<string, unknown>;
402
+ firstSeenAt: string;
403
+ lastSeenAt: string;
404
+ /** Total mentions across conversation history. */
405
+ mentionCount: number;
406
+ createdAt: string;
407
+ updatedAt: string;
408
+ }
409
+ /** Input shape for `client.listEntities(...)`. */
410
+ interface ListEntitiesInput {
411
+ /** Optional kind filter. */
412
+ kind?: EntityKind;
413
+ /** Case-insensitive substring search across name + aliases. */
414
+ q?: string;
415
+ /** Max rows. Server caps at 200. */
416
+ limit?: number;
417
+ }
418
+ /** Response from `GET /v1/entities`. */
419
+ interface ListEntitiesResponse {
420
+ items: MnemoEntity[];
421
+ }
422
+ /** Response from `GET /v1/entities/:id` (entity + linked-fact count). */
423
+ interface EntityWithCount {
424
+ entity: MnemoEntity;
425
+ linkedFactCount: number;
426
+ }
427
+ /**
428
+ * Rich fact projection — what entity- and episode-detail views render.
429
+ * Distinct from the simplified {@link Fact} exposed by `GET /v1/facts/:id`:
430
+ * the rich shape carries the full cognitive fields (subject/statement/
431
+ * kind/confidence) the Inspector UI needs. Mirrors the server's
432
+ * `MemoryFactSchema`.
433
+ */
434
+ interface MemoryFact {
435
+ id: string;
436
+ workspaceId: string;
437
+ agentId: string | null;
438
+ scope: "global" | "conversation";
439
+ scopeRef: string | null;
440
+ kind: "preference" | "trait" | "event" | "relationship" | "skill" | "concern" | "other";
441
+ subject: string;
442
+ statement: string;
443
+ confidence: number;
444
+ pinned: boolean;
445
+ relevance: number;
446
+ hitCount: number;
447
+ /** ISO 8601 or null if this fact has never been recalled yet. */
448
+ lastRecalledAt: string | null;
449
+ sourceMessageIds: string[];
450
+ attributedTo: "user" | "assistant" | "system" | null;
451
+ linkedMemoryIds: string[];
452
+ metadata: Record<string, unknown>;
453
+ status: "active" | "merged" | "forgotten";
454
+ mergedIntoId: string | null;
455
+ validFrom: string;
456
+ validTo: string | null;
457
+ createdAt: string;
458
+ updatedAt: string;
459
+ /**
460
+ * v1.4 — cognitive classification. Optional because legacy rows
461
+ * predate the column; downstream consumers treat absence as 'semantic'.
462
+ */
463
+ memoryType?: "semantic" | "episodic" | "procedural" | "working";
464
+ /**
465
+ * v1.4 — per-conversation actor isolation. NULL = workspace-shared.
466
+ * Optional because legacy rows predate the column.
467
+ */
468
+ actorId?: string | null;
469
+ }
470
+ /** Response from `GET /v1/entities/:id/facts`. */
471
+ interface EntityFactsResponse {
472
+ entity: MnemoEntity;
473
+ facts: MemoryFact[];
474
+ }
475
+ /** Input shape for `client.listEntityFacts(...)`. */
476
+ interface ListEntityFactsInput {
477
+ /** Max facts. Server caps at 500. */
478
+ limit?: number;
479
+ }
480
+ /**
481
+ * Episode (Mnemosyne v1.4 timeline primitive). Mirrors `EpisodeSchema`.
482
+ * `occurredAt` is the canonical timestamp for sorting/filtering;
483
+ * `createdAt` is when the extractor (or operator) inserted the row.
484
+ */
485
+ interface MnemoEpisode {
486
+ id: string;
487
+ workspaceId: string;
488
+ title: string;
489
+ narrative: string;
490
+ occurredAt: string;
491
+ durationMinutes: number | null;
492
+ participants: string[];
493
+ topics: string[];
494
+ linkedFactIds: string[];
495
+ sourceConversationId: string | null;
496
+ metadata: Record<string, unknown>;
497
+ createdAt: string;
498
+ updatedAt: string;
499
+ /**
500
+ * v2 — true for episodes auto-created by the extraction pipeline
501
+ * (one per message turn / document / day). Inspector UI defaults to
502
+ * hiding these; recall scoring still uses them.
503
+ */
504
+ isSynthetic: boolean;
505
+ }
506
+ /** Input shape for `client.listEpisodes(...)`. */
507
+ interface ListEpisodesInput {
508
+ /** ISO 8601. Server defaults to now-30d when omitted. */
509
+ from?: string;
510
+ /** ISO 8601. Server defaults to now when omitted. */
511
+ to?: string;
512
+ /** Single-topic filter via the GIN-indexed `topics` array. */
513
+ topic?: string;
514
+ /** Max episodes. Server caps at 200. */
515
+ limit?: number;
516
+ /** Include extractor-synthesised episodes. Defaults to false. */
517
+ includeSynthetic?: boolean;
518
+ }
519
+ /** Response from `GET /v1/episodes`. */
520
+ interface ListEpisodesResponse {
521
+ items: MnemoEpisode[];
522
+ }
523
+ /** Response from `GET /v1/episodes/:id` (episode + linked facts). */
524
+ interface EpisodeWithLinkedFacts {
525
+ episode: MnemoEpisode;
526
+ linkedFacts: MemoryFact[];
527
+ }
528
+ /**
529
+ * Input shape for `client.createEntity(...)`. Mirrors the server's
530
+ * `CreateEntitySchema`. Aliases ≤ 50 × ≤ 200 chars; the server
531
+ * 400-rejects anything outside.
532
+ */
533
+ interface CreateEntityInput {
534
+ name: string;
535
+ kind: EntityKind;
536
+ aliases?: string[];
537
+ description?: string | null;
538
+ metadata?: Record<string, unknown>;
539
+ }
540
+ /**
541
+ * Input shape for `client.updateEntity(...)`. An empty patch (every
542
+ * key undefined) is rejected with 400 — bailing early beats issuing
543
+ * a no-op UPDATE that bumps `updatedAt`.
544
+ */
545
+ interface UpdateEntityInput {
546
+ name?: string;
547
+ kind?: EntityKind;
548
+ aliases?: string[];
549
+ /**
550
+ * canonicalId is the merge knob: set to another entity's id to
551
+ * mark this row as a redirect, set to null to mark it canonical
552
+ * itself. Must exist in the same workspace and must NOT equal
553
+ * the row being patched.
554
+ */
555
+ canonicalId?: string | null;
556
+ description?: string | null;
557
+ metadata?: Record<string, unknown>;
558
+ }
559
+ /**
560
+ * Why a row was queued for human review. Mirrors the server's
561
+ * `ReviewReasonEnum` (and the SQL CHECK on `mnemo_review_queue.reason`).
562
+ */
563
+ type ReviewReason = "low_confidence" | "contradiction" | "manual";
564
+ /** How the reviewer closed a queue row. */
565
+ type ReviewResolution = "kept" | "edited" | "forgotten" | "dismissed";
566
+ /**
567
+ * One row from the active-learning queue. Mirrors the server's
568
+ * `ReviewQueueRowSchema` exactly. Either `factId` or `decisionId` is
569
+ * non-null (fact-sourced vs decision-sourced row).
570
+ */
571
+ interface ReviewQueueRow {
572
+ id: string;
573
+ workspaceId: string;
574
+ factId: string | null;
575
+ decisionId: string | null;
576
+ reason: ReviewReason;
577
+ createdAt: string;
578
+ resolvedAt: string | null;
579
+ resolvedBy: string | null;
580
+ resolution: ReviewResolution | null;
581
+ }
582
+ /** Input shape for `client.listReview(...)`. */
583
+ interface ListReviewInput {
584
+ /** Filter by reason. Omit for all reasons. */
585
+ reason?: ReviewReason;
586
+ /**
587
+ * When true, include resolved rows in addition to open ones.
588
+ * Defaults to false (queue only).
589
+ */
590
+ all?: boolean;
591
+ /** Max rows. Server caps at 200. */
592
+ limit?: number;
593
+ }
594
+ /** Response from `GET /v1/review`. */
595
+ interface ListReviewResponse {
596
+ items: ReviewQueueRow[];
597
+ }
598
+ /** Response from `GET /v1/review/count`. */
599
+ interface ReviewCountResponse {
600
+ count: number;
601
+ }
602
+ /** Input shape for `client.resolveReview(...)`. */
603
+ interface ResolveReviewInput {
604
+ resolution: ReviewResolution;
605
+ }
606
+ /**
607
+ * Response from `POST /v1/review/:id/resolve`. `cascaded:true` only
608
+ * when the reviewer picked 'forgotten' AND the row was fact-sourced —
609
+ * the server atomically flips the fact's status to 'forgotten' in the
610
+ * same tx so the fact leaves the recall pool without a follow-up
611
+ * round-trip.
612
+ */
613
+ interface ResolveReviewResponse {
614
+ id: string;
615
+ resolution: ReviewResolution;
616
+ factId: string | null;
617
+ cascaded: boolean;
618
+ }
619
+ /**
620
+ * One entry in the inspector's "Undo log" feed. Mirrors the server's
621
+ * `AuditEntrySchema`. Synthesised from two sources (user-forgotten
622
+ * facts and janitor-archived facts); the discriminant is `actorKind`.
623
+ */
624
+ interface AuditEntry {
625
+ /** Prefixed key: `forget_<factId>` (live row) or `archive_<archiveId>`. */
626
+ id: string;
627
+ factId: string;
628
+ factStatement: string;
629
+ factSubject: string;
630
+ factKind: string;
631
+ /** Currently always 'forgotten' — only action synthesised today. */
632
+ action: "forgotten";
633
+ /** 'user' = clicked Forget; 'system' = janitor merge/prune. */
634
+ actorKind: "user" | "system";
635
+ actorName: string | null;
636
+ /** ISO 8601 — fact.updatedAt or archive.archivedAt. */
637
+ timestamp: string;
638
+ /** True iff `client.restoreFact()` can reverse this entry. */
639
+ revertible: boolean;
640
+ }
641
+ /** Input shape for `client.audit(...)`. */
642
+ interface AuditInput {
643
+ /** Max entries. Server caps at 100. */
644
+ limit?: number;
645
+ }
646
+ /**
647
+ * Response from `GET /v1/audit`. `available:true` is always set — when
648
+ * the underlying query fails the server returns a 5xx, not a degraded
649
+ * payload. The legacy orchester surface used `available:false` for the
650
+ * graceful-degrade UI state; the helper layers that on after the call.
651
+ */
652
+ interface AuditResponse {
653
+ items: AuditEntry[];
654
+ total: number;
655
+ available: true;
656
+ }
657
+ /**
658
+ * Response from `GET /v1/export`. `meta` describes the dump; the four
659
+ * data arrays carry raw row objects (snake_case columns from the
660
+ * underlying SELECTs). Embeddings are excluded.
661
+ */
662
+ interface ExportResponse {
663
+ meta: {
664
+ workspaceId: string;
665
+ exportedAt: string;
666
+ rowCapPerResource: number;
667
+ embeddingsExcluded: true;
668
+ };
669
+ facts: Array<Record<string, unknown>>;
670
+ decisions: Array<Record<string, unknown>>;
671
+ relations: Array<Record<string, unknown>>;
672
+ citations: Array<Record<string, unknown>>;
673
+ }
674
+ /** Response from `POST /v1/facts/:id/restore` — minimal {id, status}. */
675
+ interface RestoreFactResponse {
676
+ id: string;
677
+ status: "active";
678
+ }
679
+ /** Decision kind — mirrors the SQL CHECK on `mnemo_decision.kind`. */
680
+ type DecisionKind = "decision" | "architecture" | "policy" | "process" | "bugfix" | "learning" | "discovery" | "config";
681
+ /** Decision lifecycle status. */
682
+ type DecisionStatus = "active" | "superseded" | "withdrawn";
683
+ /**
684
+ * Decision row (Mnemosyne v1.5 — decisions as first-class memory
685
+ * primitives). Mirrors the server's `DecisionSchema`. Embedding
686
+ * vectors are NOT exposed (heavy + the client never needs them).
687
+ */
688
+ interface MnemoDecision {
689
+ id: string;
690
+ workspaceId: string;
691
+ agentId: string | null;
692
+ conversationId: string | null;
693
+ kind: DecisionKind;
694
+ title: string;
695
+ body: string;
696
+ topicKey: string | null;
697
+ revisionCount: number;
698
+ normalizedHash: string;
699
+ decidedByUserId: string | null;
700
+ status: DecisionStatus;
701
+ supersededById: string | null;
702
+ metadata: Record<string, unknown>;
703
+ validFrom: string;
704
+ validTo: string | null;
705
+ createdAt: string;
706
+ updatedAt: string;
707
+ }
708
+ /** Input shape for `client.listDecisions(...)`. */
709
+ interface ListDecisionsInput {
710
+ status?: DecisionStatus;
711
+ /** Max rows. Server caps at 500. */
712
+ limit?: number;
713
+ }
714
+ /** Response from `GET /v1/decisions`. */
715
+ interface ListDecisionsResponse {
716
+ items: MnemoDecision[];
717
+ }
718
+ /** Mirrors `mnemo_fact.kind` (SQL CHECK). */
719
+ type MemoryFactKind = "preference" | "trait" | "event" | "relationship" | "skill" | "concern" | "other";
720
+ /** Mirrors `mnemo_fact.scope`. */
721
+ type MemoryFactScope = "global" | "conversation" | "employee" | "team" | "personal";
722
+ /** Input shape for `client.listFacts(...)`. */
723
+ interface ListFactsInput {
724
+ kind?: MemoryFactKind;
725
+ scope?: MemoryFactScope;
726
+ scopeRef?: string;
727
+ /**
728
+ * `'active'` (default) returns only currently-active facts. `'merged'`
729
+ * / `'forgotten'` filter to that single status; `'all'` exposes the
730
+ * full bitemporal view.
731
+ */
732
+ status?: "active" | "forgotten" | "merged" | "all";
733
+ pinned?: boolean;
734
+ /**
735
+ * Optional full-text query. Matches `text_lemmatized` via
736
+ * `plainto_tsquery('simple', q)` server-side, with an ILIKE fallback
737
+ * on `statement` for legacy rows whose lemma column is null.
738
+ */
739
+ q?: string;
740
+ /** Defaults to `'updated_at'`. */
741
+ sortBy?: "created_at" | "updated_at" | "relevance" | "hit_count";
742
+ /** Defaults to `'desc'`. */
743
+ order?: "asc" | "desc";
744
+ /**
745
+ * Opaque base64url cursor returned by the previous page in
746
+ * `nextCursor`. Omit to start from the top.
747
+ */
748
+ cursor?: string;
749
+ /**
750
+ * ISO 8601 bitemporal snapshot. Returns facts whose
751
+ * `[validFrom, validTo)` interval contained `asOf`. Future timestamps
752
+ * are rejected (400).
753
+ */
754
+ asOf?: string;
755
+ /** Max rows. Server caps at 500. */
756
+ limit?: number;
757
+ }
758
+ /** Response from `GET /v1/facts`. */
759
+ interface ListFactsResponse {
760
+ items: MemoryFact[];
761
+ /** Non-null when more rows follow this page. */
762
+ nextCursor: string | null;
763
+ /** Cheap COUNT(*) of rows matching the filter set (without the cursor). */
764
+ total: number;
765
+ }
766
+ /** Input shape for `client.patchFact(...)`. */
767
+ interface PatchFactInput {
768
+ subject?: string;
769
+ statement?: string;
770
+ kind?: MemoryFactKind;
771
+ pinned?: boolean;
772
+ confidence?: number;
773
+ relevance?: number;
774
+ metadata?: Record<string, unknown>;
775
+ }
776
+ /** Response from `GET /v1/facts/:id/citations`. */
777
+ interface FactCitationsResponse {
778
+ factId: string;
779
+ /** Raw `source_message_ids` list — hosts join against their own message table. */
780
+ sourceMessageIds: string[];
781
+ }
782
+ /** Input shape for `client.createDecision(...)`. */
783
+ interface CreateDecisionInput {
784
+ kind: DecisionKind;
785
+ title: string;
786
+ body: string;
787
+ topicKey?: string | null;
788
+ conversationId?: string | null;
789
+ agentId?: string | null;
790
+ decidedByUserId?: string | null;
791
+ /** Project/entity scope reference — mirrors mnemo_fact.scope_ref. */
792
+ scopeRef?: string | null;
793
+ metadata?: Record<string, unknown>;
794
+ }
795
+ /** Input shape for `client.supersedeDecision(...)`. */
796
+ interface SupersedeDecisionInput {
797
+ /** Id of the new decision that supersedes this one. */
798
+ supersededById: string;
799
+ }
800
+ /** Locked vocabulary of 9 relation verbs. */
801
+ type RelationVerb = "related" | "compatible" | "scoped" | "conflicts_with" | "supersedes" | "not_conflict" | "derived_from" | "part_of" | "member_of";
802
+ /** Mirrors `mnemo_relation.judgment_status`. */
803
+ type JudgmentStatus = "pending" | "judged" | "dismissed";
804
+ /** Memory primitive a relation can connect. */
805
+ type RelationKind = "fact" | "decision" | "entity" | "episode";
806
+ /** Who marked a relation. */
807
+ type MarkerKind = "user" | "agent" | "system" | "llm_judge";
808
+ /**
809
+ * Relation row. Mirrors the server's `RelationSchema`. Provenance is
810
+ * NULL by default (LLM-derived); `'heuristic'` is reserved for system-
811
+ * synthesised edges.
812
+ */
813
+ interface MnemoRelation {
814
+ id: string;
815
+ workspaceId: string;
816
+ sourceKind: RelationKind;
817
+ sourceId: string;
818
+ targetKind: RelationKind;
819
+ targetId: string;
820
+ relation: RelationVerb;
821
+ judgmentStatus: JudgmentStatus;
822
+ reason: string | null;
823
+ evidence: Record<string, unknown> | null;
824
+ confidence: number | null;
825
+ markedByUserId: string | null;
826
+ markedByKind: MarkerKind;
827
+ markedByModel: string | null;
828
+ markedByPromptVersion: string | null;
829
+ provenance: string | null;
830
+ conversationId: string | null;
831
+ supersededByRelationId: string | null;
832
+ validFrom: string;
833
+ validTo: string | null;
834
+ createdAt: string;
835
+ updatedAt: string;
836
+ }
837
+ /** Input shape for `client.listRelations(...)`. */
838
+ interface ListRelationsInput {
839
+ judgmentStatus?: JudgmentStatus;
840
+ /** Max rows. Server caps at 500. */
841
+ limit?: number;
842
+ }
843
+ /** Response from `GET /v1/relations`. */
844
+ interface ListRelationsResponse {
845
+ items: MnemoRelation[];
846
+ }
847
+ /** Input shape for `client.createRelation(...)`. */
848
+ interface CreateRelationInput {
849
+ sourceKind: RelationKind;
850
+ sourceId: string;
851
+ targetKind: RelationKind;
852
+ targetId: string;
853
+ relation: RelationVerb;
854
+ judgmentStatus?: JudgmentStatus;
855
+ reason?: string;
856
+ evidence?: Record<string, unknown>;
857
+ confidence?: number;
858
+ markedByKind: MarkerKind;
859
+ markedByUserId?: string | null;
860
+ markedByModel?: string;
861
+ markedByPromptVersion?: string;
862
+ conversationId?: string | null;
863
+ }
864
+ /** Input shape for `client.patchRelation(...)` (judgment application). */
865
+ interface PatchRelationInput {
866
+ relation: RelationVerb;
867
+ reason?: string;
868
+ evidence?: Record<string, unknown>;
869
+ confidence?: number;
870
+ markedByKind: MarkerKind;
871
+ markedByUserId?: string | null;
872
+ markedByModel?: string;
873
+ markedByPromptVersion?: string;
874
+ }
875
+ interface TraverseRelationsInput {
876
+ rootId: string;
877
+ rootKind: RelationKind;
878
+ maxDepth?: number;
879
+ verbs?: RelationVerb[];
880
+ }
881
+ interface TraverseRelationsResponse {
882
+ nodes: Array<{
883
+ id: string;
884
+ kind: RelationKind;
885
+ }>;
886
+ edges: MnemoRelation[];
887
+ }
888
+ /** Memory primitive a citation can attach to. */
889
+ type CitationMemoryKind = "fact" | "decision" | "entity" | "episode";
890
+ /** Where the citation came from. */
891
+ type CitationSourceKind = "message" | "document" | "tool_call" | "llm_extraction" | "user_edit" | "agent_save" | "imported";
892
+ /** Citation row. Mirrors the server's `CitationSchema`. */
893
+ interface MnemoCitation {
894
+ id: string;
895
+ workspaceId: string;
896
+ memoryKind: CitationMemoryKind;
897
+ memoryId: string;
898
+ sourceKind: CitationSourceKind;
899
+ sourceId: string | null;
900
+ extractorModel: string | null;
901
+ extractorPromptVersion: string | null;
902
+ judgeModel: string | null;
903
+ judgeRelationId: string | null;
904
+ evidenceExcerpt: string | null;
905
+ createdAt: string;
906
+ }
907
+ /** Input shape for `client.listCitations(...)`. */
908
+ interface ListCitationsInput {
909
+ memoryKind?: CitationMemoryKind;
910
+ memoryId?: string;
911
+ /** Max rows. Server caps at 500. */
912
+ limit?: number;
913
+ }
914
+ /** Response from `GET /v1/citations`. */
915
+ interface ListCitationsResponse {
916
+ items: MnemoCitation[];
917
+ }
918
+ /**
919
+ * Input shape for `client.enqueueReview(...)`. Exactly one of
920
+ * `factId`/`decisionId` must be supplied — the server 400-rejects
921
+ * both-or-neither.
922
+ */
923
+ interface EnqueueReviewInput {
924
+ factId?: string;
925
+ decisionId?: string;
926
+ reason: ReviewReason;
927
+ }
928
+ /**
929
+ * Response from `POST /v1/review/enqueue`. `inserted:false` means the
930
+ * row was already open — the helper returns the existing id rather
931
+ * than creating a duplicate (idempotent via the partial index).
932
+ */
933
+ interface EnqueueReviewResponse {
934
+ id: string;
935
+ inserted: boolean;
936
+ }
937
+ /**
938
+ * Input shape for `client.createSession(...)`.
939
+ *
940
+ * Mirrors the server's `POST /v1/session/start` request body
941
+ * (StartSessionRequest in packages/server/src/routes/index.ts).
942
+ */
943
+ interface CreateSessionInput {
944
+ /** Agent identifier. Omit to use the workspace default. */
945
+ agentId?: string;
946
+ /** Human-readable label for the session, e.g. "Meeting 2026-06-13". */
947
+ label?: string;
948
+ /** Arbitrary metadata attached to the session row. */
949
+ metadata?: Record<string, unknown>;
950
+ }
951
+ /**
952
+ * Response from `POST /v1/session/start`.
953
+ *
954
+ * Mirrors the server's `V3Session` output shape.
955
+ */
956
+ interface CreateSessionResponse {
957
+ id: string;
958
+ agentId: string | null;
959
+ status: string;
960
+ createdAt: string;
961
+ }
962
+ /**
963
+ * Input shape for `client.collapseSession(...)`.
964
+ *
965
+ * Mirrors the server's `POST /v1/session/:id/collapse` request body.
966
+ */
967
+ interface CollapseSessionInput {
968
+ /**
969
+ * "auto" — let the pipeline decide collapse strategy based on turn
970
+ * recurrence signal (default). "explicit" — force full LLM extraction
971
+ * even when the recurrence signal is below the threshold.
972
+ */
973
+ strategy?: "auto" | "explicit";
974
+ /** Natural-language hint to guide LLM extraction during collapse. */
975
+ collapseHint?: string;
976
+ }
977
+ /**
978
+ * Response from `POST /v1/session/:id/collapse`.
979
+ *
980
+ * The server returns 202 Accepted — collapse runs synchronously but
981
+ * the response shape signals that the work is complete when it arrives.
982
+ */
983
+ interface CollapseSessionResponse {
984
+ accepted: boolean;
985
+ sessionId: string;
986
+ }
987
+ /**
988
+ * Input shape for `client.appendTurn(...)`.
989
+ *
990
+ * Maps to `POST /v1/session/:id/turn`. Returns 204 No Content (void).
991
+ */
992
+ interface AppendTurnInput {
993
+ /** Conversation role — typically "user" or "assistant". */
994
+ role: string;
995
+ /** Text content of the turn. */
996
+ content: string;
997
+ /** Arbitrary metadata (e.g. model name, token counts, timestamps). */
998
+ metadata?: Record<string, unknown>;
999
+ }
1000
+ /**
1001
+ * Input shape for `client.pinSessionTurn(...)`.
1002
+ *
1003
+ * Maps to `POST /v1/session/:id/pin`. Returns 204 No Content (void).
1004
+ */
1005
+ interface PinSessionTurnInput {
1006
+ /** The ID of the turn to pin or unpin. */
1007
+ turnId: string;
1008
+ /** `true` to pin the turn; `false` to unpin. */
1009
+ pinned: boolean;
1010
+ }
1011
+ /**
1012
+ * Input for `client.triggerConsolidation(...)`.
1013
+ *
1014
+ * Maps to the body of `POST /v1/consolidation/trigger`.
1015
+ */
1016
+ interface TriggerConsolidationInput {
1017
+ /**
1018
+ * `fast` (default): process a bounded low-worth candidate set.
1019
+ *
1020
+ * Manual `deep` requests currently return HTTP 422 with code
1021
+ * `deep_mode_not_supported`. The field remains public for compatibility.
1022
+ */
1023
+ mode?: "fast" | "deep";
1024
+ /**
1025
+ * Must currently be false. A true value returns HTTP 422 with code
1026
+ * `dry_run_not_supported` without running consolidation. The field remains
1027
+ * public for compatibility.
1028
+ */
1029
+ dryRun?: boolean;
1030
+ }
1031
+ /**
1032
+ * Response from `POST /v1/consolidation/trigger`.
1033
+ */
1034
+ interface TriggerConsolidationResponse {
1035
+ accepted: boolean;
1036
+ workspaceId: string;
1037
+ mode: "fast";
1038
+ dryRun: false;
1039
+ /** Gate-passed pairs merged this tick. */
1040
+ mergedPairs: number;
1041
+ /** Gate-failed or ineligible pairs skipped. */
1042
+ skippedPairs: number;
1043
+ /** Total candidate facts fetched and inspected. */
1044
+ candidatesProcessed: number;
1045
+ /** Number of non-fatal per-fact errors encountered. */
1046
+ errors: number;
1047
+ /** Wall-clock time the server spent on the pass (milliseconds). */
1048
+ tookMs: number;
1049
+ }
1050
+ interface TaskWire {
1051
+ id: string;
1052
+ workspaceId: string;
1053
+ title: string;
1054
+ description?: string;
1055
+ status: "pending" | "in_progress" | "blocked" | "delegated" | "completed" | "cancelled";
1056
+ priority: "critical" | "high" | "medium" | "low";
1057
+ assignedTo: string;
1058
+ delegatedBy?: string;
1059
+ parentTaskId?: string;
1060
+ blockedBy: string[];
1061
+ subtaskIds: string[];
1062
+ relatedFacts: string[];
1063
+ relatedEntities: string[];
1064
+ sessionId?: string;
1065
+ outcome?: string;
1066
+ lessonsLearned?: string;
1067
+ delegatedAt?: string;
1068
+ startedAt?: string;
1069
+ completedAt?: string;
1070
+ dueAt?: string;
1071
+ createdAt: string;
1072
+ updatedAt: string;
1073
+ metadata: Record<string, unknown>;
1074
+ }
1075
+ interface PaginatedTasksResponse {
1076
+ items: TaskWire[];
1077
+ total: number;
1078
+ offset: number;
1079
+ limit: number;
1080
+ hasMore: boolean;
1081
+ }
1082
+ interface EventAnnotationWire {
1083
+ author: string;
1084
+ content: string;
1085
+ at: string;
1086
+ }
1087
+ interface EventWire {
1088
+ id: string;
1089
+ workspaceId: string;
1090
+ type: "system" | "external" | "user" | "agent" | "scheduled";
1091
+ name: string;
1092
+ description: string;
1093
+ occurredAt: string;
1094
+ durationS?: number;
1095
+ source: string;
1096
+ relatedEntities: string[];
1097
+ annotations: EventAnnotationWire[];
1098
+ createdAt: string;
1099
+ metadata: Record<string, unknown>;
1100
+ }
1101
+ interface PaginatedEventsResponse {
1102
+ items: EventWire[];
1103
+ total: number;
1104
+ offset: number;
1105
+ limit: number;
1106
+ hasMore: boolean;
1107
+ }
1108
+ interface ChainStepWire {
1109
+ step: number;
1110
+ reasoning: string;
1111
+ conclusion?: string;
1112
+ }
1113
+ interface ReasoningWire {
1114
+ id: string;
1115
+ workspaceId: string;
1116
+ agentId?: string;
1117
+ question: string;
1118
+ chain: ChainStepWire[];
1119
+ conclusion: string;
1120
+ successCount: number;
1121
+ failureCount: number;
1122
+ worth: number;
1123
+ topicKey?: string;
1124
+ status: "active" | "archived" | "pruned";
1125
+ lastUsedAt?: string;
1126
+ usageCount: number;
1127
+ createdAt: string;
1128
+ updatedAt: string;
1129
+ metadata: Record<string, unknown>;
1130
+ }
1131
+ interface PaginatedReasoningResponse {
1132
+ items: ReasoningWire[];
1133
+ total: number;
1134
+ offset: number;
1135
+ limit: number;
1136
+ hasMore: boolean;
1137
+ }
1138
+ interface CreateTaskInput {
1139
+ title: string;
1140
+ description?: string;
1141
+ priority?: "critical" | "high" | "medium" | "low";
1142
+ assignedTo: string;
1143
+ sessionId?: string;
1144
+ parentTaskId?: string;
1145
+ dueAt?: string;
1146
+ metadata?: Record<string, unknown>;
1147
+ }
1148
+ interface PatchTaskInput {
1149
+ title?: string;
1150
+ description?: string;
1151
+ status?: "pending" | "in_progress" | "blocked" | "delegated" | "completed" | "cancelled";
1152
+ priority?: "critical" | "high" | "medium" | "low";
1153
+ assignedTo?: string;
1154
+ blockedBy?: string[];
1155
+ subtaskIds?: string[];
1156
+ outcome?: string;
1157
+ lessonsLearned?: string;
1158
+ startedAt?: string;
1159
+ completedAt?: string;
1160
+ dueAt?: string;
1161
+ metadata?: Record<string, unknown>;
1162
+ }
1163
+ interface CreateEventInput {
1164
+ type: "system" | "external" | "user" | "agent" | "scheduled";
1165
+ name: string;
1166
+ description: string;
1167
+ occurredAt: string;
1168
+ durationS?: number;
1169
+ source: string;
1170
+ relatedEntities?: string[];
1171
+ annotations?: {
1172
+ author: string;
1173
+ content: string;
1174
+ at: string;
1175
+ }[];
1176
+ metadata?: Record<string, unknown>;
1177
+ }
1178
+ interface CreateReasoningInput {
1179
+ question: string;
1180
+ chain: ChainStepWire[];
1181
+ conclusion: string;
1182
+ agentId?: string;
1183
+ topicKey?: string;
1184
+ metadata?: Record<string, unknown>;
1185
+ }
1186
+ interface PatchReasoningInput {
1187
+ status?: "active" | "archived" | "pruned";
1188
+ chain?: ChainStepWire[];
1189
+ conclusion?: string;
1190
+ metadata?: Record<string, unknown>;
1191
+ }
1192
+ interface ResolveReasoningInput {
1193
+ query: string;
1194
+ topicKey?: string;
1195
+ }
1196
+ interface ResolveReasoningResponse {
1197
+ action: "hit" | "execute";
1198
+ reasoning_id?: string;
1199
+ cached_cot?: ChainStepWire[];
1200
+ conclusion?: string;
1201
+ suggested_model?: "haiku";
1202
+ similar_attempts?: Array<{
1203
+ reasoning_id: string;
1204
+ cosine: number;
1205
+ }>;
1206
+ }
1207
+ interface RecordReasoningInput {
1208
+ agentId?: string;
1209
+ question: string;
1210
+ chain: ChainStepWire[];
1211
+ conclusion: string;
1212
+ topicKey?: string;
1213
+ outcome?: "success" | "fail";
1214
+ metadata?: Record<string, unknown>;
1215
+ }
1216
+ interface ReasoningFeedbackInput {
1217
+ reasoning_id: string;
1218
+ outcome: "success" | "fail";
1219
+ }
1220
+ interface ListTasksParams {
1221
+ status?: "pending" | "in_progress" | "blocked" | "delegated" | "completed" | "cancelled";
1222
+ assignedTo?: string;
1223
+ parentTaskId?: string;
1224
+ limit?: number;
1225
+ offset?: number;
1226
+ }
1227
+ interface ListEventsParams {
1228
+ type?: "system" | "external" | "user" | "agent" | "scheduled";
1229
+ source?: string;
1230
+ after?: string;
1231
+ before?: string;
1232
+ limit?: number;
1233
+ offset?: number;
1234
+ }
1235
+ interface ListReasoningParams {
1236
+ status?: "active" | "archived" | "pruned";
1237
+ topicKey?: string;
1238
+ limit?: number;
1239
+ offset?: number;
1240
+ }
1241
+ interface StrategyWire {
1242
+ id: string;
1243
+ workspaceId: string;
1244
+ agentId?: string;
1245
+ trigger: string;
1246
+ action: string;
1247
+ context?: string;
1248
+ successCount: number;
1249
+ failureCount: number;
1250
+ worth: number;
1251
+ supersedesId?: string;
1252
+ status: "active" | "superseded" | "archived";
1253
+ embeddingStale: boolean;
1254
+ validFrom: string;
1255
+ validTo?: string;
1256
+ createdAt: string;
1257
+ updatedAt: string;
1258
+ metadata: Record<string, unknown>;
1259
+ }
1260
+ interface PaginatedStrategiesResponse {
1261
+ items: StrategyWire[];
1262
+ total: number;
1263
+ offset: number;
1264
+ limit: number;
1265
+ hasMore: boolean;
1266
+ }
1267
+ interface CreateStrategyInput {
1268
+ agentId?: string;
1269
+ trigger: string;
1270
+ action: string;
1271
+ context?: string;
1272
+ /** Project/entity scope reference — mirrors mnemo_fact.scope_ref. */
1273
+ scopeRef?: string;
1274
+ supersedesId?: string;
1275
+ validFrom?: string;
1276
+ metadata?: Record<string, unknown>;
1277
+ }
1278
+ interface PatchStrategyInput {
1279
+ trigger?: string;
1280
+ action?: string;
1281
+ context?: string;
1282
+ status?: "active" | "superseded" | "archived";
1283
+ validTo?: string;
1284
+ metadata?: Record<string, unknown>;
1285
+ }
1286
+ interface ListStrategiesParams {
1287
+ status?: "active" | "superseded" | "archived";
1288
+ /** When set, return records with scope_ref = X OR scope_ref IS NULL. */
1289
+ scopeRef?: string;
1290
+ validAt?: string;
1291
+ offset?: number;
1292
+ limit?: number;
1293
+ }
1294
+ interface HyperedgeWire {
1295
+ id: string;
1296
+ workspaceId: string;
1297
+ memberIds: string[];
1298
+ label?: string;
1299
+ description?: string;
1300
+ contextQuery?: string;
1301
+ activationCount: number;
1302
+ worth: number;
1303
+ validFrom: string;
1304
+ validTo: string | null;
1305
+ createdAt: string;
1306
+ }
1307
+ interface PaginatedHyperedgesResponse {
1308
+ items: HyperedgeWire[];
1309
+ total: number;
1310
+ offset: number;
1311
+ limit: number;
1312
+ hasMore: boolean;
1313
+ }
1314
+ interface CreateHyperedgeInput {
1315
+ memberIds: string[];
1316
+ label?: string;
1317
+ description?: string;
1318
+ contextQuery?: string;
1319
+ }
1320
+ interface PatchHyperedgeInput {
1321
+ label?: string;
1322
+ description?: string;
1323
+ contextQuery?: string;
1324
+ }
1325
+ interface ListHyperedgesParams {
1326
+ memberId?: string;
1327
+ label?: string;
1328
+ limit?: number;
1329
+ offset?: number;
1330
+ }
1331
+ /** Configuration record for one remote Mnemosyne peer. */
1332
+ interface PeerConfig {
1333
+ id: string;
1334
+ url: string;
1335
+ /** Friendly display name. */
1336
+ name?: string;
1337
+ /** DER-encoded certificate for mTLS, base64url. */
1338
+ certDer?: string;
1339
+ /** ISO 8601 — when the peer was approved. */
1340
+ approvedAt?: string | null;
1341
+ status: "pending" | "approved" | "rejected";
1342
+ createdAt: string;
1343
+ }
1344
+ /** Response from `GET /v1/memory/federation/peers`. */
1345
+ interface ListPeersResponse {
1346
+ peers: PeerConfig[];
1347
+ }
1348
+ /** Response from `GET /v1/memory/federation/peers/pending`. */
1349
+ interface ListPendingPeersResponse {
1350
+ peers: PeerConfig[];
1351
+ discovery: {
1352
+ enabled: boolean;
1353
+ reason?: string;
1354
+ };
1355
+ }
1356
+ /** Body for `POST /v1/memory/federation/peers/:id/approve` and `/approve-key`. */
1357
+ interface ApprovePeerInput {
1358
+ /** DER-encoded new certificate, base64. */
1359
+ newCertDer: string;
1360
+ /** ISO 8601. Defaults to server time if omitted. */
1361
+ issuedAt?: string;
1362
+ }
1363
+ /** Response from `POST /v1/memory/federation/peers/:id/approve-key`. */
1364
+ interface ApprovePeerKeyResponse {
1365
+ approved: boolean;
1366
+ peerId: string;
1367
+ approvedAt: string;
1368
+ }
1369
+ /** Response from `DELETE /v1/memory/federation/peers/:id`. */
1370
+ interface DeletePeerResponse {
1371
+ deleted: true;
1372
+ peerId: string;
1373
+ }
1374
+ /** One item in a federation sync feed. */
1375
+ interface FederationItem {
1376
+ id: string;
1377
+ workspaceId: string;
1378
+ content: string;
1379
+ kind: string;
1380
+ version: number;
1381
+ /** ISO 8601 */
1382
+ updatedAt: string;
1383
+ attribution?: Record<string, unknown>;
1384
+ }
1385
+ /** Response from `GET /v1/memory/federation/items`. */
1386
+ interface ListFederationItemsResponse {
1387
+ items: FederationItem[];
1388
+ nextCursor: string | null;
1389
+ }
1390
+ /** Body for `POST /v1/memory/federation/sync`. */
1391
+ interface TriggerFederationSyncInput {
1392
+ peerId: string;
1393
+ }
1394
+ /** Response from `POST /v1/memory/federation/sync` (202 Accepted). */
1395
+ interface TriggerFederationSyncResponse {
1396
+ jobId: string;
1397
+ status: "pending";
1398
+ }
1399
+ /** One federation sync job record. */
1400
+ interface FederationSyncJob {
1401
+ jobId: string;
1402
+ peerId: string;
1403
+ status: "pending" | "running" | "completed" | "failed";
1404
+ startedAt?: string | null;
1405
+ completedAt?: string | null;
1406
+ error?: string | null;
1407
+ itemsProcessed?: number;
1408
+ }
1409
+ /** One conflict claim for `POST /v1/memory/federation/resolve`. */
1410
+ interface FederationClaim {
1411
+ id: string;
1412
+ content: string;
1413
+ version: number;
1414
+ attribution?: Record<string, unknown>;
1415
+ worth?: number;
1416
+ }
1417
+ /** Body for `POST /v1/memory/federation/resolve` — two-item shorthand. */
1418
+ interface ResolveFederationConflictPairInput {
1419
+ itemA: FederationClaim;
1420
+ itemB: FederationClaim;
1421
+ }
1422
+ /** Body for `POST /v1/memory/federation/resolve` — batch form. */
1423
+ interface ResolveFederationConflictBatchInput {
1424
+ items: FederationClaim[];
1425
+ }
1426
+ /** Response from `POST /v1/memory/federation/resolve`. */
1427
+ interface ResolveFederationConflictResponse {
1428
+ /** Present when a clear winner was determined. */
1429
+ winner?: FederationClaim;
1430
+ /** Present when a clear loser was determined. */
1431
+ loser?: FederationClaim;
1432
+ /** When batch form resolves to a single outcome. */
1433
+ outcome?: FederationClaim;
1434
+ strategy: string;
1435
+ /** ISO 8601 */
1436
+ resolvedAt: string;
1437
+ }
1438
+ /** One anticipated memory from the Anticipation Engine (§30). */
1439
+ interface AnticipatedMemory {
1440
+ factId: string;
1441
+ score: number;
1442
+ source: "sequential" | "periodic" | "conditional" | "co-occurrence" | "blended";
1443
+ confidence: number;
1444
+ /** Optional short explanation for why this memory was surfaced. */
1445
+ reason?: string;
1446
+ }
1447
+ /** Response from `GET /v1/anticipation`. */
1448
+ interface AnticipationFeedResponse {
1449
+ items: AnticipatedMemory[];
1450
+ generatedAt: string;
1451
+ }
1452
+ /** One composition rule in the workspace. */
1453
+ interface CompositionRule {
1454
+ id: string;
1455
+ workspaceId: string;
1456
+ name: string;
1457
+ description?: string | null;
1458
+ conditionDsl: unknown;
1459
+ actionDsl: unknown;
1460
+ priority: number;
1461
+ isActive: boolean;
1462
+ source: "manual" | "mined" | "imported";
1463
+ executionCount: number;
1464
+ metadata: Record<string, unknown>;
1465
+ createdAt: string;
1466
+ updatedAt: string;
1467
+ }
1468
+ /** Paginated list of composition rules. */
1469
+ interface ListCompositionRulesResponse {
1470
+ items: CompositionRule[];
1471
+ total: number;
1472
+ offset: number;
1473
+ limit: number;
1474
+ }
1475
+ /** One derived inference from the dry-run endpoint. */
1476
+ interface DerivedInference {
1477
+ type: "fact" | "warning";
1478
+ statement: string;
1479
+ confidence: number;
1480
+ ruleId: string;
1481
+ ruleName: string;
1482
+ hop: number;
1483
+ premises: string[];
1484
+ }
1485
+ /** Response from `POST /v1/composition/dry-run`. */
1486
+ interface CompositionDryRunResponse {
1487
+ fired: number;
1488
+ inferences: DerivedInference[];
1489
+ conflicts: Array<{
1490
+ winner: DerivedInference;
1491
+ dropped: DerivedInference[];
1492
+ }>;
1493
+ }
1494
+ type SelfEditAction = "append" | "replace" | "strengthen" | "weaken" | "forget" | "reflect" | "link";
1495
+ type SelfEditTargetKind = "fact" | "strategy" | "profile";
1496
+ interface AppliedSelfEditBase {
1497
+ applied: true;
1498
+ target: string;
1499
+ targetKind: SelfEditTargetKind;
1500
+ countsAsEdit: boolean;
1501
+ countsAsDelete: boolean;
1502
+ }
1503
+ interface AppliedFactReplaceResponse extends AppliedSelfEditBase {
1504
+ action: "replace";
1505
+ targetKind: "fact";
1506
+ replacementId: string;
1507
+ }
1508
+ interface AppliedNonFactReplaceResponse extends AppliedSelfEditBase {
1509
+ action: "replace";
1510
+ targetKind: "strategy" | "profile";
1511
+ replacementId?: never;
1512
+ }
1513
+ interface AppliedNonReplaceResponse extends AppliedSelfEditBase {
1514
+ action: Exclude<SelfEditAction, "replace" | "reflect">;
1515
+ replacementId?: never;
1516
+ }
1517
+ interface SelfEditApprovalResponse {
1518
+ applied: false;
1519
+ action: SelfEditAction;
1520
+ target: string;
1521
+ targetKind: SelfEditTargetKind;
1522
+ approvalRequired: true;
1523
+ scope: "delete_fact" | "edit_entity";
1524
+ reason: string;
1525
+ replacementId?: never;
1526
+ }
1527
+ interface SelfEditReflectionResponse {
1528
+ applied: true;
1529
+ action: "reflect";
1530
+ episode_id: string;
1531
+ strengthened: string[];
1532
+ weakened: string[];
1533
+ replacementId?: never;
1534
+ }
1535
+ /** Discriminated response from `POST /v1/self/edit`. */
1536
+ type SelfEditResponse = AppliedFactReplaceResponse | AppliedNonFactReplaceResponse | AppliedNonReplaceResponse | SelfEditApprovalResponse | SelfEditReflectionResponse;
1537
+ /**
1538
+ * Options for `client.subscribe(channel, handler, opts?)`.
1539
+ *
1540
+ * Internally the SDK opens a WebSocket to `ws[s]://…/v1/memory/ws?token=<apiKey>`.
1541
+ * Requires the runtime to support `WebSocket` (Node ≥ 22 ships a native global;
1542
+ * older environments must polyfill with e.g. `ws`).
1543
+ */
1544
+ interface SubscribeOptions {
1545
+ /** Optional entity/agent/memoryType filter forwarded to the server. */
1546
+ filter?: {
1547
+ entityId?: string;
1548
+ agentId?: string;
1549
+ memoryType?: string;
1550
+ };
1551
+ /**
1552
+ * Called when the WS disconnects. Return `true` to attempt a reconnect
1553
+ * (the SDK will NOT reconnect automatically by default).
1554
+ */
1555
+ onDisconnect?: (reason: string) => boolean | undefined;
1556
+ /** Optional WebSocket constructor — inject for Node < 22 or testing. */
1557
+ WebSocketImpl?: typeof WebSocket;
1558
+ }
1559
+ /** Handle returned by `client.subscribe(...)`. */
1560
+ interface SubscribeHandle {
1561
+ /** Close the WebSocket subscription. */
1562
+ close(): void;
1563
+ /** True while the socket is open. */
1564
+ readonly connected: boolean;
1565
+ }
1566
+ type SelfModelAspect = "coverage" | "trends" | "gaps" | "strengths" | "all";
1567
+ interface SelfModelResponse {
1568
+ workspaceId: string;
1569
+ generatedAt: string;
1570
+ strongTopics: Array<{
1571
+ topicKey: string;
1572
+ memoryCount: number;
1573
+ avgWorth: number;
1574
+ evidenceVolume: number;
1575
+ }>;
1576
+ gaps: Array<{
1577
+ topicKey: string;
1578
+ gapScore: number;
1579
+ recallHits30d: number;
1580
+ avgWorth: number;
1581
+ memoryCount: number;
1582
+ }>;
1583
+ summary: {
1584
+ totalTopics: number;
1585
+ strongTopicsCount: number;
1586
+ gapsCount: number;
1587
+ avgWorthAcrossWorkspace: number;
1588
+ };
1589
+ }
1590
+ /**
1591
+ * Status for a single diagnostic check.
1592
+ * `"ok"` — check passed. `"warn"` — check returned a warning. `"error"` — check
1593
+ * failed. `"unknown"` — check could not determine its own result (e.g. permission
1594
+ * denied before the query ran).
1595
+ */
1596
+ type DoctorCheckStatus = "ok" | "warn" | "error" | "unknown";
1597
+ /**
1598
+ * One diagnostic check result in a `DoctorReport`.
1599
+ */
1600
+ interface DoctorCheck {
1601
+ /** Stable machine-readable check identifier (e.g. "connectivity", "app_user_grants"). */
1602
+ name: string;
1603
+ /** Check outcome. */
1604
+ status: DoctorCheckStatus;
1605
+ /** Human-readable explanation of the outcome. */
1606
+ message: string;
1607
+ /** Optional numeric / structured detail (e.g. backlog count, migration filename). */
1608
+ detail?: Record<string, unknown>;
1609
+ }
1610
+ /**
1611
+ * Full operational diagnostic report returned by `GET /v1/doctor` and the
1612
+ * `memory_doctor` MCP tool.
1613
+ *
1614
+ * `status` is the worst-of all checks: if any check is `"error"` the overall
1615
+ * status is `"error"`; if any is `"warn"` (and none are `"error"`) the overall
1616
+ * status is `"warn"`; otherwise `"ok"`.
1617
+ */
1618
+ interface DoctorReport {
1619
+ /** Worst-of status across all checks. */
1620
+ status: DoctorCheckStatus;
1621
+ /** Individual check results. */
1622
+ checks: DoctorCheck[];
1623
+ /** ISO 8601 timestamp of report generation. */
1624
+ timestamp: string;
1625
+ }
1626
+ /**
1627
+ * Condensed fact summary inside a conflict pair.
1628
+ * Mirrors `ConflictFact` from `packages/server/src/routes/conflicts.ts`.
1629
+ */
1630
+ interface ConflictFact {
1631
+ id: string;
1632
+ subject: string;
1633
+ statement: string;
1634
+ worth: number;
1635
+ validFrom: string;
1636
+ validTo: string | null;
1637
+ }
1638
+ /**
1639
+ * One unresolved conflict pair — two facts linked by a `conflicts_with`
1640
+ * relation, surfaced for interactive LLM judgment.
1641
+ */
1642
+ interface ConflictPair {
1643
+ relationId: string;
1644
+ confidence: number | null;
1645
+ factA: ConflictFact;
1646
+ factB: ConflictFact;
1647
+ }
1648
+ /** Response from `GET /v1/conflicts`. */
1649
+ interface ListConflictsResponse {
1650
+ pairs: ConflictPair[];
1651
+ }
1652
+ /** Input to `POST /v1/conflicts/:id/resolve`. */
1653
+ interface ResolveConflictInput {
1654
+ /** How to resolve the conflict. */
1655
+ action: "supersede_a" | "supersede_b" | "keep_both" | "merge";
1656
+ /**
1657
+ * Required when `action='merge'`. The statement for the new merged fact
1658
+ * that replaces both conflicting facts.
1659
+ */
1660
+ mergedStatement?: string;
1661
+ }
1662
+ /** Response from `POST /v1/conflicts/:id/resolve`. */
1663
+ interface ResolveConflictResponse {
1664
+ resolved: boolean;
1665
+ action: "supersede_a" | "supersede_b" | "keep_both" | "merge";
1666
+ relationId: string;
1667
+ /** ID of the newly created merged fact; null unless action='merge'. */
1668
+ mergedFactId: string | null;
1669
+ }
1670
+ /**
1671
+ * Aggregate workspace statistics returned by `GET /v1/admin/stats` and the
1672
+ * `memory_stats` MCP tool.
1673
+ *
1674
+ * Mirrors the `AdminStatsSchema` from `packages/server/src/routes/admin.ts`.
1675
+ */
1676
+ interface AdminStats {
1677
+ workspaceId: string;
1678
+ /** ISO 8601 timestamp of when the stats snapshot was generated. */
1679
+ generatedAt: string;
1680
+ facts: {
1681
+ /** Active facts with an open validity interval (validTo IS NULL). */
1682
+ live: number;
1683
+ /** Facts whose validity was closed by a `forget()` call. */
1684
+ closed: number;
1685
+ /** Facts with `pinned = true`. */
1686
+ pinned: number;
1687
+ /** Facts archived by the janitor. */
1688
+ archived: number;
1689
+ /** Active facts that have never been recalled (hit_count = 0). */
1690
+ withZeroHits: number;
1691
+ /** Live fact counts per scopeRef. Only entries with a non-null scopeRef. */
1692
+ byScopeRef: Array<{
1693
+ scopeRef: string;
1694
+ count: number;
1695
+ }>;
1696
+ };
1697
+ decisions: {
1698
+ /** Decisions with status = 'active'. */
1699
+ active: number;
1700
+ };
1701
+ relations: {
1702
+ /** Relations with verb = 'conflicts_with'. */
1703
+ conflicts: number;
1704
+ };
1705
+ embeddings: {
1706
+ /** Facts with an up-to-date embedding vector. */
1707
+ indexed: number;
1708
+ /** Facts awaiting embedding. */
1709
+ pending: number;
1710
+ };
1711
+ recall: {
1712
+ /** 30-day recall hit rate (0–1), or null if no recall data yet. */
1713
+ hitRate30d: number | null;
1714
+ /** ISO 8601 timestamp of the last recall query, or null. */
1715
+ lastRecallAt: string | null;
1716
+ };
1717
+ /** ISO 8601 timestamp of the last write to the workspace, or null. */
1718
+ lastWriteAt: string | null;
1719
+ }
1720
+ /**
1721
+ * Response from `DELETE /v1/facts/:id/hard`.
1722
+ * Hard-deletes a single fact by ID (requires `memory:hard_delete` scope).
1723
+ */
1724
+ interface PurgeFactResponse {
1725
+ deleted: true;
1726
+ }
1727
+ /**
1728
+ * Response from `DELETE /v1/facts/purge`.
1729
+ * Bulk-deletes all closed (forgotten) facts in the workspace.
1730
+ * Requires `memory:hard_delete` scope.
1731
+ */
1732
+ interface PurgeClosedFactsResponse {
1733
+ deleted: number;
1734
+ }
1735
+ /** Metadata for an API key in the list response. */
1736
+ interface KeyListItem {
1737
+ id: string;
1738
+ label: string;
1739
+ prefix: string;
1740
+ scopes: string[];
1741
+ plan: string;
1742
+ ipAllowlist: string[];
1743
+ expiresAt: string | null;
1744
+ createdAt: string;
1745
+ lastUsedAt: string | null;
1746
+ revokedAt: string | null;
1747
+ maxSensitivity?: string | null;
1748
+ }
1749
+ /** Input payload for creating a new API key. */
1750
+ interface CreateKeyInput {
1751
+ label: string;
1752
+ scopes: string[];
1753
+ expiresIn?: string;
1754
+ ipAllowlist?: string[];
1755
+ plan?: "free" | "pro" | "enterprise";
1756
+ test?: boolean;
1757
+ maxSensitivity?: Sensitivity;
1758
+ }
1759
+ /** Response from API key creation — plaintext key is shown ONCE. */
1760
+ interface CreateKeyResponse {
1761
+ id: string;
1762
+ key: string;
1763
+ label: string;
1764
+ scopes: string[];
1765
+ plan: string;
1766
+ expiresAt: string | null;
1767
+ createdAt: string;
1768
+ maxSensitivity?: string | null;
1769
+ }
1770
+ /** Metadata for a single API key detail response. */
1771
+ interface KeyDetailResponse {
1772
+ id: string;
1773
+ label: string;
1774
+ scopes: string[];
1775
+ ipAllowlist: string[];
1776
+ expiresAt: string | null;
1777
+ lastUsedAt: string | null;
1778
+ revokedAt: string | null;
1779
+ deprecatedAt: string | null;
1780
+ rotatedFromId: string | null;
1781
+ createdAt: string;
1782
+ maxSensitivity?: string | null;
1783
+ }
1784
+ /** Response from key rotation. */
1785
+ interface RotateKeyResponse {
1786
+ newKey: string;
1787
+ newKeyId: string;
1788
+ oldKeySunsetAt: string;
1789
+ }
1790
+ /** Wire representation of an agent Skill (stored prompt template). */
1791
+ interface SkillWire {
1792
+ id: string;
1793
+ workspaceId: string;
1794
+ name: string;
1795
+ promptTemplate: string;
1796
+ variables: string[];
1797
+ requiredContext: string[];
1798
+ qualityScore: number;
1799
+ usageCount: number;
1800
+ lastUsedAt?: string;
1801
+ embeddingModel?: string;
1802
+ embeddingStale: boolean;
1803
+ sensitivity: Sensitivity;
1804
+ createdAt: string;
1805
+ updatedAt: string;
1806
+ metadata: Record<string, unknown>;
1807
+ }
1808
+ /** Input payload for creating a skill. */
1809
+ interface CreateSkillClientInput {
1810
+ name: string;
1811
+ promptTemplate: string;
1812
+ variables?: string[];
1813
+ requiredContext?: string[];
1814
+ sensitivity?: Sensitivity;
1815
+ metadata?: Record<string, unknown>;
1816
+ }
1817
+ /** Paginated list response for skills. */
1818
+ interface SkillListResponse {
1819
+ items: SkillWire[];
1820
+ total: number;
1821
+ offset: number;
1822
+ limit: number;
1823
+ hasMore: boolean;
1824
+ }
1825
+ /** Constructor options for `MnemosyneClient`. */
1826
+ interface MnemosyneClientOptions {
1827
+ /** Base URL of the Mnemosyne HTTP server, e.g. `https://memory.example.com`. */
1828
+ url: string;
1829
+ /** API key minted in the Mnemosyne control plane. Scoped to a workspace. */
1830
+ apiKey: string;
1831
+ /** Optional fetch implementation. Defaults to the global `fetch`. */
1832
+ fetch?: typeof fetch;
1833
+ /** Request timeout in milliseconds. Default 30_000. */
1834
+ timeout?: number;
1835
+ /** Retry policy. Default: 3 attempts, exponential backoff with jitter. */
1836
+ retry?: RetryConfig;
1837
+ /**
1838
+ * Optional User-Agent suffix. Useful for operators to distinguish
1839
+ * traffic from different consumer apps in their logs.
1840
+ */
1841
+ userAgent?: string;
1842
+ }
1843
+
1844
+ /**
1845
+ * Typed SDK for the Mnemosyne HTTP API.
1846
+ *
1847
+ * Designed as a drop-in alternative to importing `@mnemo-ai/core`
1848
+ * directly. Pick this when:
1849
+ * - You want to talk to a centralized memory server from many apps
1850
+ * (microservices, edge functions, CLI tools).
1851
+ * - You can't (or don't want to) install the core package and its
1852
+ * Drizzle / pg / pgvector graph in your runtime.
1853
+ * - You need a stable wire contract that survives memory-engine
1854
+ * internal refactors.
1855
+ *
1856
+ * Pick `@mnemo-ai/core` directly when:
1857
+ * - You want sub-millisecond in-process recall.
1858
+ * - You're already running a Postgres connection pool you'd rather
1859
+ * reuse than proxy through HTTP.
1860
+ *
1861
+ * @example
1862
+ * ```ts
1863
+ * import { MnemosyneClient } from "@mnemo-ai/client-ts";
1864
+ *
1865
+ * const memory = new MnemosyneClient({
1866
+ * url: "https://memory.example.com",
1867
+ * apiKey: process.env.MNEMOSYNE_API_KEY!,
1868
+ * });
1869
+ *
1870
+ * const { hits } = await memory.recall({ query: "user email preferences" });
1871
+ * ```
1872
+ */
1873
+ declare class MnemosyneClient {
1874
+ private readonly http;
1875
+ constructor(options: MnemosyneClientOptions);
1876
+ /**
1877
+ * Recall facts relevant to a query.
1878
+ *
1879
+ * The server returns top-K hits ranked by a blended score (vector
1880
+ * similarity + lexical match + recency + pin boost). Don't compare
1881
+ * scores across queries — they're only meaningful within a response.
1882
+ *
1883
+ * Trade-off: we accept an optional pre-embedded `embedding` so the
1884
+ * caller can BYO embedder. Most callers should omit it and let the
1885
+ * server handle embedding — that's what keeps recall behavior
1886
+ * consistent across consumer apps.
1887
+ */
1888
+ recall(input: RecallInput, signal?: AbortSignal): Promise<RecallResponse>;
1889
+ /**
1890
+ * Store a fact via the cognitive engine endpoint (POST /remember).
1891
+ * Supports scope/scopeRef for project-namespaced memory — use this instead
1892
+ * of createFact when you need to isolate facts by project or context.
1893
+ */
1894
+ remember(input: RememberInput, signal?: AbortSignal, idempotencyKey?: string): Promise<RememberResponse>;
1895
+ /**
1896
+ * Persist a new fact. Idempotent via content-hash on the server —
1897
+ * re-sending the same `content` won't duplicate.
1898
+ *
1899
+ * The wire body is exactly `{ content, attribution, tags }` (see
1900
+ * {@link CreateFactInput}). The server responds 201 with the created
1901
+ * {@link Fact}.
1902
+ */
1903
+ createFact(input: CreateFactInput, signal?: AbortSignal, idempotencyKey?: string): Promise<CreateFactResponse>;
1904
+ /** Fetch one fact by id. Returns 404 → MnemosyneAPIError if not found. */
1905
+ getFact(id: string, signal?: AbortSignal): Promise<Fact>;
1906
+ /**
1907
+ * Pin a fact — protects it from automated prune/forget and gives it
1908
+ * a recall boost. Use for canonical, never-forget knowledge.
1909
+ *
1910
+ * The server models pin/unpin as a single route that takes a boolean
1911
+ * flag (POST /v1/facts/:id/pin with `{ pinned }`) rather than two
1912
+ * verbs, so we send `{ pinned: true }`.
1913
+ */
1914
+ pinFact(id: string, signal?: AbortSignal, idempotencyKey?: string): Promise<PinResponse>;
1915
+ /** Inverse of {@link pinFact} — same route, `{ pinned: false }`. */
1916
+ unpinFact(id: string, signal?: AbortSignal, idempotencyKey?: string): Promise<PinResponse>;
1917
+ /**
1918
+ * Forget a fact. This is the server's bitemporal soft-delete:
1919
+ * DELETE /v1/facts/:id sets `valid_to = now` rather than hard-deleting,
1920
+ * so the fact stays auditable/recoverable. Returns 204 No Content, so
1921
+ * this resolves to `void`.
1922
+ */
1923
+ forgetFact(id: string, signal?: AbortSignal, idempotencyKey?: string, reason?: string): Promise<ForgetResponse>;
1924
+ /**
1925
+ * P18 — Soft-delete (archive) any cognitive primitive by kind and id.
1926
+ * Maps to `DELETE /v1/forget/:kind/:id`.
1927
+ * For facts, prefer {@link forgetFact} which also supports idempotency keys.
1928
+ */
1929
+ forgetPrimitive(kind: "fact" | "decision" | "episode" | "entity" | "strategy" | "workflow" | "skill" | "task" | "event" | "reasoning" | "hyperedge", id: string, signal?: AbortSignal, reason?: string): Promise<{
1930
+ forgotten: boolean;
1931
+ }>;
1932
+ /**
1933
+ * Recent fact-lifecycle events for the workspace (created / pinned /
1934
+ * unpinned / closed / updated), newest-first. Useful for diff views
1935
+ * ("what did my AI learn this week?") and the Mnemosyne Studio
1936
+ * inspector. Paginate with `nextCursor` via the `since` param.
1937
+ */
1938
+ timeline(input?: TimelineInput, signal?: AbortSignal): Promise<TimelineResponse>;
1939
+ /**
1940
+ * Liveness + readiness snapshot. Returns more than a binary "ok"
1941
+ * so operators can wire it into existing dashboards (db / embedder /
1942
+ * queue sub-components are surfaced individually when degraded).
1943
+ */
1944
+ health(signal?: AbortSignal): Promise<HealthSnapshot>;
1945
+ /**
1946
+ * Quick readiness check endpoint. Maps to `GET /health/ready`.
1947
+ */
1948
+ healthReady(signal?: AbortSignal): Promise<{
1949
+ status: string;
1950
+ }>;
1951
+ /**
1952
+ * Generic request escape hatch for un-wrapped or dynamic routes.
1953
+ */
1954
+ request<T>(opts: {
1955
+ method: "GET" | "POST" | "PATCH" | "DELETE";
1956
+ path: string;
1957
+ body?: unknown;
1958
+ query?: Record<string, string | number | boolean | undefined>;
1959
+ signal?: AbortSignal;
1960
+ }): Promise<T>;
1961
+ /**
1962
+ * Introspect the current API key — returns workspace, user, tenant,
1963
+ * scopes, plan and expiry. Maps to `GET /me`.
1964
+ */
1965
+ getMe(signal?: AbortSignal): Promise<Record<string, unknown>>;
1966
+ /**
1967
+ * List workspaces available in the current tenant.
1968
+ * Maps to `GET /tenants/:tenantId/workspaces`.
1969
+ * Returns empty array when the key has no tenant binding.
1970
+ */
1971
+ listWorkspacesForCurrentTenant(signal?: AbortSignal): Promise<Array<Record<string, unknown>>>;
1972
+ /**
1973
+ * List workspaces the active user belongs to.
1974
+ * Maps to `GET /workspaces/mine`.
1975
+ */
1976
+ listMyWorkspaces(signal?: AbortSignal): Promise<Array<Record<string, unknown>>>;
1977
+ /**
1978
+ * List members of a workspace.
1979
+ * Maps to `GET /workspaces/:workspaceId/members`.
1980
+ */
1981
+ listWorkspaceMembers(workspaceId: string, signal?: AbortSignal): Promise<Array<Record<string, unknown>>>;
1982
+ /**
1983
+ * Run the 6 server-side operational diagnostic checks (connectivity,
1984
+ * app_user_grants, schema_shadows, migration_version, embedding_backlog,
1985
+ * workspace_id_valid) and return a structured `DoctorReport`.
1986
+ *
1987
+ * The `memory_doctor` MCP tool calls this and appends 2 additional
1988
+ * client-side checks (env_config, mcp_tools) before returning the merged
1989
+ * report to the LLM caller.
1990
+ *
1991
+ * Maps to `GET /v1/doctor`.
1992
+ */
1993
+ doctor(signal?: AbortSignal): Promise<DoctorReport>;
1994
+ /**
1995
+ * Aggregate workspace statistics: fact counts (live / closed / pinned /
1996
+ * archived / zero-hits), decision count, conflict relations, embedding
1997
+ * coverage, recall hit rate, and last activity timestamps.
1998
+ *
1999
+ * Delegates to `GET /v1/admin/stats` on the Mnemosyne server.
2000
+ * No parameters — all stats are scoped to the authenticated workspace
2001
+ * by RLS.
2002
+ */
2003
+ getStats(signal?: AbortSignal): Promise<AdminStats>;
2004
+ /**
2005
+ * Memory Graph snapshot. With no input, returns the workspace's full
2006
+ * canonical graph (entities + episodes + decisions, plus typed
2007
+ * relations between them). When `focus` is supplied (a cuid2-shaped
2008
+ * `ment_*` id), returns only that entity and its 1-hop neighbourhood
2009
+ * — cheaper to compute and much cheaper to render.
2010
+ *
2011
+ * The server caches with `Cache-Control: private, max-age=30`, so
2012
+ * repeated calls within that window are short-circuited by any
2013
+ * standards-conformant fetch implementation.
2014
+ */
2015
+ graph(input?: GraphInput, signal?: AbortSignal): Promise<GraphResponse>;
2016
+ /**
2017
+ * Multi-hop BFS traversal over `mnemo_relation` starting from a root entity.
2018
+ * Returns reachable nodes with their minimum hop distance and a relevance
2019
+ * score (decay^hop). Supports optional verb filtering and bitemporal as-of
2020
+ * reconstruction.
2021
+ *
2022
+ * Maps to `GET /v1/graph/traverse`.
2023
+ */
2024
+ graphTraverse(input: GraphTraverseInput, signal?: AbortSignal): Promise<{
2025
+ hits: TraverseHit[];
2026
+ }>;
2027
+ /**
2028
+ * Low-level BFS relation edge traversal from a root node over `mnemo_relation`.
2029
+ * Returns reachable nodes and raw edge objects.
2030
+ *
2031
+ * Maps to `POST /v1/relations/traverse`.
2032
+ */
2033
+ relationsTraverse(input: TraverseRelationsInput, signal?: AbortSignal): Promise<TraverseRelationsResponse>;
2034
+ /**
2035
+ * Shortest path between two nodes over `mnemo_relation` via a recursive
2036
+ * CTE with cycle detection. Returns the node id chain from `from` to `to`
2037
+ * and the relation verbs traversed at each step. Returns an empty path
2038
+ * when the nodes are unreachable within `maxHops`.
2039
+ *
2040
+ * Maps to `GET /v1/graph/path`.
2041
+ */
2042
+ graphPath(input: GraphPathInput, signal?: AbortSignal): Promise<GraphPathResponse>;
2043
+ /**
2044
+ * List entities in the workspace (Mnemosyne v1.6 G2 entity browser).
2045
+ * Filters by `kind` (one of 6 enum values) and/or `q` (case-insensitive
2046
+ * substring across name + aliases). Server-cap on `limit` is 200.
2047
+ *
2048
+ * Sorted newest-mentioned first (most likely interesting for the
2049
+ * inspector header).
2050
+ */
2051
+ listEntities(input?: ListEntitiesInput, signal?: AbortSignal): Promise<ListEntitiesResponse>;
2052
+ /**
2053
+ * Fetch a single entity by id plus its active-fact count. The count
2054
+ * powers the inspector header chip ("12 linked facts") without
2055
+ * forcing a second round-trip. Throws {@link MnemosyneAPIError} (404)
2056
+ * when the entity doesn't exist in this workspace.
2057
+ */
2058
+ getEntity(id: string, signal?: AbortSignal): Promise<EntityWithCount>;
2059
+ /**
2060
+ * List the facts the extraction pipeline linked to a given entity
2061
+ * (via `mnemo_fact.entity_id`). Active facts only — forgotten/merged
2062
+ * stay hidden from the entity-detail view. Server-cap on `limit` is
2063
+ * 500. Throws 404 when the entity itself doesn't exist.
2064
+ */
2065
+ listEntityFacts(id: string, input?: ListEntityFactsInput, signal?: AbortSignal): Promise<EntityFactsResponse>;
2066
+ /**
2067
+ * List episodes in a date window (Mnemosyne v1.4 timeline). When
2068
+ * `from`/`to` are omitted the server defaults to the last 30 days —
2069
+ * the inspector rarely cares about older slices unless explicitly
2070
+ * requested. `topic` filters via the GIN-indexed `topics` array
2071
+ * (single-topic only by design). Server-cap on `limit` is 200.
2072
+ *
2073
+ * `includeSynthetic` defaults to false — extractor-synthesised
2074
+ * episodes are hidden from the inspector view but visible to operator
2075
+ * tools that opt in.
2076
+ */
2077
+ listEpisodes(input?: ListEpisodesInput, signal?: AbortSignal): Promise<ListEpisodesResponse>;
2078
+ /**
2079
+ * Fetch a single episode plus its linked facts. Linked facts that
2080
+ * have since been archived are silently filtered out (an episode
2081
+ * legitimately outlives some of its constituent facts). Throws 404
2082
+ * when the episode itself doesn't exist.
2083
+ */
2084
+ getEpisode(id: string, signal?: AbortSignal): Promise<EpisodeWithLinkedFacts>;
2085
+ /**
2086
+ * Manual entity create. The extraction pipeline auto-creates via
2087
+ * `findOrCreate`; this method exists so an operator can bootstrap
2088
+ * the entity table before any conversation has happened or
2089
+ * backfill an out-of-band mention.
2090
+ *
2091
+ * The server enforces a `(workspace_id, name, kind)` unique
2092
+ * constraint — a duplicate surfaces as a {@link MnemosyneAPIError}
2093
+ * with status 409.
2094
+ */
2095
+ createEntity(input: CreateEntityInput, signal?: AbortSignal, idempotencyKey?: string): Promise<MnemoEntity>;
2096
+ /**
2097
+ * Patch an existing entity (rename / alias edits / kind change /
2098
+ * canonical merge). An empty patch (every key undefined) gets
2099
+ * 400; canonicalId targets that don't exist (or equal the row
2100
+ * being patched) get 400. 404 when the row itself doesn't exist.
2101
+ */
2102
+ updateEntity(id: string, input: UpdateEntityInput, signal?: AbortSignal): Promise<MnemoEntity>;
2103
+ /**
2104
+ * List active-learning queue rows (Mnemosyne v1.3+). Defaults to
2105
+ * unresolved only — pass `all:true` to include resolved rows for
2106
+ * the full history. Editor-tier surface; the queue is an
2107
+ * operational concern.
2108
+ */
2109
+ listReview(input?: ListReviewInput, signal?: AbortSignal): Promise<ListReviewResponse>;
2110
+ /**
2111
+ * Cheap COUNT(*) of unresolved queue rows. Powers the inspector
2112
+ * header badge ("12 to review") — uses the partial index
2113
+ * `idx_mnemo_review_queue_workspace_unresolved` so it's
2114
+ * constant-time at queue depths the inspector cares about.
2115
+ */
2116
+ reviewCount(signal?: AbortSignal): Promise<ReviewCountResponse>;
2117
+ /**
2118
+ * Close a queue row. When `resolution='forgotten'` AND the row is
2119
+ * fact-sourced, the server atomically cascades the fact's status
2120
+ * to 'forgotten' in the same tx so the fact leaves the recall pool
2121
+ * without a follow-up round-trip. The response's `cascaded` field
2122
+ * confirms this happened.
2123
+ *
2124
+ * Throws 404 if the row doesn't exist; 409 if it was already
2125
+ * resolved (idempotent re-resolve is intentionally NOT silent so
2126
+ * the caller can decide whether to retry or surface a warning).
2127
+ */
2128
+ resolveReview(id: string, input: ResolveReviewInput, signal?: AbortSignal): Promise<ResolveReviewResponse>;
2129
+ /**
2130
+ * "Undo log" feed — most recent fact-mutation events. Synthesised
2131
+ * from two sources: user-driven Forget (revertible via
2132
+ * {@link restoreFact}) and janitor-driven archive (not revertible).
2133
+ * Newest first. Powers the inspector's undo surface.
2134
+ */
2135
+ audit(input?: AuditInput, signal?: AbortSignal): Promise<AuditResponse>;
2136
+ /**
2137
+ * Full workspace memory dump (admin-tier surface). Returns the four
2138
+ * mnemo_* tables (facts, decisions, relations, citations) in a
2139
+ * single buffered JSON payload. Embeddings are excluded.
2140
+ *
2141
+ * v1.3 caps at 100k rows per resource. Large workspaces should
2142
+ * wait for the v1.4 streaming endpoint rather than chunk by hand.
2143
+ */
2144
+ exportWorkspace(signal?: AbortSignal): Promise<ExportResponse>;
2145
+ /**
2146
+ * Restore a forgotten fact — flips `status` back to 'active' so the
2147
+ * fact rejoins the recall pool. Companion to {@link forgetFact}.
2148
+ * Returns the minimal `{id, status}` pair; chain {@link getFact}
2149
+ * if you need the full body.
2150
+ *
2151
+ * 404 when the fact doesn't exist (or RLS hides it).
2152
+ */
2153
+ restoreFact(id: string, signal?: AbortSignal): Promise<RestoreFactResponse>;
2154
+ /**
2155
+ * List decisions in the workspace (Mnemosyne v1.5). Decisions are
2156
+ * durable, audited statements of "we are going to do X because Y"
2157
+ * — distinct from facts (transient observations). Newest first.
2158
+ */
2159
+ listDecisions(input?: ListDecisionsInput, signal?: AbortSignal): Promise<ListDecisionsResponse>;
2160
+ /**
2161
+ * Fetch a single decision by id. Throws 404 if it doesn't exist.
2162
+ *
2163
+ * Note: orchester's `/api/mnemo/decisions/[traceId]` route is the
2164
+ * Decision BOM (Bill-of-Materials) endpoint, which joins mnemo
2165
+ * decision data with orchester's audit_log table — this method
2166
+ * returns ONLY the mnemo decision row, not the BOM composition.
2167
+ */
2168
+ getDecision(id: string, signal?: AbortSignal): Promise<MnemoDecision>;
2169
+ /**
2170
+ * Paginated fact list (rich projection — subject/statement/kind, not
2171
+ * the simplified content shape `/facts/:id` returns).
2172
+ *
2173
+ * Tramo 5 surface:
2174
+ * - Filters: kind, scope, scopeRef, status, pinned, asOf (bitemporal).
2175
+ * - Search: `q` runs `plainto_tsquery` on the lemmatized column with
2176
+ * an ILIKE fallback for facts whose lemma column is null.
2177
+ * - Sort: `sortBy` ∈ {created_at, updated_at, relevance, hit_count},
2178
+ * `order` ∈ {asc, desc}. Tied rows are broken by id.
2179
+ * - Pagination: pass back the previous response's `nextCursor` to
2180
+ * keyset-paginate. Cursors are opaque — do not parse them.
2181
+ *
2182
+ * Response envelope `{ items, nextCursor, total }`. `total` is the
2183
+ * COUNT(*) for the filter set (sans cursor) so an inspector header
2184
+ * can render "X of Y" without a separate request.
2185
+ */
2186
+ listFacts(input?: ListFactsInput, signal?: AbortSignal): Promise<ListFactsResponse>;
2187
+ /**
2188
+ * Patch a fact's editable columns (subject/statement/kind/pinned/
2189
+ * confidence/relevance/metadata). An empty patch (every field
2190
+ * undefined) returns 400; 404 when the row doesn't exist.
2191
+ *
2192
+ * Bitemporal note: PATCH does NOT close the interval — `validFrom`
2193
+ * stays put, `validTo` stays null. Use {@link forgetFact} to mark
2194
+ * the fact as no-longer-valid at a point in time.
2195
+ */
2196
+ patchFact(id: string, input: PatchFactInput, signal?: AbortSignal): Promise<MemoryFact>;
2197
+ /**
2198
+ * Source-message ids for a fact. Returns just the id list —
2199
+ * Mnemosyne doesn't own the message table that orchester joins
2200
+ * against, so hosts wanting `{role, content, timestamp}` per message
2201
+ * do that join on their side.
2202
+ */
2203
+ getFactCitations(id: string, signal?: AbortSignal): Promise<FactCitationsResponse>;
2204
+ /**
2205
+ * Create a decision (Mnemosyne v1.5). Topic-key upsert + normalized-
2206
+ * hash dedup happen server-side — re-creating a decision with the
2207
+ * same (workspace_id, topic_key) returns the existing row (201
2208
+ * status either way; the client cannot distinguish first-create
2209
+ * from upsert without comparing the returned id).
2210
+ */
2211
+ createDecision(input: CreateDecisionInput, signal?: AbortSignal, idempotencyKey?: string): Promise<MnemoDecision>;
2212
+ /**
2213
+ * Supersede a decision: marks `id` as status='superseded' and
2214
+ * points its supersededById at `input.supersededById`. Returns
2215
+ * the updated decision. Caller is responsible for the matching
2216
+ * `supersedes` relation row (via {@link createRelation}).
2217
+ */
2218
+ supersedeDecision(id: string, input: SupersedeDecisionInput, signal?: AbortSignal): Promise<MnemoDecision>;
2219
+ /**
2220
+ * List relations in the workspace (Mnemosyne v1.0 — LOCKED 9-verb
2221
+ * vocabulary). Filter by `judgmentStatus`: typical inspector use is
2222
+ * `judgmentStatus: 'pending'` for the judge queue.
2223
+ */
2224
+ listRelations(input?: ListRelationsInput, signal?: AbortSignal): Promise<ListRelationsResponse>;
2225
+ /**
2226
+ * Create a relation between two memory primitives. `relation` MUST
2227
+ * be one of the 9 LOCKED verbs; the server 400-rejects unknown verbs.
2228
+ *
2229
+ * Multi-actor disagreement is captured by creating a SECOND relation
2230
+ * row with the same source/target but a different markedBy* —
2231
+ * the server has no UNIQUE constraint preventing this (intentional,
2232
+ * see migration 0020).
2233
+ */
2234
+ createRelation(input: CreateRelationInput, signal?: AbortSignal, idempotencyKey?: string): Promise<MnemoRelation>;
2235
+ /**
2236
+ * Apply a judgment to a pending relation: replace the verb, flip
2237
+ * `judgmentStatus` to 'judged', stamp the marker. Returns the
2238
+ * updated row, or throws 404 when the relation does not exist.
2239
+ */
2240
+ patchRelation(id: string, input: PatchRelationInput, signal?: AbortSignal): Promise<MnemoRelation>;
2241
+ /**
2242
+ * List citations attached to memory primitives. Filter by
2243
+ * `memoryKind` (fact/decision/entity/episode) and/or `memoryId`
2244
+ * for a specific row's provenance trail. Newest first.
2245
+ */
2246
+ listCitations(input?: ListCitationsInput, signal?: AbortSignal): Promise<ListCitationsResponse>;
2247
+ /**
2248
+ * Manually enqueue a fact (or decision) for human review.
2249
+ * Idempotent via the server-side partial index: re-enqueuing an
2250
+ * open row returns the existing id with `inserted:false` instead
2251
+ * of creating a duplicate. Exactly one of `factId`/`decisionId`
2252
+ * MUST be supplied; the server 400-rejects both-or-neither.
2253
+ */
2254
+ enqueueReview(input: EnqueueReviewInput, signal?: AbortSignal): Promise<EnqueueReviewResponse>;
2255
+ /**
2256
+ * Create a prospective memory reminder. The reminder will surface during
2257
+ * recall when its time condition (`triggerAt`) is met, when the query
2258
+ * embedding is semantically close to the reminder's condition, or both.
2259
+ *
2260
+ * Returns the created reminder with its assigned `id`.
2261
+ */
2262
+ createReminder(input: {
2263
+ content: string;
2264
+ condition: string;
2265
+ triggerAt?: string;
2266
+ }, signal?: AbortSignal, idempotencyKey?: string): Promise<{
2267
+ id: string;
2268
+ content: string;
2269
+ condition: string;
2270
+ triggerAt: string | null;
2271
+ status: string;
2272
+ createdAt: string;
2273
+ }>;
2274
+ /**
2275
+ * List reminders for the workspace. Defaults to `status=pending`.
2276
+ *
2277
+ * @param status - 'pending' | 'triggered' | 'dismissed' | 'all' (default: 'pending')
2278
+ * @param limit - Max rows to return (default: 50, max: 200)
2279
+ */
2280
+ listReminders(input?: {
2281
+ status?: "pending" | "triggered" | "dismissed" | "all";
2282
+ limit?: number;
2283
+ }, signal?: AbortSignal): Promise<{
2284
+ reminders: Array<{
2285
+ id: string;
2286
+ content: string;
2287
+ condition: string;
2288
+ triggerAt: string | null;
2289
+ status: string;
2290
+ createdAt: string;
2291
+ }>;
2292
+ }>;
2293
+ /**
2294
+ * Dismiss a reminder by id. Sets status to 'dismissed' (no row deleted).
2295
+ * Throws MnemosyneAPIError (404) when the reminder does not exist.
2296
+ */
2297
+ dismissReminder(id: string, signal?: AbortSignal): Promise<void>;
2298
+ /**
2299
+ * Start a new ephemeral session (episode). Use the returned `id` with
2300
+ * {@link collapseSession} when the conversation ends.
2301
+ *
2302
+ * Maps to `POST /v1/session/start` on the Mnemosyne server.
2303
+ */
2304
+ createSession(input?: CreateSessionInput, signal?: AbortSignal, idempotencyKey?: string): Promise<CreateSessionResponse>;
2305
+ /**
2306
+ * Collapse an active session into durable knowledge units (facts,
2307
+ * decisions, strategies). The server returns 202 Accepted after the
2308
+ * collapse pipeline completes.
2309
+ *
2310
+ * Throws `MnemosyneAPIError` with status 404 when the session does not
2311
+ * exist or has already been collapsed.
2312
+ *
2313
+ * Maps to `POST /v1/session/:id/collapse` on the Mnemosyne server.
2314
+ */
2315
+ collapseSession(id: string, input?: CollapseSessionInput, signal?: AbortSignal, idempotencyKey?: string): Promise<CollapseSessionResponse>;
2316
+ /**
2317
+ * Append a conversation turn to an active session's transcript.
2318
+ *
2319
+ * Both user and assistant turns should be recorded here so the collapse
2320
+ * pipeline can extract facts from the full conversation context.
2321
+ *
2322
+ * Maps to `POST /v1/session/:id/turn`. Returns 204 No Content (void).
2323
+ */
2324
+ appendTurn(id: string, input: AppendTurnInput, signal?: AbortSignal): Promise<void>;
2325
+ /**
2326
+ * Pin or unpin a specific turn within an active session.
2327
+ *
2328
+ * Pinned turns are given higher weight during the collapse extraction pass
2329
+ * and are more likely to become durable facts.
2330
+ *
2331
+ * Maps to `POST /v1/session/:id/pin`. Returns 204 No Content (void).
2332
+ */
2333
+ pinSessionTurn(id: string, input: PinSessionTurnInput, signal?: AbortSignal): Promise<void>;
2334
+ /**
2335
+ * Submit explicit user feedback (thumbs up/down rating) for a session.
2336
+ *
2337
+ * Maps to `POST /v1/session/:id/feedback`. Returns 204 No Content (void).
2338
+ */
2339
+ sessionFeedback(id: string, rating: "up" | "down", signal?: AbortSignal): Promise<void>;
2340
+ /**
2341
+ * Namespaced session helpers — convenience wrapper that satisfies the
2342
+ * spec's chaining example with zero client state.
2343
+ *
2344
+ * @example
2345
+ * ```ts
2346
+ * const { id } = await client.sessions.create();
2347
+ * await client.sessions.addTurn(id, { role: "user", content: "Hello!" });
2348
+ * await client.sessions.pinTurn(id, { turnId: "turn_1", pinned: true });
2349
+ * await client.sessions.collapse(id);
2350
+ * ```
2351
+ */
2352
+ get sessions(): {
2353
+ create: (input?: CreateSessionInput, signal?: AbortSignal, idempotencyKey?: string) => Promise<CreateSessionResponse>;
2354
+ addTurn: (id: string, input: AppendTurnInput, signal?: AbortSignal) => Promise<void>;
2355
+ pinTurn: (id: string, input: PinSessionTurnInput, signal?: AbortSignal) => Promise<void>;
2356
+ collapse: (id: string, input?: CollapseSessionInput, signal?: AbortSignal, idempotencyKey?: string) => Promise<CollapseSessionResponse>;
2357
+ feedback: (id: string, rating: "up" | "down", signal?: AbortSignal) => Promise<void>;
2358
+ };
2359
+ /**
2360
+ * Write a scratch note (ephemeral working-memory entry) to an active session.
2361
+ *
2362
+ * The `scratch` object is stored under the session's working-memory context.
2363
+ * The `note` key conventionally carries the human-readable text; additional
2364
+ * arbitrary keys are passed through as metadata (e.g. `{ role, metadata }`).
2365
+ *
2366
+ * Maps to `POST /v1/session/:id/scratch` (not `/turn` — they are different
2367
+ * endpoints: `/scratch` is ephemeral working-memory, `/turn` is transcript).
2368
+ * Returns 204 No Content, so this resolves to `void`.
2369
+ */
2370
+ updateSessionScratch(id: string, scratch: Record<string, unknown>, signal?: AbortSignal): Promise<void>;
2371
+ /**
2372
+ * Discard an active session without collapsing it into durable memory.
2373
+ *
2374
+ * Use when the conversation should be abandoned (e.g. user cancelled or
2375
+ * the context is irrelevant) rather than collapsed into knowledge units.
2376
+ * The server marks the session as discarded; no extraction pass is run.
2377
+ *
2378
+ * Maps to `POST /v1/session/:id/discard`. Returns 204 No Content, so this
2379
+ * resolves to `void`.
2380
+ */
2381
+ discardSession(id: string, signal?: AbortSignal): Promise<void>;
2382
+ /**
2383
+ * Trigger an on-demand consolidation pass for the workspace.
2384
+ *
2385
+ * The background scheduler already runs on its own interval. Use this
2386
+ * method when you want to force a consolidation immediately — e.g. after
2387
+ * a large batch of `remember` calls, or when the `memory_consolidate`
2388
+ * MCP tool is invoked.
2389
+ *
2390
+ * Only `mode: "fast"` (default) with `dryRun: false` is currently
2391
+ * supported and processes a bounded low-worth candidate set. Manual `mode: "deep"`
2392
+ * requests throw `MnemosyneAPIError` with status 422 and code
2393
+ * `deep_mode_not_supported`. Requests with `dryRun: true` throw status 422
2394
+ * with code `dry_run_not_supported`, without running consolidation.
2395
+ *
2396
+ * Throws `MnemosyneAPIError` with status 503 when required server-side
2397
+ * consolidation or storage services are unavailable.
2398
+ *
2399
+ * Maps to `POST /v1/consolidation/trigger`.
2400
+ */
2401
+ triggerConsolidation(input?: TriggerConsolidationInput, signal?: AbortSignal, idempotencyKey?: string): Promise<TriggerConsolidationResponse>;
2402
+ /** List tasks for the workspace. Maps to `GET /v1/tasks`. */
2403
+ listTasks(params?: ListTasksParams, signal?: AbortSignal): Promise<PaginatedTasksResponse>;
2404
+ /** Create a new task. Maps to `POST /v1/tasks`. */
2405
+ createTask(body: CreateTaskInput, signal?: AbortSignal, idempotencyKey?: string): Promise<TaskWire>;
2406
+ /** Get a single task by ID. Maps to `GET /v1/tasks/:id`. */
2407
+ getTask(id: string, signal?: AbortSignal): Promise<TaskWire>;
2408
+ /** Update fields on an existing task. Maps to `PATCH /v1/tasks/:id`. */
2409
+ patchTask(id: string, body: PatchTaskInput, signal?: AbortSignal): Promise<TaskWire>;
2410
+ /** Archive (soft-delete) a task. Maps to `DELETE /v1/tasks/:id`. */
2411
+ archiveTask(id: string, signal?: AbortSignal): Promise<void>;
2412
+ /** List events for the workspace. Maps to `GET /v1/events`. */
2413
+ listEvents(params?: ListEventsParams, signal?: AbortSignal): Promise<PaginatedEventsResponse>;
2414
+ /** Create a new event (immutable append). Maps to `POST /v1/events`. */
2415
+ createEvent(body: CreateEventInput, signal?: AbortSignal, idempotencyKey?: string): Promise<EventWire>;
2416
+ /** Get a single event by ID. Maps to `GET /v1/events/:id`. */
2417
+ getEvent(id: string, signal?: AbortSignal): Promise<EventWire>;
2418
+ /** Archive an event (soft-delete). Maps to `DELETE /v1/events/:id`. */
2419
+ archiveEvent(id: string, signal?: AbortSignal): Promise<void>;
2420
+ /** Append a human annotation to an immutable event. Maps to `POST /v1/events/:id/annotations`. */
2421
+ annotateEvent(id: string, body: {
2422
+ author: string;
2423
+ content: string;
2424
+ at?: string;
2425
+ }, signal?: AbortSignal): Promise<EventWire>;
2426
+ /** List workflows in the workspace. Maps to `GET /v1/workflows`. */
2427
+ listWorkflows(params?: {
2428
+ status?: string;
2429
+ scopeRef?: string;
2430
+ offset?: number;
2431
+ limit?: number;
2432
+ }, signal?: AbortSignal): Promise<{
2433
+ items: unknown[];
2434
+ total: number;
2435
+ hasMore: boolean;
2436
+ }>;
2437
+ /** Create a new workflow. Maps to `POST /v1/workflows`. */
2438
+ createWorkflow(body: {
2439
+ name: string;
2440
+ description?: string;
2441
+ steps: unknown[];
2442
+ scopeRef?: string;
2443
+ metadata?: Record<string, unknown>;
2444
+ }, signal?: AbortSignal): Promise<unknown>;
2445
+ /** Get a single workflow by ID. Maps to `GET /v1/workflows/:id`. */
2446
+ getWorkflow(id: string, signal?: AbortSignal): Promise<unknown>;
2447
+ /** List reasoning chains for the workspace. Maps to `GET /v1/reasoning`. */
2448
+ listReasoning(params?: ListReasoningParams, signal?: AbortSignal): Promise<PaginatedReasoningResponse>;
2449
+ /** Create a new reasoning chain. Maps to `POST /v1/reasoning`. */
2450
+ createReasoning(body: CreateReasoningInput, signal?: AbortSignal): Promise<ReasoningWire>;
2451
+ /** Get a single reasoning chain by ID. Maps to `GET /v1/reasoning/:id`. */
2452
+ getReasoning(id: string, signal?: AbortSignal): Promise<ReasoningWire>;
2453
+ /** Update fields on an existing reasoning chain. Maps to `PATCH /v1/reasoning/:id`. */
2454
+ patchReasoning(id: string, body: PatchReasoningInput, signal?: AbortSignal): Promise<ReasoningWire>;
2455
+ /** Archive (soft-delete) a reasoning chain. Maps to `DELETE /v1/reasoning/:id`. */
2456
+ archiveReasoning(id: string, signal?: AbortSignal): Promise<void>;
2457
+ /** Resolve a reasoning query against the CoT cache. Maps to `POST /v1/reasoning/resolve`. */
2458
+ resolveReasoning(body: ResolveReasoningInput, signal?: AbortSignal): Promise<ResolveReasoningResponse>;
2459
+ /** Record a completed reasoning chain into the CoT cache. Maps to `POST /v1/reasoning/record`. */
2460
+ recordReasoning(body: RecordReasoningInput, signal?: AbortSignal): Promise<ReasoningWire>;
2461
+ /** Submit outcome feedback for a cached reasoning chain. Maps to `POST /v1/reasoning/feedback`. */
2462
+ reasoningFeedback(body: ReasoningFeedbackInput, signal?: AbortSignal): Promise<ReasoningWire>;
2463
+ /** List strategies for the workspace. */
2464
+ listStrategies(params?: ListStrategiesParams, signal?: AbortSignal): Promise<PaginatedStrategiesResponse>;
2465
+ /** Create a new strategy. */
2466
+ createStrategy(body: CreateStrategyInput, signal?: AbortSignal, idempotencyKey?: string): Promise<StrategyWire>;
2467
+ /** Get a single strategy by ID. */
2468
+ getStrategy(id: string, signal?: AbortSignal): Promise<StrategyWire>;
2469
+ /** Patch an existing strategy. */
2470
+ patchStrategy(id: string, body: PatchStrategyInput, signal?: AbortSignal): Promise<StrategyWire>;
2471
+ /** Archive a strategy (soft-delete). */
2472
+ archiveStrategy(id: string, signal?: AbortSignal): Promise<void>;
2473
+ /**
2474
+ * §24 Record the outcome of executing a strategy.
2475
+ * Triggers a Beta-Bernoulli recompute on the server:
2476
+ * alpha = 2 + successCount, beta = 2 + failureCount, worth = alpha / (alpha + beta).
2477
+ * Not idempotent — each call increments successCount or failureCount.
2478
+ */
2479
+ rateStrategy(id: string, outcome: "success" | "failure", signal?: AbortSignal): Promise<StrategyWire>;
2480
+ /** List hyperedges for this workspace. */
2481
+ listHyperedges(params?: ListHyperedgesParams, signal?: AbortSignal): Promise<PaginatedHyperedgesResponse>;
2482
+ /** Create a new hyperedge (n-ary relation with ≥3 members). */
2483
+ createHyperedge(body: CreateHyperedgeInput, signal?: AbortSignal, idempotencyKey?: string): Promise<HyperedgeWire>;
2484
+ /** Get a single hyperedge by ID. */
2485
+ getHyperedge(id: string, signal?: AbortSignal): Promise<HyperedgeWire>;
2486
+ /** Patch an existing hyperedge (label, description, contextQuery). */
2487
+ patchHyperedge(id: string, body: PatchHyperedgeInput, signal?: AbortSignal): Promise<HyperedgeWire>;
2488
+ /** Archive a hyperedge (soft-delete). */
2489
+ archiveHyperedge(id: string, signal?: AbortSignal): Promise<void>;
2490
+ /** Return the workspace SelfModel (§31 meta-cognition). */
2491
+ getSelfModel(opts?: {
2492
+ aspect?: SelfModelAspect;
2493
+ entity?: string;
2494
+ limit?: number;
2495
+ }, signal?: AbortSignal): Promise<SelfModelResponse>;
2496
+ /**
2497
+ * Return ranked anticipated memories (§8 Anticipation Engine).
2498
+ *
2499
+ * The `GET /v1/anticipation` route honors four query params:
2500
+ * - `recentlyRecalledId` — drives the sequential ("when I recall X I
2501
+ * usually recall Y") branch. Without it, only periodicity counts.
2502
+ * - `context` — free-text query context for conditional anticipation
2503
+ * patterns (§30). Server caps length at 500 chars.
2504
+ * - `lookAhead` — minutes to anticipate ahead (§30); shifts the
2505
+ * periodic slot. Server default 30, range 0–10080 (one week).
2506
+ * - `limit` — max items, server default 20, range 1–100.
2507
+ */
2508
+ getAnticipationFeed(opts?: {
2509
+ recentlyRecalledId?: string;
2510
+ context?: string;
2511
+ lookAhead?: number;
2512
+ limit?: number;
2513
+ }): Promise<AnticipationFeedResponse>;
2514
+ /**
2515
+ * Namespace getter for §32 Compositionality Engine admin routes.
2516
+ *
2517
+ * @example
2518
+ * ```ts
2519
+ * const page = await client.composition.listRules({ isActive: true });
2520
+ * const rule = await client.composition.createRule({ name: "My Rule", ... });
2521
+ * const dryRun = await client.composition.dryRun({ ruleId: "r-1", hits });
2522
+ * ```
2523
+ */
2524
+ get composition(): {
2525
+ listRules(opts?: {
2526
+ isActive?: boolean;
2527
+ offset?: number;
2528
+ limit?: number;
2529
+ signal?: AbortSignal;
2530
+ }): Promise<ListCompositionRulesResponse>;
2531
+ createRule(input: {
2532
+ name: string;
2533
+ conditionDsl: unknown;
2534
+ actionDsl: unknown;
2535
+ description?: string;
2536
+ priority?: number;
2537
+ isActive?: boolean;
2538
+ source?: "manual" | "mined" | "imported";
2539
+ metadata?: Record<string, unknown>;
2540
+ }, signal?: AbortSignal): Promise<CompositionRule>;
2541
+ getRule(id: string, signal?: AbortSignal): Promise<CompositionRule>;
2542
+ patchRule(id: string, patch: {
2543
+ name?: string;
2544
+ description?: string;
2545
+ conditionDsl?: unknown;
2546
+ actionDsl?: unknown;
2547
+ priority?: number;
2548
+ isActive?: boolean;
2549
+ metadata?: Record<string, unknown>;
2550
+ }, signal?: AbortSignal): Promise<CompositionRule>;
2551
+ dryRun(input: {
2552
+ ruleId?: string;
2553
+ rule?: {
2554
+ name: string;
2555
+ conditionDsl: unknown;
2556
+ actionDsl: unknown;
2557
+ priority?: number;
2558
+ };
2559
+ hits: Array<{
2560
+ id: string;
2561
+ primitive: string;
2562
+ content: string;
2563
+ score: number;
2564
+ factKind?: string;
2565
+ worth?: number;
2566
+ tags?: string[];
2567
+ }>;
2568
+ }, signal?: AbortSignal): Promise<CompositionDryRunResponse>;
2569
+ };
2570
+ /**
2571
+ * Edit the agent's own memory using one of seven actions:
2572
+ * append | replace | strengthen | weaken | forget | reflect | link.
2573
+ * `target` is polymorphic: fact_id | "profile" | "strategy:{id}".
2574
+ * `reason` is required policy and log context, but is not durably audited yet.
2575
+ * link: creates an n-ary hyperedge; target=anchor, content=comma-separated co-members (total ≥3).
2576
+ */
2577
+ selfEdit(input: {
2578
+ action: "append" | "replace" | "strengthen" | "weaken" | "forget" | "reflect" | "link";
2579
+ target: string;
2580
+ content?: string;
2581
+ reason: string;
2582
+ agentId?: string;
2583
+ sessionId?: string;
2584
+ }, signal?: AbortSignal, idempotencyKey?: string): Promise<SelfEditResponse>;
2585
+ /**
2586
+ * Trigger the reflection cycle immediately for an agent.
2587
+ * Returns the episode_id of the synthetic reflection episode plus
2588
+ * the lists of strengthened / weakened strategy ids.
2589
+ */
2590
+ selfReflect(input?: {
2591
+ agentId?: string;
2592
+ }, signal?: AbortSignal): Promise<{
2593
+ episode_id: string;
2594
+ strengthened: string[];
2595
+ weakened: string[];
2596
+ }>;
2597
+ /**
2598
+ * Retrieve the current agent profile (self-model).
2599
+ * Returns an empty profile (summary: "") when none exists yet.
2600
+ */
2601
+ getSelfProfile(agentId?: string, signal?: AbortSignal): Promise<{
2602
+ workspaceId: string;
2603
+ agentId: string;
2604
+ summary: string;
2605
+ metadata: Record<string, unknown>;
2606
+ createdAt: string | null;
2607
+ updatedAt: string | null;
2608
+ }>;
2609
+ /**
2610
+ * List all approved peers in the federation mesh.
2611
+ * Maps to `GET /v1/memory/federation/peers`.
2612
+ */
2613
+ listFederationPeers(signal?: AbortSignal): Promise<ListPeersResponse>;
2614
+ /**
2615
+ * List peers awaiting approval plus discovery state.
2616
+ * Maps to `GET /v1/memory/federation/peers/pending`.
2617
+ */
2618
+ listPendingFederationPeers(signal?: AbortSignal): Promise<ListPendingPeersResponse>;
2619
+ /**
2620
+ * Approve a pending peer (certificate rotation).
2621
+ * Maps to `POST /v1/memory/federation/peers/:id/approve`.
2622
+ */
2623
+ approveFederationPeer(id: string, input: ApprovePeerInput, signal?: AbortSignal): Promise<void>;
2624
+ /**
2625
+ * Approve a peer's public key specifically.
2626
+ * Maps to `POST /v1/memory/federation/peers/:id/approve-key`.
2627
+ */
2628
+ approveFederationPeerKey(id: string, input: ApprovePeerInput, signal?: AbortSignal): Promise<ApprovePeerKeyResponse>;
2629
+ /**
2630
+ * Remove a peer from the federation mesh.
2631
+ * Maps to `DELETE /v1/memory/federation/peers/:id`.
2632
+ */
2633
+ deleteFederationPeer(id: string, signal?: AbortSignal): Promise<DeletePeerResponse>;
2634
+ /**
2635
+ * Fetch the federated item log (facts received from peers).
2636
+ * Maps to `GET /v1/memory/federation/items`.
2637
+ */
2638
+ listFederationItems(opts?: {
2639
+ since?: string;
2640
+ limit?: number;
2641
+ }, signal?: AbortSignal): Promise<ListFederationItemsResponse>;
2642
+ /**
2643
+ * Trigger an immediate sync pull from a peer.
2644
+ * Maps to `POST /v1/memory/federation/sync` (returns 202 Accepted).
2645
+ */
2646
+ triggerFederationSync(input: TriggerFederationSyncInput, signal?: AbortSignal): Promise<TriggerFederationSyncResponse>;
2647
+ /**
2648
+ * Get status of a federation sync job by its jobId.
2649
+ * Maps to `GET /v1/memory/federation/sync/:jobId`.
2650
+ */
2651
+ getFederationSyncJob(jobId: string, signal?: AbortSignal): Promise<FederationSyncJob>;
2652
+ /**
2653
+ * Resolve a conflict between federated claims. Accepts either a
2654
+ * two-item pair (`{ itemA, itemB }`) or a batch (`{ items: [...] }`).
2655
+ *
2656
+ * Maps to `POST /v1/memory/federation/resolve`.
2657
+ */
2658
+ resolveFederationConflict(input: ResolveFederationConflictPairInput | ResolveFederationConflictBatchInput, signal?: AbortSignal): Promise<ResolveFederationConflictResponse>;
2659
+ /**
2660
+ * List unresolved conflict pairs in the workspace.
2661
+ *
2662
+ * Conflicts are `conflicts_with` relations between active facts that have
2663
+ * not yet been resolved. The list is sorted newest-first. Use
2664
+ * `resolveConflict` to apply a resolution action to each pair.
2665
+ *
2666
+ * @param limit - Max pairs to return. Default 5, max 20.
2667
+ * Maps to `GET /v1/conflicts`.
2668
+ */
2669
+ judge(opts?: {
2670
+ limit?: number;
2671
+ }, signal?: AbortSignal): Promise<ListConflictsResponse>;
2672
+ /**
2673
+ * Resolve a specific conflict pair by its `relationId`.
2674
+ *
2675
+ * Four resolution strategies:
2676
+ * - `supersede_a`: forget factA, relation becomes `supersedes`.
2677
+ * - `supersede_b`: forget factB, relation becomes `supersedes`.
2678
+ * - `keep_both`: mark as `not_conflict` (both facts stay active).
2679
+ * - `merge`: forget both, create a new merged fact, relation becomes `supersedes`.
2680
+ * `mergedStatement` is required for this action.
2681
+ *
2682
+ * Maps to `POST /v1/conflicts/:id/resolve`.
2683
+ */
2684
+ resolveConflict(relationId: string, input: ResolveConflictInput, signal?: AbortSignal): Promise<ResolveConflictResponse>;
2685
+ /**
2686
+ * Subscribe to a Mnemosyne event channel via WebSocket.
2687
+ *
2688
+ * Opens a WebSocket to `/memory/ws?token=<apiKey>`, sends a subscribe
2689
+ * frame for `channel`, and calls `handler` for each matching event.
2690
+ *
2691
+ * Requires a `WebSocket` global (native in Node ≥ 22 and browsers; inject
2692
+ * via `opts.WebSocketImpl` for older environments):
2693
+ *
2694
+ * ```ts
2695
+ * import WebSocket from "ws"; // npm install ws
2696
+ * const handle = client.subscribe("facts.*", console.log, { WebSocketImpl: WebSocket });
2697
+ * ```
2698
+ *
2699
+ * Live server integration requires Wave Q WS wiring to be confirmed.
2700
+ * Tests are skipped until then.
2701
+ *
2702
+ * @param channel - Glob channel, e.g. `"facts.*"`, `"session.abc123"`.
2703
+ * @param handler - Called with each raw bus event payload (JSON).
2704
+ * @param opts - Optional filter / disconnect / WebSocketImpl.
2705
+ */
2706
+ subscribe(channel: string, handler: (event: Record<string, unknown>) => void, opts?: SubscribeOptions): SubscribeHandle;
2707
+ /**
2708
+ * Passive capture — send subagent or pipeline output to Mnemosyne for
2709
+ * automatic fact extraction.
2710
+ *
2711
+ * The server extracts 0-3 durable facts from `content`. When an LLM is
2712
+ * configured server-side it uses guided extraction; otherwise regex
2713
+ * heuristics detect decision/bugfix/config patterns. Identical content
2714
+ * within the same workspace is deduplicated via content-hash.
2715
+ *
2716
+ * Designed for fire-and-forget use from Claude Code hooks:
2717
+ * ```ts
2718
+ * await client.capture({ content: agentStdout, source: "subagent-stop" });
2719
+ * ```
2720
+ *
2721
+ * Maps to `POST /v1/capture`.
2722
+ */
2723
+ capture(opts: {
2724
+ content: string;
2725
+ source: string;
2726
+ }, signal?: AbortSignal): Promise<{
2727
+ extracted: number;
2728
+ skipped: number;
2729
+ }>;
2730
+ /**
2731
+ * Hard-delete a single fact by ID (GDPR / test-workspace cleanup).
2732
+ *
2733
+ * Performs a physical DELETE on `mnemo_fact`. The row is permanently removed —
2734
+ * this bypasses the bitemporal model and cannot be undone. Use only in
2735
+ * test workspaces or when legally required.
2736
+ *
2737
+ * Requires `memory:hard_delete` scope on the API key. Returns 403 when the
2738
+ * key lacks that scope.
2739
+ *
2740
+ * Maps to `DELETE /v1/facts/:id/hard`.
2741
+ */
2742
+ purgeFact(id: string, signal?: AbortSignal): Promise<PurgeFactResponse>;
2743
+ /**
2744
+ * Bulk hard-delete all closed (forgotten) facts in the workspace.
2745
+ *
2746
+ * Deletes every fact whose `status = 'forgotten'` (i.e. facts that were
2747
+ * soft-deleted via `memory_forget`). Useful for reclaiming space in test
2748
+ * workspaces after a test run.
2749
+ *
2750
+ * Requires `memory:hard_delete` scope on the API key. Returns 403 when the
2751
+ * key lacks that scope.
2752
+ *
2753
+ * Maps to `DELETE /v1/facts/purge`.
2754
+ */
2755
+ purgeClosedFacts(signal?: AbortSignal): Promise<PurgeClosedFactsResponse>;
2756
+ /**
2757
+ * List API keys for the current workspace.
2758
+ * Requires `admin:keys` scope.
2759
+ */
2760
+ listKeys(options?: {
2761
+ expired?: boolean;
2762
+ }, signal?: AbortSignal): Promise<{
2763
+ keys: KeyListItem[];
2764
+ }>;
2765
+ /**
2766
+ * Create a new API key for the current workspace.
2767
+ * Plaintext key is returned ONCE in the response.
2768
+ * Requires `admin:keys` scope.
2769
+ */
2770
+ createKey(input: CreateKeyInput, signal?: AbortSignal): Promise<CreateKeyResponse>;
2771
+ /**
2772
+ * Get metadata for a single API key (secret is never returned).
2773
+ * Requires `admin:keys` scope.
2774
+ */
2775
+ getKey(keyId: string, signal?: AbortSignal): Promise<KeyDetailResponse>;
2776
+ /**
2777
+ * Revoke an API key by ID.
2778
+ * Requires `admin:keys` scope.
2779
+ */
2780
+ revokeKey(keyId: string, signal?: AbortSignal): Promise<{
2781
+ ok: boolean;
2782
+ revokedAt: string;
2783
+ }>;
2784
+ /**
2785
+ * Rotate an API key by ID. Generates a new key with 7 days sunset grace for the old key.
2786
+ * Requires `admin:keys` scope.
2787
+ */
2788
+ rotateKey(keyId: string, input?: {
2789
+ reason?: string;
2790
+ }, signal?: AbortSignal): Promise<RotateKeyResponse>;
2791
+ /**
2792
+ * Create a new Skill (stored prompt template).
2793
+ * Maps to `POST /v1/skills`.
2794
+ */
2795
+ createSkill(input: CreateSkillClientInput, signal?: AbortSignal): Promise<SkillWire>;
2796
+ /**
2797
+ * List skills for the current workspace.
2798
+ * Maps to `GET /v1/skills`.
2799
+ */
2800
+ listSkills(options?: {
2801
+ offset?: number;
2802
+ limit?: number;
2803
+ }, signal?: AbortSignal): Promise<SkillListResponse>;
2804
+ /**
2805
+ * Get a single skill by ID.
2806
+ * Maps to `GET /v1/skills/:id`.
2807
+ */
2808
+ getSkill(id: string, signal?: AbortSignal): Promise<SkillWire>;
2809
+ /**
2810
+ * Delegate a task to another agent, setting delegatedBy and delegatedAt provenance fields.
2811
+ * Maps to `POST /v1/tasks/:id/delegate`.
2812
+ */
2813
+ delegateTask(id: string, input: {
2814
+ assignedTo: string;
2815
+ }, signal?: AbortSignal): Promise<TaskWire>;
2816
+ /**
2817
+ * Create a gRPC/ConnectRPC transport for typed streaming calls.
2818
+ *
2819
+ * **This is a stub.** The real implementation requires the optional peer
2820
+ * dependency `@connectrpc/connect`. Install it with:
2821
+ *
2822
+ * ```sh
2823
+ * npm install @connectrpc/connect @connectrpc/connect-web
2824
+ * ```
2825
+ *
2826
+ * Once installed, replace this stub by importing and returning
2827
+ * `createConnectTransport(...)` from `@connectrpc/connect-web`.
2828
+ *
2829
+ * @throws Error — always, until `@connectrpc/connect` is installed.
2830
+ */
2831
+ createGrpcTransport(): never;
2832
+ }
2833
+
2834
+ /**
2835
+ * Typed error hierarchy for the Mnemosyne client SDK.
2836
+ *
2837
+ * Why a class hierarchy instead of plain Error objects:
2838
+ * - Consumers want to `catch` and branch on cause (timeout vs. server
2839
+ * 500 vs. validation 4xx). Discriminating by string-matching `.message`
2840
+ * is brittle across versions.
2841
+ * - We surface the server's `requestId` so support tickets are
2842
+ * immediately greppable in server logs.
2843
+ * - `code` mirrors the server's machine-readable error code (e.g.
2844
+ * "FACT_NOT_FOUND", "RATE_LIMITED") so retry/auth recovery logic
2845
+ * can be written without parsing English prose.
2846
+ *
2847
+ * All three errors extend `MnemosyneError` so `catch (e) { if (e
2848
+ * instanceof MnemosyneError) ... }` covers the whole surface.
2849
+ */
2850
+ declare class MnemosyneError extends Error {
2851
+ constructor(message: string);
2852
+ }
2853
+ /**
2854
+ * Thrown when the server responded with a non-2xx HTTP status.
2855
+ *
2856
+ * Includes the parsed error body (status, code, message, requestId)
2857
+ * so the caller can:
2858
+ * - Decide whether to retry (5xx vs 4xx)
2859
+ * - Show a useful error to the end-user (message)
2860
+ * - File a bug with the operator (requestId)
2861
+ */
2862
+ declare class MnemosyneAPIError extends MnemosyneError {
2863
+ /** HTTP status code returned by the server (e.g. 404, 429, 500). */
2864
+ readonly status: number;
2865
+ /** Machine-readable error code from the server, when present. */
2866
+ readonly code: string | undefined;
2867
+ /** Server-generated request id for log correlation, when present. */
2868
+ readonly requestId: string | undefined;
2869
+ /** Raw parsed JSON body, in case callers need details we didn't surface. */
2870
+ readonly body: unknown;
2871
+ constructor(opts: {
2872
+ status: number;
2873
+ message: string;
2874
+ code?: string | undefined;
2875
+ requestId?: string | undefined;
2876
+ body?: unknown;
2877
+ });
2878
+ }
2879
+ /**
2880
+ * Thrown when the underlying fetch failed at the transport layer (DNS,
2881
+ * connection refused, TLS error, etc.). NOT thrown for HTTP error
2882
+ * statuses — those are MnemosyneAPIError.
2883
+ *
2884
+ * The retry layer treats this as retryable by default.
2885
+ */
2886
+ declare class MnemosyneNetworkError extends MnemosyneError {
2887
+ /** The original error from fetch (or wherever the failure surfaced). */
2888
+ readonly cause: unknown;
2889
+ constructor(message: string, cause: unknown);
2890
+ }
2891
+ /**
2892
+ * Thrown when a request exceeded its timeout budget.
2893
+ *
2894
+ * Distinct from MnemosyneNetworkError because timeouts often indicate
2895
+ * the server IS working but slow — the retry policy may want to back
2896
+ * off more aggressively rather than hammering with rapid retries.
2897
+ */
2898
+ declare class MnemosyneTimeoutError extends MnemosyneError {
2899
+ /** Configured timeout in milliseconds when the request was abandoned. */
2900
+ readonly timeoutMs: number;
2901
+ constructor(timeoutMs: number);
2902
+ }
2903
+
2904
+ export { type AnticipatedMemory, type AnticipationFeedResponse, type AppendTurnInput, type AppliedFactReplaceResponse, type AppliedNonFactReplaceResponse, type AppliedNonReplaceResponse, type ApprovePeerInput, type ApprovePeerKeyResponse, type Attribution, type AuditEntry, type AuditInput, type AuditResponse, type ChainStepWire, type CitationMemoryKind, type CitationSourceKind, type CollapseSessionInput, type CollapseSessionResponse, type CompositionDryRunResponse, type CompositionRule, type ConflictFact, type ConflictPair, type CreateDecisionInput, type CreateEntityInput, type CreateEventInput, type CreateFactInput, type CreateFactResponse, type CreateHyperedgeInput, type CreateKeyInput, type CreateKeyResponse, type CreateReasoningInput, type CreateRelationInput, type CreateSessionInput, type CreateSessionResponse, type CreateSkillClientInput, type CreateStrategyInput, type CreateTaskInput, type DecisionKind, type DecisionStatus, type DeletePeerResponse, type DerivedInference, type DoctorCheck, type DoctorCheckStatus, type DoctorReport, type EnqueueReviewInput, type EnqueueReviewResponse, type EntityFactsResponse, type EntityKind, type EntityWithCount, type EpisodeWithLinkedFacts, type EventAnnotationWire, type EventWire, type ExportResponse, type Fact, type FactCitationsResponse, type FederationClaim, type FederationItem, type FederationSyncJob, type ForgetResponse, type GraphEdge, type GraphInput, type GraphNode, type GraphResponse, type HealthSnapshot, type HyperedgeWire, type JudgmentStatus, type KeyDetailResponse, type KeyListItem, type ListCitationsInput, type ListCitationsResponse, type ListConflictsResponse, type ListDecisionsInput, type ListDecisionsResponse, type ListEntitiesInput, type ListEntitiesResponse, type ListEntityFactsInput, type ListEpisodesInput, type ListEpisodesResponse, type ListEventsParams, type ListFactsInput, type ListFactsResponse, type ListFederationItemsResponse, type ListHyperedgesParams, type ListPeersResponse, type ListPendingPeersResponse, type ListReasoningParams, type ListRelationsInput, type ListRelationsResponse, type ListReviewInput, type ListReviewResponse, type ListStrategiesParams, type ListTasksParams, type MarkerKind, type MemoryFact, type MemoryFactKind, type MemoryFactScope, type MnemoCitation, type MnemoDecision, type MnemoEntity, type MnemoEpisode, type MnemoRelation, MnemosyneAPIError, MnemosyneClient, type MnemosyneClientOptions, MnemosyneError, MnemosyneNetworkError, MnemosyneTimeoutError, type PaginatedEventsResponse, type PaginatedHyperedgesResponse, type PaginatedReasoningResponse, type PaginatedStrategiesResponse, type PaginatedTasksResponse, type PatchFactInput, type PatchHyperedgeInput, type PatchReasoningInput, type PatchRelationInput, type PatchStrategyInput, type PatchTaskInput, type PeerConfig, type PinResponse, type PinSessionTurnInput, type PurgeClosedFactsResponse, type PurgeFactResponse, type ReasoningFeedbackInput, type ReasoningWire, type RecallHit, type RecallInput, type RecallResponse, type RecordReasoningInput, type RelationKind, type RelationVerb, type ResolveConflictInput, type ResolveConflictResponse, type ResolveFederationConflictBatchInput, type ResolveFederationConflictPairInput, type ResolveFederationConflictResponse, type ResolveReasoningInput, type ResolveReasoningResponse, type ResolveReviewInput, type ResolveReviewResponse, type RestoreFactResponse, type RetryConfig, type ReviewCountResponse, type ReviewQueueRow, type ReviewReason, type ReviewResolution, type RotateKeyResponse, type SelfEditAction, type SelfEditApprovalResponse, type SelfEditReflectionResponse, type SelfEditResponse, type SelfEditTargetKind, type SelfModelAspect, type SelfModelResponse, type SkillListResponse, type SkillWire, type StrategyWire, type SubscribeHandle, type SubscribeOptions, type SupersedeDecisionInput, type TaskWire, type TimelineEvent, type TimelineInput, type TimelineResponse, type TraverseRelationsInput, type TraverseRelationsResponse, type TriggerConsolidationInput, type TriggerConsolidationResponse, type TriggerFederationSyncInput, type TriggerFederationSyncResponse, type UpdateEntityInput };