@z3rno/sdk 0.9.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,1355 +0,0 @@
1
- 'use strict';
2
-
3
- var zod = require('zod');
4
-
5
- // src/errors.ts
6
- var Z3rnoError = class extends Error {
7
- /** HTTP status code returned by the server, if applicable. */
8
- statusCode;
9
- /**
10
- * @param message - Human-readable description of the error.
11
- * @param statusCode - HTTP status code associated with the error, if any.
12
- */
13
- constructor(message, statusCode) {
14
- super(message);
15
- this.name = "Z3rnoError";
16
- this.statusCode = statusCode;
17
- }
18
- };
19
- var AuthenticationError = class extends Z3rnoError {
20
- /**
21
- * @param message - Description of the authentication failure.
22
- */
23
- constructor(message) {
24
- super(message, 401);
25
- this.name = "AuthenticationError";
26
- }
27
- };
28
- var RateLimitError = class extends Z3rnoError {
29
- /** Number of seconds to wait before retrying, per the Retry-After header. */
30
- retryAfter;
31
- /**
32
- * @param message - Description of the rate-limit error.
33
- * @param retryAfter - Seconds to wait before retrying (defaults to 60).
34
- */
35
- constructor(message, retryAfter = 60) {
36
- super(message, 429);
37
- this.name = "RateLimitError";
38
- this.retryAfter = retryAfter;
39
- }
40
- };
41
- var ValidationError = class extends Z3rnoError {
42
- /**
43
- * @param message - Description of the validation failure.
44
- * @param statusCode - HTTP status code (400 or 422, defaults to 400).
45
- */
46
- constructor(message, statusCode = 400) {
47
- super(message, statusCode);
48
- this.name = "ValidationError";
49
- }
50
- };
51
- var NotFoundError = class extends Z3rnoError {
52
- /**
53
- * @param message - Description of what was not found.
54
- */
55
- constructor(message) {
56
- super(message, 404);
57
- this.name = "NotFoundError";
58
- }
59
- };
60
- var ServerError = class extends Z3rnoError {
61
- /**
62
- * @param message - Description of the server error.
63
- * @param statusCode - HTTP status code (defaults to 500).
64
- */
65
- constructor(message, statusCode = 500) {
66
- super(message, statusCode);
67
- this.name = "ServerError";
68
- }
69
- };
70
- var Z3rnoTimeoutError = class extends Z3rnoError {
71
- /** The timeout duration in milliseconds that was exceeded. */
72
- timeout;
73
- /**
74
- * @param message - Description of the timeout.
75
- * @param timeout - The configured timeout value in milliseconds.
76
- */
77
- constructor(message, timeout) {
78
- super(message, void 0);
79
- this.name = "Z3rnoTimeoutError";
80
- this.timeout = timeout;
81
- }
82
- };
83
- var Z3rnoConnectionError = class extends Z3rnoError {
84
- /**
85
- * @param message - Description of the connection failure.
86
- */
87
- constructor(message) {
88
- super(message, void 0);
89
- this.name = "Z3rnoConnectionError";
90
- }
91
- };
92
- var MemoryType = zod.z.enum([
93
- "working",
94
- "episodic",
95
- "semantic",
96
- "procedural"
97
- ]);
98
- var RelationshipType = zod.z.enum([
99
- "derived_from",
100
- "contradicts",
101
- "supports",
102
- "supersedes",
103
- "related_to",
104
- "caused_by"
105
- ]);
106
- var RetrievalStrategy = zod.z.enum([
107
- "AUTO",
108
- "VECTOR",
109
- "LEXICAL",
110
- "GRAPH",
111
- "TRIPLET",
112
- "TRACE",
113
- "TEMPORAL",
114
- "ASK",
115
- "CYPHER"
116
- ]);
117
- zod.z.object({
118
- /** UUID of the agent that owns this memory. */
119
- agentId: zod.z.string().uuid(),
120
- /** The text content to store (1 to 100,000 characters). */
121
- content: zod.z.string().min(1).max(1e5),
122
- /** Category of memory. Defaults to `"episodic"`. */
123
- memoryType: MemoryType.default("episodic"),
124
- /** Optional UUID of the user associated with this memory. */
125
- userId: zod.z.string().uuid().optional(),
126
- /** Arbitrary key-value metadata attached to the memory. */
127
- metadata: zod.z.record(zod.z.unknown()).default({}),
128
- /** Relationships to other memories in the knowledge graph. */
129
- relationships: zod.z.array(
130
- zod.z.object({
131
- /** UUID of the target memory. */
132
- targetMemoryId: zod.z.string().uuid(),
133
- /** Type of relationship to the target memory. */
134
- relationshipType: RelationshipType,
135
- /** Relationship strength from 0 to 1. Defaults to 1.0. */
136
- weight: zod.z.number().min(0).max(1).default(1),
137
- /** Arbitrary metadata for the relationship edge. */
138
- metadata: zod.z.record(zod.z.unknown()).default({})
139
- })
140
- ).default([]),
141
- /** Time-to-live in seconds. Memory auto-deletes after this duration. */
142
- ttlSeconds: zod.z.number().int().positive().optional(),
143
- /** Importance score from 0 to 1. Influences recall ranking. */
144
- importance: zod.z.number().min(0).max(1).optional()
145
- });
146
- zod.z.object({
147
- /** UUID of the agent whose memories to search. */
148
- agentId: zod.z.string().uuid(),
149
- /** Natural-language query for semantic similarity search. */
150
- query: zod.z.string().optional(),
151
- /** Filter results to a specific memory type. */
152
- memoryType: zod.z.string().optional(),
153
- /** Additional metadata filters. */
154
- filters: zod.z.record(zod.z.unknown()).optional(),
155
- /** Maximum number of results to return (1-100, default 10). */
156
- topK: zod.z.number().int().min(1).max(100).default(10),
157
- /** Minimum similarity score threshold (0-1, default 0). */
158
- similarityThreshold: zod.z.number().min(0).max(1).default(0),
159
- /** ISO 8601 timestamp for temporal queries (point-in-time recall). */
160
- asOf: zod.z.string().datetime().optional(),
161
- /** Whether to include soft-deleted memories. */
162
- includeDeleted: zod.z.boolean().default(false),
163
- /**
164
- * Phase C retrieval strategy. `AUTO` (default) lets the server's
165
- * LLM router pick the best fit. See {@link RetrievalStrategy}.
166
- */
167
- strategy: RetrievalStrategy.default("AUTO"),
168
- /**
169
- * Phase C cross-encoder re-ranking. When `true`, the server
170
- * re-ranks the top results via a cross-encoder. Requires the
171
- * `sentence-transformers` extra on the server.
172
- */
173
- rerank: zod.z.boolean().default(false)
174
- });
175
- zod.z.object({
176
- /** UUID of the agent that owns the memories. */
177
- agentId: zod.z.string().uuid(),
178
- /** UUID of a single memory to delete. */
179
- memoryId: zod.z.string().uuid().optional(),
180
- /** UUIDs of multiple memories to delete in one call. */
181
- memoryIds: zod.z.array(zod.z.string().uuid()).optional(),
182
- /** If true, permanently deletes (vs. soft-delete). Defaults to false. */
183
- hardDelete: zod.z.boolean().default(false),
184
- /** If true, also deletes related memories. Defaults to false. */
185
- cascade: zod.z.boolean().default(false),
186
- /** Optional reason for the deletion (stored in audit log). */
187
- reason: zod.z.string().optional()
188
- });
189
- var MemoryResponse = zod.z.object({
190
- /** Unique identifier for this memory. */
191
- id: zod.z.string(),
192
- /** UUID of the owning agent. */
193
- agent_id: zod.z.string(),
194
- /** Text content of the memory. */
195
- content: zod.z.string(),
196
- /** Category of the memory. */
197
- memory_type: zod.z.string(),
198
- /** Server-computed importance score (0-1). */
199
- importance_score: zod.z.number(),
200
- /** Number of times this memory has been recalled. */
201
- recall_count: zod.z.number(),
202
- /** Name of the embedding model used, if any. */
203
- embedding_model: zod.z.string().nullable().optional(),
204
- /** ISO 8601 creation timestamp. */
205
- created_at: zod.z.string(),
206
- /** Arbitrary metadata attached to the memory. */
207
- metadata: zod.z.record(zod.z.unknown()).default({})
208
- });
209
- var RecallResultItem = zod.z.object({
210
- /** Unique identifier of the recalled memory. */
211
- memory_id: zod.z.string(),
212
- /** Text content of the memory. */
213
- content: zod.z.string(),
214
- /** Optional server-generated summary. */
215
- summary: zod.z.string().nullable().optional(),
216
- /** Category of the memory. */
217
- memory_type: zod.z.string(),
218
- /** Cosine similarity to the query (0-1). */
219
- similarity_score: zod.z.number(),
220
- /** Server-computed importance score (0-1). */
221
- importance_score: zod.z.number(),
222
- /** Combined relevance score used for ranking (0-1). */
223
- relevance_score: zod.z.number(),
224
- /** Number of times this memory has been recalled. */
225
- recall_count: zod.z.number(),
226
- /** ISO 8601 creation timestamp. */
227
- created_at: zod.z.string(),
228
- /** Arbitrary metadata attached to the memory. */
229
- metadata: zod.z.record(zod.z.unknown()).default({}),
230
- /**
231
- * Phase C per-source signals — e.g. `{ vector: 0.83, lexical: 0.61 }`.
232
- * Optional so older servers (v0.7.x) keep parsing.
233
- */
234
- score_components: zod.z.record(zod.z.number()).default({})
235
- });
236
- var RecallResponse = zod.z.object({
237
- /** Ranked list of matching memories. */
238
- results: zod.z.array(RecallResultItem),
239
- /** Total number of matches (may exceed `topK`). */
240
- total: zod.z.number(),
241
- /** The query that was searched, if any. */
242
- query: zod.z.string().nullable().optional(),
243
- /** Phase C: strategy that actually ran (after AUTO routing + re-rank). */
244
- strategy_used: zod.z.string().default("VECTOR"),
245
- /** Phase C: AUTO's candidate list (e.g. `["AUTO->GRAPH"]`). */
246
- strategies_considered: zod.z.array(zod.z.string()).default([]),
247
- /** Phase C: whether the cross-encoder re-rank ran. */
248
- reranked: zod.z.boolean().default(false),
249
- /** Phase C: end-to-end recall latency on the server (ms). */
250
- elapsed_ms: zod.z.number().default(0)
251
- });
252
- var ForgetResponse = zod.z.object({
253
- /** Number of memories deleted. */
254
- deleted_count: zod.z.number(),
255
- /** Whether a hard delete was performed. */
256
- hard_deleted: zod.z.boolean(),
257
- /** Number of related memories deleted via cascade. */
258
- cascade_count: zod.z.number(),
259
- /** IDs of all deleted memories. */
260
- memory_ids: zod.z.array(zod.z.string())
261
- });
262
- var AuditEntry = zod.z.object({
263
- /** Auto-incrementing audit entry ID. */
264
- id: zod.z.number(),
265
- /** UUID of the agent, if applicable. */
266
- agent_id: zod.z.string().nullable().optional(),
267
- /** UUID of the user, if applicable. */
268
- user_id: zod.z.string().nullable().optional(),
269
- /** Operation type (e.g., `"store"`, `"recall"`, `"forget"`). */
270
- operation: zod.z.string(),
271
- /** UUID of the affected memory, if applicable. */
272
- memory_id: zod.z.string().nullable().optional(),
273
- /** Memory type of the affected memory, if applicable. */
274
- memory_type: zod.z.string().nullable().optional(),
275
- /** Additional details about the operation. */
276
- details: zod.z.record(zod.z.unknown()).default({}),
277
- /** IP address of the caller, if available. */
278
- ip_address: zod.z.string().nullable().optional(),
279
- /** ISO 8601 timestamp of the operation. */
280
- created_at: zod.z.string()
281
- }).transform((data) => ({
282
- ...data,
283
- /** Alias for `created_at`. Added in v0.8.1 for cross-SDK naming parity. */
284
- timestamp: data.created_at
285
- }));
286
- var AuditPageResponse = zod.z.object({
287
- /** Audit entries on this page. */
288
- entries: zod.z.array(AuditEntry),
289
- /** Total number of matching audit entries. */
290
- total: zod.z.number(),
291
- /** Current page number (1-indexed). */
292
- page: zod.z.number(),
293
- /** Number of entries per page. */
294
- page_size: zod.z.number(),
295
- /** Whether more pages are available. */
296
- has_next: zod.z.boolean()
297
- }).transform((data) => ({
298
- ...data,
299
- /** Alias for `total`. Added in v0.8.1 for cross-SDK naming parity. */
300
- total_count: data.total
301
- }));
302
- var BatchStoreResponse = zod.z.object({
303
- /** Array of stored memory objects. */
304
- results: zod.z.array(MemoryResponse),
305
- /** Number of memories successfully stored. */
306
- stored_count: zod.z.number()
307
- });
308
- var MemoryVersion = zod.z.object({
309
- /** Version identifier. */
310
- id: zod.z.string(),
311
- /** Text content at this version. */
312
- content: zod.z.string(),
313
- /** Memory type at this version. */
314
- memory_type: zod.z.string(),
315
- /** Importance score at this version. */
316
- importance_score: zod.z.number(),
317
- /** ISO 8601 timestamp when this version became active. */
318
- valid_from: zod.z.string(),
319
- /** ISO 8601 timestamp when this version was superseded, or null if current. */
320
- valid_to: zod.z.string().nullable().optional(),
321
- /** Metadata at this version. */
322
- metadata: zod.z.record(zod.z.unknown()).default({})
323
- });
324
- var MemoryHistoryResponse = zod.z.object({
325
- /** UUID of the memory. */
326
- memory_id: zod.z.string(),
327
- /** Chronologically ordered list of versions. */
328
- versions: zod.z.array(MemoryVersion),
329
- /** Total number of versions. */
330
- total: zod.z.number()
331
- });
332
- var SessionResponse = zod.z.object({
333
- /** Unique session identifier. */
334
- session_id: zod.z.string(),
335
- /** UUID of the agent this session belongs to. */
336
- agent_id: zod.z.string(),
337
- /** Type of session (e.g., `"conversation"`). */
338
- session_type: zod.z.string(),
339
- /** ISO 8601 timestamp when the session started. */
340
- started_at: zod.z.string(),
341
- /** Arbitrary session metadata. */
342
- metadata: zod.z.record(zod.z.unknown()).default({})
343
- });
344
- var EndSessionResponse = zod.z.object({
345
- /** The session that was ended. */
346
- session_id: zod.z.string(),
347
- /** ISO 8601 timestamp when the session ended. */
348
- ended_at: zod.z.string(),
349
- /** Total duration of the session in seconds. */
350
- duration_seconds: zod.z.number(),
351
- /** Number of memories created during the session. */
352
- memory_count: zod.z.number()
353
- });
354
- var IngestJobResponse = zod.z.object({
355
- job_id: zod.z.string(),
356
- kind: zod.z.string(),
357
- status: zod.z.string(),
358
- dataset_id: zod.z.string().nullable().optional(),
359
- enqueued_at: zod.z.string()
360
- });
361
- var IngestJobStatusResponse = zod.z.object({
362
- job_id: zod.z.string(),
363
- agent_id: zod.z.string(),
364
- dataset_id: zod.z.string().nullable().optional(),
365
- kind: zod.z.string(),
366
- status: zod.z.string(),
367
- source_uri: zod.z.string().nullable().optional(),
368
- content_type: zod.z.string().nullable().optional(),
369
- filename: zod.z.string().nullable().optional(),
370
- file_size: zod.z.number().nullable().optional(),
371
- memory_ids: zod.z.array(zod.z.string()).default([]),
372
- memos_written: zod.z.number().default(0),
373
- distill_job_id: zod.z.string().nullable().optional(),
374
- codegraph_memos_written: zod.z.number().default(0),
375
- codegraph_edges_written: zod.z.number().default(0),
376
- error: zod.z.string().nullable().optional(),
377
- warnings: zod.z.array(zod.z.record(zod.z.unknown())).default([]),
378
- started_at: zod.z.string().nullable().optional(),
379
- completed_at: zod.z.string().nullable().optional(),
380
- created_at: zod.z.string().nullable().optional(),
381
- updated_at: zod.z.string().nullable().optional()
382
- });
383
- var DistillJobResponse = zod.z.object({
384
- job_id: zod.z.string(),
385
- status: zod.z.string(),
386
- memory_ids: zod.z.array(zod.z.string()),
387
- enqueued_at: zod.z.string()
388
- });
389
- var DistillJobStatusResponse = zod.z.object({
390
- job_id: zod.z.string(),
391
- agent_id: zod.z.string(),
392
- status: zod.z.string(),
393
- model: zod.z.string(),
394
- memory_ids: zod.z.array(zod.z.string()),
395
- chunk_size: zod.z.number(),
396
- chunk_overlap: zod.z.number(),
397
- max_concurrency: zod.z.number(),
398
- chunks_total: zod.z.number(),
399
- chunks_failed: zod.z.number(),
400
- entities_extracted: zod.z.number(),
401
- relationships_extracted: zod.z.number(),
402
- memos_written: zod.z.number(),
403
- error: zod.z.string().nullable().optional(),
404
- started_at: zod.z.string().nullable().optional(),
405
- completed_at: zod.z.string().nullable().optional(),
406
- created_at: zod.z.string().nullable().optional(),
407
- updated_at: zod.z.string().nullable().optional()
408
- });
409
- var RefineJobResponse = zod.z.object({
410
- job_id: zod.z.string(),
411
- status: zod.z.string(),
412
- dataset_id: zod.z.string().nullable().optional(),
413
- enqueued_at: zod.z.string()
414
- });
415
- var RefineJobStatusResponse = zod.z.object({
416
- job_id: zod.z.string(),
417
- status: zod.z.string(),
418
- dataset_id: zod.z.string().nullable().optional(),
419
- trigger: zod.z.string(),
420
- memos_scanned: zod.z.number().default(0),
421
- memos_deduped: zod.z.number().default(0),
422
- edges_reweighted: zod.z.number().default(0),
423
- edges_pruned: zod.z.number().default(0),
424
- feedback_drained: zod.z.number().default(0),
425
- job_metadata: zod.z.record(zod.z.unknown()).default({}),
426
- error: zod.z.string().nullable().optional(),
427
- started_at: zod.z.string().nullable().optional(),
428
- completed_at: zod.z.string().nullable().optional(),
429
- created_at: zod.z.string().nullable().optional(),
430
- updated_at: zod.z.string().nullable().optional()
431
- });
432
- var ConversationResponse = zod.z.object({
433
- id: zod.z.string(),
434
- agent_id: zod.z.string(),
435
- user_id: zod.z.string().nullable().optional(),
436
- title: zod.z.string().nullable().optional(),
437
- summary_cadence: zod.z.number(),
438
- turn_count: zod.z.number(),
439
- last_summary_turn: zod.z.number(),
440
- metadata: zod.z.record(zod.z.unknown()).default({}),
441
- created_at: zod.z.string(),
442
- updated_at: zod.z.string()
443
- });
444
- var TurnAddResponse = zod.z.object({
445
- turn_index: zod.z.number(),
446
- needs_summary: zod.z.boolean()
447
- });
448
- var TurnResponse = zod.z.object({
449
- memory_id: zod.z.string(),
450
- turn_index: zod.z.number(),
451
- turn_role: zod.z.string(),
452
- content: zod.z.string(),
453
- created_at: zod.z.string()
454
- });
455
- var TurnListResponse = zod.z.object({
456
- turns: zod.z.array(TurnResponse),
457
- total: zod.z.number(),
458
- conversation_id: zod.z.string()
459
- });
460
- var TenantBudgets = zod.z.object({
461
- daily_tokens: zod.z.number(),
462
- daily_llm_calls: zod.z.number(),
463
- daily_embeddings: zod.z.number(),
464
- monthly_tokens: zod.z.number(),
465
- monthly_llm_calls: zod.z.number(),
466
- monthly_embeddings: zod.z.number()
467
- });
468
- var TenantBudgetsView = zod.z.object({
469
- overrides: TenantBudgets,
470
- effective: TenantBudgets
471
- });
472
-
473
- // src/client.ts
474
- var Z3rnoClient = class {
475
- baseUrl;
476
- apiKey;
477
- timeout;
478
- maxRetries;
479
- fetchImpl;
480
- onRequest;
481
- onResponse;
482
- /**
483
- * Creates a new Z3rno client instance.
484
- *
485
- * @param config - Client configuration options. All fields are optional.
486
- *
487
- * @example
488
- * ```ts
489
- * // Explicit configuration
490
- * const client = new Z3rnoClient({
491
- * baseUrl: "http://localhost:8000",
492
- * apiKey: "z3rno_sk_test_...",
493
- * timeout: 10000,
494
- * maxRetries: 2,
495
- * });
496
- *
497
- * // Or rely on environment variables (Z3RNO_BASE_URL, Z3RNO_API_KEY)
498
- * const client = new Z3rnoClient();
499
- * ```
500
- */
501
- constructor(config = {}) {
502
- let resolvedUrl = config.baseUrl ?? "";
503
- if (!resolvedUrl && typeof process !== "undefined" && process.env) {
504
- resolvedUrl = process.env.Z3RNO_BASE_URL ?? "";
505
- }
506
- if (!resolvedUrl) {
507
- resolvedUrl = "https://api.z3rno.dev";
508
- }
509
- this.baseUrl = resolvedUrl.replace(/\/$/, "");
510
- let resolvedKey = config.apiKey ?? "";
511
- if (!resolvedKey && typeof process !== "undefined" && process.env) {
512
- resolvedKey = process.env.Z3RNO_API_KEY ?? "";
513
- }
514
- this.apiKey = resolvedKey;
515
- this.timeout = config.timeout ?? 3e4;
516
- this.maxRetries = config.maxRetries ?? 3;
517
- this.fetchImpl = config.fetch ?? globalThis.fetch;
518
- this.onRequest = config.onRequest;
519
- this.onResponse = config.onResponse;
520
- }
521
- // --- Store ---
522
- /**
523
- * Stores a new memory for an agent.
524
- *
525
- * The server generates an embedding for the content and stores it in
526
- * the vector database. The memory is immediately available for recall.
527
- *
528
- * @param request - The memory to store.
529
- * @returns The stored memory, including the server-generated ID and scores.
530
- * @throws {@link AuthenticationError} If the API key is invalid.
531
- * @throws {@link ValidationError} If the request body is invalid.
532
- * @throws {@link Z3rnoTimeoutError} If the request times out.
533
- *
534
- * @example
535
- * ```ts
536
- * const memory = await client.store({
537
- * agentId: "550e8400-e29b-41d4-a716-446655440000",
538
- * content: "User prefers dark mode",
539
- * memoryType: "semantic",
540
- * metadata: { source: "settings-page" },
541
- * });
542
- * console.log(memory.id); // "mem-abc123"
543
- * ```
544
- */
545
- async store(request) {
546
- const body = {
547
- agent_id: request.agentId,
548
- content: request.content,
549
- memory_type: request.memoryType,
550
- user_id: request.userId,
551
- metadata: request.metadata,
552
- relationships: request.relationships?.map((r) => ({
553
- target_memory_id: r.targetMemoryId,
554
- relationship_type: r.relationshipType,
555
- weight: r.weight,
556
- metadata: r.metadata
557
- })),
558
- ttl_seconds: request.ttlSeconds,
559
- importance: request.importance
560
- };
561
- const resp = await this.request("POST", "/v1/memories", body);
562
- return MemoryResponse.parse(resp);
563
- }
564
- // --- Recall ---
565
- /**
566
- * Recalls memories by semantic similarity to a query.
567
- *
568
- * Returns a ranked list of memories sorted by a combined relevance score
569
- * that factors in similarity, importance, and recency.
570
- *
571
- * @param params - Recall parameters including the query and filters.
572
- * @param params.agentId - UUID of the agent whose memories to search.
573
- * @param params.query - Natural-language query for semantic search.
574
- * @param params.memoryType - Filter by memory type.
575
- * @param params.filters - Additional metadata filters.
576
- * @param params.topK - Maximum results to return (default 10).
577
- * @param params.similarityThreshold - Minimum similarity score (default 0).
578
- * @returns Ranked recall results with similarity scores.
579
- * @throws {@link AuthenticationError} If the API key is invalid.
580
- * @throws {@link Z3rnoTimeoutError} If the request times out.
581
- *
582
- * @example
583
- * ```ts
584
- * const results = await client.recall({
585
- * agentId: "550e8400-e29b-41d4-a716-446655440000",
586
- * query: "user preferences",
587
- * topK: 5,
588
- * similarityThreshold: 0.7,
589
- * });
590
- * for (const item of results.results) {
591
- * console.log(`${item.content} (score: ${item.relevance_score})`);
592
- * }
593
- * ```
594
- */
595
- async recall(params) {
596
- let metadataFilter = params.metadataFilter;
597
- if (params.filters !== void 0 && metadataFilter === void 0) {
598
- if (typeof console !== "undefined" && console.warn) {
599
- console.warn(
600
- "Z3rnoClient.recall({filters}) is deprecated; use {metadataFilter} instead."
601
- );
602
- }
603
- metadataFilter = params.filters;
604
- }
605
- const body = {
606
- agent_id: params.agentId,
607
- query: params.query,
608
- memory_type: params.memoryType,
609
- metadata_filter: metadataFilter,
610
- top_k: params.topK ?? 10,
611
- similarity_threshold: params.similarityThreshold ?? 0,
612
- // Always send strategy + rerank. Older servers silently ignore
613
- // unknown body fields.
614
- strategy: params.strategy ?? "AUTO",
615
- rerank: params.rerank ?? false
616
- };
617
- if (params.userId) {
618
- body.user_id = params.userId;
619
- }
620
- if (params.conversationId) {
621
- body.conversation_id = params.conversationId;
622
- }
623
- const resp = await this.request("POST", "/v1/memories/recall", body);
624
- return RecallResponse.parse(resp);
625
- }
626
- // --- Forget ---
627
- /**
628
- * Forgets (deletes) one or more memories.
629
- *
630
- * By default, performs a soft delete (marks as deleted but retains data).
631
- * Set `hardDelete: true` for permanent removal. Use `cascade: true` to
632
- * also delete related memories in the knowledge graph.
633
- *
634
- * @param params - Forget parameters.
635
- * @param params.agentId - UUID of the agent that owns the memories.
636
- * @param params.memoryId - UUID of a single memory to delete.
637
- * @param params.memoryIds - UUIDs of multiple memories to delete.
638
- * @param params.hardDelete - Permanently delete (default false).
639
- * @param params.cascade - Delete related memories too (default false).
640
- * @param params.reason - Reason for deletion (stored in audit log).
641
- * @returns Summary of the deletion operation.
642
- * @throws {@link AuthenticationError} If the API key is invalid.
643
- * @throws {@link NotFoundError} If the specified memory does not exist.
644
- *
645
- * @example
646
- * ```ts
647
- * const result = await client.forget({
648
- * agentId: "550e8400-e29b-41d4-a716-446655440000",
649
- * memoryId: "mem-abc123",
650
- * hardDelete: true,
651
- * reason: "User requested data deletion",
652
- * });
653
- * console.log(`Deleted ${result.deleted_count} memories`);
654
- * ```
655
- */
656
- async forget(params) {
657
- const body = {
658
- agent_id: params.agentId,
659
- memory_id: params.memoryId,
660
- memory_ids: params.memoryIds,
661
- hard_delete: params.hardDelete ?? false,
662
- cascade: params.cascade ?? false,
663
- reason: params.reason
664
- };
665
- const resp = await this.request("POST", "/v1/memories/forget", body);
666
- return ForgetResponse.parse(resp);
667
- }
668
- // --- Get Memory ---
669
- /**
670
- * Retrieves a single memory by its ID.
671
- *
672
- * @param memoryId - The unique identifier of the memory to retrieve.
673
- * @returns The full memory object.
674
- * @throws {@link NotFoundError} If no memory exists with the given ID.
675
- * @throws {@link AuthenticationError} If the API key is invalid.
676
- *
677
- * @example
678
- * ```ts
679
- * const memory = await client.getMemory("mem-abc123");
680
- * console.log(memory.content);
681
- * console.log(memory.importance_score);
682
- * ```
683
- */
684
- async getMemory(memoryId) {
685
- const resp = await this.request("GET", `/v1/memories/${memoryId}`);
686
- return MemoryResponse.parse(resp);
687
- }
688
- // --- Store Batch ---
689
- /**
690
- * Stores multiple memories in a single API call.
691
- *
692
- * More efficient than calling {@link store} in a loop. All memories are
693
- * processed atomically on the server.
694
- *
695
- * @param memories - Array of memories to store.
696
- * @returns The stored memories and a count of how many were created.
697
- * @throws {@link ValidationError} If any memory in the batch is invalid.
698
- * @throws {@link AuthenticationError} If the API key is invalid.
699
- *
700
- * @example
701
- * ```ts
702
- * const result = await client.storeBatch([
703
- * { agentId: "agent-1", content: "Fact one" },
704
- * { agentId: "agent-1", content: "Fact two", memoryType: "semantic" },
705
- * ]);
706
- * console.log(`Stored ${result.stored_count} memories`);
707
- * ```
708
- */
709
- async storeBatch(memories) {
710
- const body = {
711
- memories: memories.map((m) => ({
712
- agent_id: m.agentId,
713
- content: m.content,
714
- memory_type: m.memoryType,
715
- metadata: m.metadata,
716
- importance: m.importance
717
- }))
718
- };
719
- const resp = await this.request("POST", "/v1/memories/batch", body);
720
- return BatchStoreResponse.parse(resp);
721
- }
722
- // --- Memory History ---
723
- /**
724
- * Retrieves the full version history of a memory.
725
- *
726
- * Z3rno uses temporal versioning — every update creates a new version
727
- * rather than overwriting. This method returns all versions ordered
728
- * chronologically.
729
- *
730
- * @param memoryId - The unique identifier of the memory.
731
- * @returns All versions of the memory with validity timestamps.
732
- * @throws {@link NotFoundError} If no memory exists with the given ID.
733
- * @throws {@link AuthenticationError} If the API key is invalid.
734
- *
735
- * @example
736
- * ```ts
737
- * const history = await client.getMemoryHistory("mem-abc123");
738
- * for (const version of history.versions) {
739
- * console.log(`${version.valid_from}: ${version.content}`);
740
- * }
741
- * ```
742
- */
743
- async getMemoryHistory(memoryId) {
744
- const resp = await this.request("GET", `/v1/memories/${memoryId}/history`);
745
- return MemoryHistoryResponse.parse(resp);
746
- }
747
- // --- Update Memory ---
748
- /**
749
- * Updates an existing memory's content, metadata, or importance.
750
- *
751
- * Creates a new temporal version of the memory. The previous version
752
- * remains accessible via {@link getMemoryHistory}.
753
- *
754
- * @param memoryId - The unique identifier of the memory to update.
755
- * @param updates - Fields to update (only provided fields are changed).
756
- * @param updates.content - New text content.
757
- * @param updates.metadata - New metadata (replaces existing metadata).
758
- * @param updates.importance - New importance score (0-1).
759
- * @returns The updated memory object.
760
- * @throws {@link NotFoundError} If no memory exists with the given ID.
761
- * @throws {@link ValidationError} If the update values are invalid.
762
- * @throws {@link AuthenticationError} If the API key is invalid.
763
- *
764
- * @example
765
- * ```ts
766
- * const updated = await client.updateMemory("mem-abc123", {
767
- * content: "User now prefers light mode",
768
- * importance: 0.9,
769
- * });
770
- * ```
771
- */
772
- async updateMemory(memoryId, updates) {
773
- const body = {};
774
- if (updates.content !== void 0) body.content = updates.content;
775
- if (updates.metadata !== void 0) body.metadata = updates.metadata;
776
- if (updates.importance !== void 0) body.importance = updates.importance;
777
- const resp = await this.request("PATCH", `/v1/memories/${memoryId}`, body);
778
- return MemoryResponse.parse(resp);
779
- }
780
- // --- Sessions ---
781
- /**
782
- * Starts a new session for grouping related memory operations.
783
- *
784
- * Sessions are useful for tracking conversation turns or task boundaries.
785
- * Memories created during a session are automatically associated with it.
786
- *
787
- * @param params - Session parameters.
788
- * @param params.agentId - UUID of the agent to start the session for.
789
- * @param params.sessionType - Type of session (default `"conversation"`).
790
- * @returns The created session with its ID and start time.
791
- * @throws {@link AuthenticationError} If the API key is invalid.
792
- *
793
- * @example
794
- * ```ts
795
- * const session = await client.startSession({ agentId: "agent-1" });
796
- * console.log(`Session started: ${session.session_id}`);
797
- * // ... perform operations ...
798
- * await client.endSession(session.session_id);
799
- * ```
800
- */
801
- async startSession(params) {
802
- const body = {
803
- agent_id: params.agentId,
804
- session_type: params.sessionType ?? "conversation"
805
- };
806
- const resp = await this.request("POST", "/v1/sessions", body);
807
- return SessionResponse.parse(resp);
808
- }
809
- /**
810
- * Ends an active session.
811
- *
812
- * Returns summary statistics including the session duration and the
813
- * number of memories created during the session.
814
- *
815
- * @param sessionId - The unique identifier of the session to end.
816
- * @returns Session summary with duration and memory count.
817
- * @throws {@link NotFoundError} If no active session exists with the given ID.
818
- * @throws {@link AuthenticationError} If the API key is invalid.
819
- *
820
- * @example
821
- * ```ts
822
- * const summary = await client.endSession("sess-abc123");
823
- * console.log(`Session lasted ${summary.duration_seconds}s, ${summary.memory_count} memories`);
824
- * ```
825
- */
826
- async endSession(sessionId) {
827
- const resp = await this.request("POST", `/v1/sessions/${sessionId}/end`);
828
- return EndSessionResponse.parse(resp);
829
- }
830
- // --- Audit ---
831
- /**
832
- * Retrieves a paginated audit log of memory operations.
833
- *
834
- * The audit log records every store, recall, forget, and update operation
835
- * performed by any agent. Useful for compliance, debugging, and analytics.
836
- *
837
- * @param params - Optional pagination and filter parameters.
838
- * @param params.agentId - Filter by agent UUID.
839
- * @param params.page - Page number (1-indexed).
840
- * @param params.pageSize - Number of entries per page.
841
- * @returns A page of audit log entries with pagination metadata.
842
- * @throws {@link AuthenticationError} If the API key is invalid.
843
- *
844
- * @example
845
- * ```ts
846
- * const page = await client.audit({ agentId: "agent-1", page: 1, pageSize: 20 });
847
- * for (const entry of page.entries) {
848
- * console.log(`${entry.created_at}: ${entry.operation} on ${entry.memory_id}`);
849
- * }
850
- * if (page.has_next) {
851
- * const nextPage = await client.audit({ agentId: "agent-1", page: 2 });
852
- * }
853
- * ```
854
- */
855
- async audit(params) {
856
- const searchParams = new URLSearchParams();
857
- if (params?.agentId) searchParams.set("agent_id", params.agentId);
858
- if (params?.page) searchParams.set("page", String(params.page));
859
- if (params?.pageSize)
860
- searchParams.set("page_size", String(params.pageSize));
861
- const query = searchParams.toString();
862
- const path = query ? `/v1/audit?${query}` : "/v1/audit";
863
- const resp = await this.request("GET", path);
864
- return AuditPageResponse.parse(resp);
865
- }
866
- // --- Forge: ingest / distill / refine -------------------------------
867
- //
868
- // Wrap the server's POST /v1/ingest, /v1/distill, /v1/refine plus the
869
- // matching GET status endpoints. The server gates each verb behind an
870
- // operator flag (INGEST_ENABLED / DISTILL_ENABLED / REFINE_ENABLED);
871
- // when off, these methods throw NotFoundError.
872
- async ingestText(params) {
873
- const body = {
874
- kind: "text",
875
- agent_id: params.agentId,
876
- text: params.text
877
- };
878
- if (params.datasetId) body.dataset_id = params.datasetId;
879
- const resp = await this.request("POST", "/v1/ingest", body);
880
- return IngestJobResponse.parse(resp);
881
- }
882
- async ingestUrl(params) {
883
- const body = {
884
- kind: "url",
885
- agent_id: params.agentId,
886
- url: params.url
887
- };
888
- if (params.datasetId) body.dataset_id = params.datasetId;
889
- const resp = await this.request("POST", "/v1/ingest", body);
890
- return IngestJobResponse.parse(resp);
891
- }
892
- async getIngestStatus(jobId) {
893
- const resp = await this.request("GET", `/v1/ingest/${jobId}`);
894
- return IngestJobStatusResponse.parse(resp);
895
- }
896
- async distill(params) {
897
- const body = {
898
- agent_id: params.agentId,
899
- memory_ids: params.memoryIds,
900
- include_summary: params.includeSummary ?? true
901
- };
902
- if (params.chunkSize !== void 0) body.chunk_size = params.chunkSize;
903
- if (params.chunkOverlap !== void 0)
904
- body.chunk_overlap = params.chunkOverlap;
905
- if (params.maxConcurrency !== void 0)
906
- body.max_concurrency = params.maxConcurrency;
907
- if (params.summaryStyle !== void 0)
908
- body.summary_style = params.summaryStyle;
909
- const resp = await this.request("POST", "/v1/distill", body);
910
- return DistillJobResponse.parse(resp);
911
- }
912
- async getDistillStatus(jobId) {
913
- const resp = await this.request("GET", `/v1/distill/${jobId}`);
914
- return DistillJobStatusResponse.parse(resp);
915
- }
916
- async refine(params) {
917
- const body = {};
918
- if (params?.datasetId) body.dataset_id = params.datasetId;
919
- const resp = await this.request("POST", "/v1/refine", body);
920
- return RefineJobResponse.parse(resp);
921
- }
922
- async getRefineStatus(jobId) {
923
- const resp = await this.request("GET", `/v1/refine/${jobId}`);
924
- return RefineJobStatusResponse.parse(resp);
925
- }
926
- // --- Conversations (Phase G slice 2) ---
927
- /**
928
- * Open a new conversation. Returns the conversation row including
929
- * the assigned `id`, which subsequent `recall`s and `addTurn`s
930
- * reference. The `summaryCadence` controls how often the server
931
- * flags the conversation for summarization.
932
- */
933
- async createConversation(params) {
934
- const body = {
935
- agent_id: params.agentId,
936
- summary_cadence: params.summaryCadence ?? 10
937
- };
938
- if (params.userId) body.user_id = params.userId;
939
- if (params.title) body.title = params.title;
940
- if (params.metadata) body.metadata = params.metadata;
941
- const resp = await this.request("POST", "/v1/conversations", body);
942
- return ConversationResponse.parse(resp);
943
- }
944
- async getConversation(conversationId) {
945
- const resp = await this.request("GET", `/v1/conversations/${conversationId}`);
946
- return ConversationResponse.parse(resp);
947
- }
948
- /**
949
- * Stamp an existing Memo as the next turn of the conversation.
950
- * Returns the assigned `turn_index` plus `needs_summary` — when
951
- * `true`, the conversation has crossed its cadence threshold.
952
- */
953
- async addTurn(conversationId, params) {
954
- const resp = await this.request(
955
- "POST",
956
- `/v1/conversations/${conversationId}/turns`,
957
- { memory_id: params.memoryId, turn_role: params.turnRole }
958
- );
959
- return TurnAddResponse.parse(resp);
960
- }
961
- /**
962
- * v0.19.3 — soft-delete a conversation. Existing turn Memos stay
963
- * queryable through standard recall; the conversation itself stops
964
- * accepting turns and its endpoints 404. Idempotent.
965
- */
966
- async deleteConversation(conversationId) {
967
- await this.request("DELETE", `/v1/conversations/${conversationId}`);
968
- }
969
- async listTurns(conversationId, params) {
970
- const query = new URLSearchParams();
971
- if (params?.afterTurn !== void 0)
972
- query.set("after_turn", String(params.afterTurn));
973
- query.set("limit", String(params?.limit ?? 50));
974
- const path = `/v1/conversations/${conversationId}/turns?${query.toString()}`;
975
- const resp = await this.request("GET", path);
976
- return TurnListResponse.parse(resp);
977
- }
978
- // --- Tenant budgets (v0.20.3) ---
979
- /**
980
- * Cross-tenant admin sub-namespace (v0.22.1, slice 21.3).
981
- *
982
- * Pairs with z3rno-server v0.22.1's `/v1/tenants/{orgId}/budgets`
983
- * surface. Requires `SUPERADMIN_ENABLED=true` on the server and
984
- * the client to be configured with the matching superadmin API
985
- * key. Methods raise `AuthenticationError` (401) or a generic
986
- * `Z3rnoError` (403) otherwise.
987
- */
988
- get admin() {
989
- return new AdminAPI(this.request.bind(this));
990
- }
991
- /**
992
- * Read this org's stored budget overrides + resolved effective caps.
993
- * Auth: any admin/write/read member of the calling org.
994
- */
995
- async getMyBudgets() {
996
- const resp = await this.request("GET", "/v1/tenants/me/budgets");
997
- return TenantBudgetsView.parse(resp);
998
- }
999
- /**
1000
- * Replace this org's budget overrides. Zero / missing fields
1001
- * inherit the server default. Auth: admin/write only.
1002
- */
1003
- async setMyBudgets(budgets) {
1004
- const body = {
1005
- daily_tokens: budgets.daily_tokens ?? 0,
1006
- daily_llm_calls: budgets.daily_llm_calls ?? 0,
1007
- daily_embeddings: budgets.daily_embeddings ?? 0,
1008
- monthly_tokens: budgets.monthly_tokens ?? 0,
1009
- monthly_llm_calls: budgets.monthly_llm_calls ?? 0,
1010
- monthly_embeddings: budgets.monthly_embeddings ?? 0
1011
- };
1012
- const resp = await this.request("PUT", "/v1/tenants/me/budgets", body);
1013
- return TenantBudgetsView.parse(resp);
1014
- }
1015
- // --- HTTP layer ---
1016
- async request(method, path, body) {
1017
- let lastError;
1018
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1019
- const controller = new AbortController();
1020
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1021
- try {
1022
- const url = `${this.baseUrl}${path}`;
1023
- let init = {
1024
- method,
1025
- headers: {
1026
- Authorization: `Bearer ${this.apiKey}`,
1027
- "Content-Type": "application/json",
1028
- "User-Agent": "@z3rno/sdk/0.0.1"
1029
- },
1030
- body: body ? JSON.stringify(body) : void 0,
1031
- signal: controller.signal
1032
- };
1033
- if (this.onRequest) {
1034
- init = this.onRequest(url, init);
1035
- }
1036
- let response = await this.fetchImpl(url, init);
1037
- if (this.onResponse) {
1038
- response = this.onResponse(response);
1039
- }
1040
- clearTimeout(timeoutId);
1041
- if (response.status === 429 && attempt < this.maxRetries) {
1042
- const retryAfter = parseInt(
1043
- response.headers.get("Retry-After") ?? "1",
1044
- 10
1045
- );
1046
- await this.sleep(retryAfter * 1e3);
1047
- continue;
1048
- }
1049
- if (response.status >= 500 && attempt < this.maxRetries) {
1050
- const delay = Math.pow(2, attempt) * 1e3;
1051
- await this.sleep(delay);
1052
- continue;
1053
- }
1054
- return this.handleResponse(response);
1055
- } catch (error) {
1056
- clearTimeout(timeoutId);
1057
- if (error instanceof Z3rnoError) throw error;
1058
- if (error instanceof DOMException && error.name === "AbortError") {
1059
- lastError = new Z3rnoTimeoutError(
1060
- `Request timed out after ${this.timeout}ms`,
1061
- this.timeout
1062
- );
1063
- } else if (error instanceof TypeError) {
1064
- lastError = new Z3rnoConnectionError(
1065
- `Connection failed: ${error.message}`
1066
- );
1067
- } else {
1068
- lastError = error instanceof Error ? error : new Error(String(error));
1069
- }
1070
- if (attempt < this.maxRetries) {
1071
- const delay = Math.pow(2, attempt) * 1e3;
1072
- await this.sleep(delay);
1073
- continue;
1074
- }
1075
- }
1076
- }
1077
- if (lastError instanceof Z3rnoError) {
1078
- throw lastError;
1079
- }
1080
- throw new Z3rnoError(
1081
- `Request failed after ${this.maxRetries + 1} attempts: ${String(lastError)}`
1082
- );
1083
- }
1084
- sleep(ms) {
1085
- return new Promise((resolve) => setTimeout(resolve, ms));
1086
- }
1087
- async handleResponse(resp) {
1088
- if (resp.ok) {
1089
- if (resp.status === 204) {
1090
- return void 0;
1091
- }
1092
- return resp.json();
1093
- }
1094
- let detail = resp.statusText;
1095
- try {
1096
- const text = await resp.text();
1097
- try {
1098
- const body = JSON.parse(text);
1099
- detail = String(body.detail ?? body.error ?? resp.statusText);
1100
- } catch {
1101
- if (text.length > 0) {
1102
- const preview = text.length > 200 ? text.slice(0, 200) + "..." : text;
1103
- detail = `${resp.statusText} \u2014 ${preview}`;
1104
- }
1105
- }
1106
- } catch {
1107
- }
1108
- switch (resp.status) {
1109
- case 401:
1110
- throw new AuthenticationError(`Authentication failed: ${detail}`);
1111
- case 404:
1112
- throw new NotFoundError(`Not found: ${detail}`);
1113
- case 429: {
1114
- const retryAfter = parseInt(
1115
- resp.headers.get("Retry-After") ?? "60",
1116
- 10
1117
- );
1118
- throw new RateLimitError(`Rate limit exceeded: ${detail}`, retryAfter);
1119
- }
1120
- case 400:
1121
- case 422:
1122
- throw new ValidationError(detail, resp.status);
1123
- default:
1124
- if (resp.status >= 500) {
1125
- throw new ServerError(`Server error: ${detail}`, resp.status);
1126
- }
1127
- throw new Z3rnoError(
1128
- `Unexpected error (${resp.status}): ${detail}`,
1129
- resp.status
1130
- );
1131
- }
1132
- }
1133
- };
1134
- var AdminAPI = class {
1135
- constructor(request) {
1136
- this.request = request;
1137
- }
1138
- request;
1139
- /**
1140
- * Read another tenant's budget overrides + effective caps.
1141
- *
1142
- * Requires `SUPERADMIN_ENABLED=true` server-side and the client to
1143
- * be configured with the superadmin API key.
1144
- */
1145
- async getBudgets(orgId) {
1146
- const resp = await this.request("GET", `/v1/tenants/${orgId}/budgets`);
1147
- return TenantBudgetsView.parse(resp);
1148
- }
1149
- /**
1150
- * Replace another tenant's budget overrides. Zero / missing fields
1151
- * inherit the server default.
1152
- */
1153
- async setBudgets(orgId, budgets) {
1154
- const body = {
1155
- daily_tokens: budgets.daily_tokens ?? 0,
1156
- daily_llm_calls: budgets.daily_llm_calls ?? 0,
1157
- daily_embeddings: budgets.daily_embeddings ?? 0,
1158
- monthly_tokens: budgets.monthly_tokens ?? 0,
1159
- monthly_llm_calls: budgets.monthly_llm_calls ?? 0,
1160
- monthly_embeddings: budgets.monthly_embeddings ?? 0
1161
- };
1162
- const resp = await this.request("PUT", `/v1/tenants/${orgId}/budgets`, body);
1163
- return TenantBudgetsView.parse(resp);
1164
- }
1165
- };
1166
-
1167
- // src/integrations/vercel-ai.ts
1168
- var Z3rnoVercelMemory = class {
1169
- client;
1170
- agentId;
1171
- conversationId;
1172
- topK;
1173
- constructor(options) {
1174
- this.client = options.client;
1175
- this.agentId = options.agentId;
1176
- this.conversationId = options.conversationId;
1177
- this.topK = options.topK ?? 50;
1178
- }
1179
- async messages() {
1180
- if (this.conversationId) {
1181
- const page = await this.client.listTurns(this.conversationId, {
1182
- limit: this.topK
1183
- });
1184
- return page.turns.map((t) => ({
1185
- role: this.normaliseRole(t.turn_role),
1186
- content: t.content
1187
- }));
1188
- }
1189
- const resp = await this.client.recall({
1190
- agentId: this.agentId,
1191
- topK: this.topK,
1192
- memoryType: "episodic"
1193
- });
1194
- const reversed = [...resp.results].reverse();
1195
- return reversed.map((r) => ({
1196
- role: this.normaliseRole(
1197
- (r.metadata ?? {})["role"]
1198
- ),
1199
- content: r.content
1200
- }));
1201
- }
1202
- async appendUserMessage(content) {
1203
- await this.append(content, "user");
1204
- }
1205
- async appendAssistantMessage(content) {
1206
- await this.append(content, "assistant");
1207
- }
1208
- async appendToolMessage(content) {
1209
- await this.append(content, "tool");
1210
- }
1211
- async append(content, role) {
1212
- const memory = await this.client.store({
1213
- agentId: this.agentId,
1214
- content,
1215
- memoryType: "episodic",
1216
- metadata: { role },
1217
- relationships: []
1218
- });
1219
- if (this.conversationId) {
1220
- await this.client.addTurn(this.conversationId, {
1221
- memoryId: memory.id,
1222
- turnRole: role
1223
- });
1224
- }
1225
- }
1226
- normaliseRole(raw) {
1227
- switch (raw) {
1228
- case "assistant":
1229
- case "ai":
1230
- return "assistant";
1231
- case "system":
1232
- return "system";
1233
- case "tool":
1234
- return "tool";
1235
- default:
1236
- return "user";
1237
- }
1238
- }
1239
- };
1240
-
1241
- // src/integrations/mastra.ts
1242
- var Z3rnoMastraMemory = class {
1243
- client;
1244
- agentId;
1245
- conversationId;
1246
- topK;
1247
- constructor(options) {
1248
- this.client = options.client;
1249
- this.agentId = options.agentId;
1250
- this.conversationId = options.conversationId;
1251
- this.topK = options.topK ?? 50;
1252
- }
1253
- /** Mastra contract: return ordered prior messages for the thread. */
1254
- async getMessages(_args) {
1255
- const limit = _args?.limit ?? this.topK;
1256
- if (this.conversationId) {
1257
- const page = await this.client.listTurns(this.conversationId, { limit });
1258
- return page.turns.map((t) => ({
1259
- role: this.normaliseRole(t.turn_role),
1260
- content: t.content,
1261
- threadId: this.conversationId
1262
- }));
1263
- }
1264
- const resp = await this.client.recall({
1265
- agentId: this.agentId,
1266
- topK: limit,
1267
- memoryType: "episodic"
1268
- });
1269
- const reversed = [...resp.results].reverse();
1270
- return reversed.map((r) => ({
1271
- role: this.normaliseRole(
1272
- (r.metadata ?? {})["role"]
1273
- ),
1274
- content: r.content
1275
- }));
1276
- }
1277
- /** Mastra contract: persist one message. */
1278
- async addMessage(message) {
1279
- const memory = await this.client.store({
1280
- agentId: this.agentId,
1281
- content: message.content,
1282
- memoryType: "episodic",
1283
- metadata: { role: message.role },
1284
- relationships: []
1285
- });
1286
- if (this.conversationId) {
1287
- await this.client.addTurn(this.conversationId, {
1288
- memoryId: memory.id,
1289
- turnRole: message.role
1290
- });
1291
- }
1292
- }
1293
- /**
1294
- * Mastra `clear()` — deliberate no-op. Z3rno keeps the source of
1295
- * truth and recall is already scoped per conversation; flushing
1296
- * the thread would risk losing audit-relevant history.
1297
- */
1298
- async clear() {
1299
- return;
1300
- }
1301
- normaliseRole(raw) {
1302
- switch (raw) {
1303
- case "assistant":
1304
- case "ai":
1305
- return "assistant";
1306
- case "system":
1307
- return "system";
1308
- case "tool":
1309
- return "tool";
1310
- default:
1311
- return "user";
1312
- }
1313
- }
1314
- };
1315
-
1316
- exports.AdminAPI = AdminAPI;
1317
- exports.AuditEntry = AuditEntry;
1318
- exports.AuditPageResponse = AuditPageResponse;
1319
- exports.AuthenticationError = AuthenticationError;
1320
- exports.BatchStoreResponse = BatchStoreResponse;
1321
- exports.ConversationResponse = ConversationResponse;
1322
- exports.DistillJobResponse = DistillJobResponse;
1323
- exports.DistillJobStatusResponse = DistillJobStatusResponse;
1324
- exports.EndSessionResponse = EndSessionResponse;
1325
- exports.ForgetResponse = ForgetResponse;
1326
- exports.IngestJobResponse = IngestJobResponse;
1327
- exports.IngestJobStatusResponse = IngestJobStatusResponse;
1328
- exports.MemoryHistoryResponse = MemoryHistoryResponse;
1329
- exports.MemoryResponse = MemoryResponse;
1330
- exports.MemoryType = MemoryType;
1331
- exports.MemoryVersion = MemoryVersion;
1332
- exports.NotFoundError = NotFoundError;
1333
- exports.RateLimitError = RateLimitError;
1334
- exports.RecallResponse = RecallResponse;
1335
- exports.RecallResultItem = RecallResultItem;
1336
- exports.RefineJobResponse = RefineJobResponse;
1337
- exports.RefineJobStatusResponse = RefineJobStatusResponse;
1338
- exports.RelationshipType = RelationshipType;
1339
- exports.RetrievalStrategy = RetrievalStrategy;
1340
- exports.ServerError = ServerError;
1341
- exports.SessionResponse = SessionResponse;
1342
- exports.TenantBudgets = TenantBudgets;
1343
- exports.TenantBudgetsView = TenantBudgetsView;
1344
- exports.TurnAddResponse = TurnAddResponse;
1345
- exports.TurnListResponse = TurnListResponse;
1346
- exports.TurnResponse = TurnResponse;
1347
- exports.ValidationError = ValidationError;
1348
- exports.Z3rnoClient = Z3rnoClient;
1349
- exports.Z3rnoConnectionError = Z3rnoConnectionError;
1350
- exports.Z3rnoError = Z3rnoError;
1351
- exports.Z3rnoMastraMemory = Z3rnoMastraMemory;
1352
- exports.Z3rnoTimeoutError = Z3rnoTimeoutError;
1353
- exports.Z3rnoVercelMemory = Z3rnoVercelMemory;
1354
- //# sourceMappingURL=index.cjs.map
1355
- //# sourceMappingURL=index.cjs.map