@z3rno/sdk 0.0.1 → 0.1.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 CHANGED
@@ -4,7 +4,12 @@ var zod = require('zod');
4
4
 
5
5
  // src/errors.ts
6
6
  var Z3rnoError = class extends Error {
7
+ /** HTTP status code returned by the server, if applicable. */
7
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
+ */
8
13
  constructor(message, statusCode) {
9
14
  super(message);
10
15
  this.name = "Z3rnoError";
@@ -12,13 +17,21 @@ var Z3rnoError = class extends Error {
12
17
  }
13
18
  };
14
19
  var AuthenticationError = class extends Z3rnoError {
20
+ /**
21
+ * @param message - Description of the authentication failure.
22
+ */
15
23
  constructor(message) {
16
24
  super(message, 401);
17
25
  this.name = "AuthenticationError";
18
26
  }
19
27
  };
20
28
  var RateLimitError = class extends Z3rnoError {
29
+ /** Number of seconds to wait before retrying, per the Retry-After header. */
21
30
  retryAfter;
31
+ /**
32
+ * @param message - Description of the rate-limit error.
33
+ * @param retryAfter - Seconds to wait before retrying (defaults to 60).
34
+ */
22
35
  constructor(message, retryAfter = 60) {
23
36
  super(message, 429);
24
37
  this.name = "RateLimitError";
@@ -26,23 +39,56 @@ var RateLimitError = class extends Z3rnoError {
26
39
  }
27
40
  };
28
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
+ */
29
46
  constructor(message, statusCode = 400) {
30
47
  super(message, statusCode);
31
48
  this.name = "ValidationError";
32
49
  }
33
50
  };
34
51
  var NotFoundError = class extends Z3rnoError {
52
+ /**
53
+ * @param message - Description of what was not found.
54
+ */
35
55
  constructor(message) {
36
56
  super(message, 404);
37
57
  this.name = "NotFoundError";
38
58
  }
39
59
  };
40
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
+ */
41
65
  constructor(message, statusCode = 500) {
42
66
  super(message, statusCode);
43
67
  this.name = "ServerError";
44
68
  }
45
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
+ };
46
92
  var MemoryType = zod.z.enum([
47
93
  "working",
48
94
  "episodic",
@@ -58,104 +104,283 @@ var RelationshipType = zod.z.enum([
58
104
  "caused_by"
59
105
  ]);
60
106
  zod.z.object({
107
+ /** UUID of the agent that owns this memory. */
61
108
  agentId: zod.z.string().uuid(),
109
+ /** The text content to store (1 to 100,000 characters). */
62
110
  content: zod.z.string().min(1).max(1e5),
111
+ /** Category of memory. Defaults to `"episodic"`. */
63
112
  memoryType: MemoryType.default("episodic"),
113
+ /** Optional UUID of the user associated with this memory. */
64
114
  userId: zod.z.string().uuid().optional(),
115
+ /** Arbitrary key-value metadata attached to the memory. */
65
116
  metadata: zod.z.record(zod.z.unknown()).default({}),
117
+ /** Relationships to other memories in the knowledge graph. */
66
118
  relationships: zod.z.array(
67
119
  zod.z.object({
120
+ /** UUID of the target memory. */
68
121
  targetMemoryId: zod.z.string().uuid(),
122
+ /** Type of relationship to the target memory. */
69
123
  relationshipType: RelationshipType,
124
+ /** Relationship strength from 0 to 1. Defaults to 1.0. */
70
125
  weight: zod.z.number().min(0).max(1).default(1),
126
+ /** Arbitrary metadata for the relationship edge. */
71
127
  metadata: zod.z.record(zod.z.unknown()).default({})
72
128
  })
73
129
  ).default([]),
130
+ /** Time-to-live in seconds. Memory auto-deletes after this duration. */
74
131
  ttlSeconds: zod.z.number().int().positive().optional(),
132
+ /** Importance score from 0 to 1. Influences recall ranking. */
75
133
  importance: zod.z.number().min(0).max(1).optional()
76
134
  });
77
135
  zod.z.object({
136
+ /** UUID of the agent whose memories to search. */
78
137
  agentId: zod.z.string().uuid(),
138
+ /** Natural-language query for semantic similarity search. */
79
139
  query: zod.z.string().optional(),
140
+ /** Filter results to a specific memory type. */
80
141
  memoryType: zod.z.string().optional(),
142
+ /** Additional metadata filters. */
81
143
  filters: zod.z.record(zod.z.unknown()).optional(),
144
+ /** Maximum number of results to return (1-100, default 10). */
82
145
  topK: zod.z.number().int().min(1).max(100).default(10),
146
+ /** Minimum similarity score threshold (0-1, default 0). */
83
147
  similarityThreshold: zod.z.number().min(0).max(1).default(0),
148
+ /** ISO 8601 timestamp for temporal queries (point-in-time recall). */
84
149
  asOf: zod.z.string().datetime().optional(),
150
+ /** Whether to include soft-deleted memories. */
85
151
  includeDeleted: zod.z.boolean().default(false)
86
152
  });
87
153
  zod.z.object({
154
+ /** UUID of the agent that owns the memories. */
88
155
  agentId: zod.z.string().uuid(),
156
+ /** UUID of a single memory to delete. */
89
157
  memoryId: zod.z.string().uuid().optional(),
158
+ /** UUIDs of multiple memories to delete in one call. */
90
159
  memoryIds: zod.z.array(zod.z.string().uuid()).optional(),
160
+ /** If true, permanently deletes (vs. soft-delete). Defaults to false. */
91
161
  hardDelete: zod.z.boolean().default(false),
162
+ /** If true, also deletes related memories. Defaults to false. */
92
163
  cascade: zod.z.boolean().default(false),
164
+ /** Optional reason for the deletion (stored in audit log). */
93
165
  reason: zod.z.string().optional()
94
166
  });
95
167
  var MemoryResponse = zod.z.object({
168
+ /** Unique identifier for this memory. */
96
169
  id: zod.z.string(),
170
+ /** UUID of the owning agent. */
97
171
  agent_id: zod.z.string(),
172
+ /** Text content of the memory. */
98
173
  content: zod.z.string(),
174
+ /** Category of the memory. */
99
175
  memory_type: zod.z.string(),
176
+ /** Server-computed importance score (0-1). */
100
177
  importance_score: zod.z.number(),
178
+ /** Number of times this memory has been recalled. */
101
179
  recall_count: zod.z.number(),
180
+ /** Name of the embedding model used, if any. */
102
181
  embedding_model: zod.z.string().nullable().optional(),
182
+ /** ISO 8601 creation timestamp. */
103
183
  created_at: zod.z.string(),
184
+ /** Arbitrary metadata attached to the memory. */
104
185
  metadata: zod.z.record(zod.z.unknown()).default({})
105
186
  });
106
187
  var RecallResultItem = zod.z.object({
188
+ /** Unique identifier of the recalled memory. */
107
189
  memory_id: zod.z.string(),
190
+ /** Text content of the memory. */
108
191
  content: zod.z.string(),
192
+ /** Optional server-generated summary. */
109
193
  summary: zod.z.string().nullable().optional(),
194
+ /** Category of the memory. */
110
195
  memory_type: zod.z.string(),
196
+ /** Cosine similarity to the query (0-1). */
111
197
  similarity_score: zod.z.number(),
198
+ /** Server-computed importance score (0-1). */
112
199
  importance_score: zod.z.number(),
200
+ /** Combined relevance score used for ranking (0-1). */
113
201
  relevance_score: zod.z.number(),
202
+ /** Number of times this memory has been recalled. */
114
203
  recall_count: zod.z.number(),
204
+ /** ISO 8601 creation timestamp. */
115
205
  created_at: zod.z.string(),
206
+ /** Arbitrary metadata attached to the memory. */
116
207
  metadata: zod.z.record(zod.z.unknown()).default({})
117
208
  });
118
209
  var RecallResponse = zod.z.object({
210
+ /** Ranked list of matching memories. */
119
211
  results: zod.z.array(RecallResultItem),
212
+ /** Total number of matches (may exceed `topK`). */
120
213
  total: zod.z.number(),
214
+ /** The query that was searched, if any. */
121
215
  query: zod.z.string().nullable().optional()
122
216
  });
123
217
  var ForgetResponse = zod.z.object({
218
+ /** Number of memories deleted. */
124
219
  deleted_count: zod.z.number(),
220
+ /** Whether a hard delete was performed. */
125
221
  hard_deleted: zod.z.boolean(),
222
+ /** Number of related memories deleted via cascade. */
126
223
  cascade_count: zod.z.number(),
224
+ /** IDs of all deleted memories. */
127
225
  memory_ids: zod.z.array(zod.z.string())
128
226
  });
129
227
  var AuditEntry = zod.z.object({
228
+ /** Auto-incrementing audit entry ID. */
130
229
  id: zod.z.number(),
230
+ /** UUID of the agent, if applicable. */
131
231
  agent_id: zod.z.string().nullable().optional(),
232
+ /** UUID of the user, if applicable. */
132
233
  user_id: zod.z.string().nullable().optional(),
234
+ /** Operation type (e.g., `"store"`, `"recall"`, `"forget"`). */
133
235
  operation: zod.z.string(),
236
+ /** UUID of the affected memory, if applicable. */
134
237
  memory_id: zod.z.string().nullable().optional(),
238
+ /** Memory type of the affected memory, if applicable. */
135
239
  memory_type: zod.z.string().nullable().optional(),
240
+ /** Additional details about the operation. */
136
241
  details: zod.z.record(zod.z.unknown()).default({}),
242
+ /** IP address of the caller, if available. */
137
243
  ip_address: zod.z.string().nullable().optional(),
244
+ /** ISO 8601 timestamp of the operation. */
138
245
  created_at: zod.z.string()
139
246
  });
140
247
  var AuditPageResponse = zod.z.object({
248
+ /** Audit entries on this page. */
141
249
  entries: zod.z.array(AuditEntry),
250
+ /** Total number of matching audit entries. */
142
251
  total: zod.z.number(),
252
+ /** Current page number (1-indexed). */
143
253
  page: zod.z.number(),
254
+ /** Number of entries per page. */
144
255
  page_size: zod.z.number(),
256
+ /** Whether more pages are available. */
145
257
  has_next: zod.z.boolean()
146
258
  });
259
+ var BatchStoreResponse = zod.z.object({
260
+ /** Array of stored memory objects. */
261
+ results: zod.z.array(MemoryResponse),
262
+ /** Number of memories successfully stored. */
263
+ stored_count: zod.z.number()
264
+ });
265
+ var MemoryVersion = zod.z.object({
266
+ /** Version identifier. */
267
+ id: zod.z.string(),
268
+ /** Text content at this version. */
269
+ content: zod.z.string(),
270
+ /** Memory type at this version. */
271
+ memory_type: zod.z.string(),
272
+ /** Importance score at this version. */
273
+ importance_score: zod.z.number(),
274
+ /** ISO 8601 timestamp when this version became active. */
275
+ valid_from: zod.z.string(),
276
+ /** ISO 8601 timestamp when this version was superseded, or null if current. */
277
+ valid_to: zod.z.string().nullable().optional(),
278
+ /** Metadata at this version. */
279
+ metadata: zod.z.record(zod.z.unknown()).default({})
280
+ });
281
+ var MemoryHistoryResponse = zod.z.object({
282
+ /** UUID of the memory. */
283
+ memory_id: zod.z.string(),
284
+ /** Chronologically ordered list of versions. */
285
+ versions: zod.z.array(MemoryVersion),
286
+ /** Total number of versions. */
287
+ total: zod.z.number()
288
+ });
289
+ var SessionResponse = zod.z.object({
290
+ /** Unique session identifier. */
291
+ session_id: zod.z.string(),
292
+ /** UUID of the agent this session belongs to. */
293
+ agent_id: zod.z.string(),
294
+ /** Type of session (e.g., `"conversation"`). */
295
+ session_type: zod.z.string(),
296
+ /** ISO 8601 timestamp when the session started. */
297
+ started_at: zod.z.string(),
298
+ /** Arbitrary session metadata. */
299
+ metadata: zod.z.record(zod.z.unknown()).default({})
300
+ });
301
+ var EndSessionResponse = zod.z.object({
302
+ /** The session that was ended. */
303
+ session_id: zod.z.string(),
304
+ /** ISO 8601 timestamp when the session ended. */
305
+ ended_at: zod.z.string(),
306
+ /** Total duration of the session in seconds. */
307
+ duration_seconds: zod.z.number(),
308
+ /** Number of memories created during the session. */
309
+ memory_count: zod.z.number()
310
+ });
147
311
 
148
312
  // src/client.ts
149
313
  var Z3rnoClient = class {
150
314
  baseUrl;
151
315
  apiKey;
152
316
  timeout;
153
- constructor(config) {
154
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
155
- this.apiKey = config.apiKey;
317
+ maxRetries;
318
+ fetchImpl;
319
+ onRequest;
320
+ onResponse;
321
+ /**
322
+ * Creates a new Z3rno client instance.
323
+ *
324
+ * @param config - Client configuration options. All fields are optional.
325
+ *
326
+ * @example
327
+ * ```ts
328
+ * // Explicit configuration
329
+ * const client = new Z3rnoClient({
330
+ * baseUrl: "http://localhost:8000",
331
+ * apiKey: "z3rno_sk_test_...",
332
+ * timeout: 10000,
333
+ * maxRetries: 2,
334
+ * });
335
+ *
336
+ * // Or rely on environment variables (Z3RNO_BASE_URL, Z3RNO_API_KEY)
337
+ * const client = new Z3rnoClient();
338
+ * ```
339
+ */
340
+ constructor(config = {}) {
341
+ let resolvedUrl = config.baseUrl ?? "";
342
+ if (!resolvedUrl && typeof process !== "undefined" && process.env) {
343
+ resolvedUrl = process.env.Z3RNO_BASE_URL ?? "";
344
+ }
345
+ if (!resolvedUrl) {
346
+ resolvedUrl = "https://api.z3rno.dev";
347
+ }
348
+ this.baseUrl = resolvedUrl.replace(/\/$/, "");
349
+ let resolvedKey = config.apiKey ?? "";
350
+ if (!resolvedKey && typeof process !== "undefined" && process.env) {
351
+ resolvedKey = process.env.Z3RNO_API_KEY ?? "";
352
+ }
353
+ this.apiKey = resolvedKey;
156
354
  this.timeout = config.timeout ?? 3e4;
355
+ this.maxRetries = config.maxRetries ?? 3;
356
+ this.fetchImpl = config.fetch ?? globalThis.fetch;
357
+ this.onRequest = config.onRequest;
358
+ this.onResponse = config.onResponse;
157
359
  }
158
360
  // --- Store ---
361
+ /**
362
+ * Stores a new memory for an agent.
363
+ *
364
+ * The server generates an embedding for the content and stores it in
365
+ * the vector database. The memory is immediately available for recall.
366
+ *
367
+ * @param request - The memory to store.
368
+ * @returns The stored memory, including the server-generated ID and scores.
369
+ * @throws {@link AuthenticationError} If the API key is invalid.
370
+ * @throws {@link ValidationError} If the request body is invalid.
371
+ * @throws {@link Z3rnoTimeoutError} If the request times out.
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * const memory = await client.store({
376
+ * agentId: "550e8400-e29b-41d4-a716-446655440000",
377
+ * content: "User prefers dark mode",
378
+ * memoryType: "semantic",
379
+ * metadata: { source: "settings-page" },
380
+ * });
381
+ * console.log(memory.id); // "mem-abc123"
382
+ * ```
383
+ */
159
384
  async store(request) {
160
385
  const body = {
161
386
  agent_id: request.agentId,
@@ -176,6 +401,36 @@ var Z3rnoClient = class {
176
401
  return MemoryResponse.parse(resp);
177
402
  }
178
403
  // --- Recall ---
404
+ /**
405
+ * Recalls memories by semantic similarity to a query.
406
+ *
407
+ * Returns a ranked list of memories sorted by a combined relevance score
408
+ * that factors in similarity, importance, and recency.
409
+ *
410
+ * @param params - Recall parameters including the query and filters.
411
+ * @param params.agentId - UUID of the agent whose memories to search.
412
+ * @param params.query - Natural-language query for semantic search.
413
+ * @param params.memoryType - Filter by memory type.
414
+ * @param params.filters - Additional metadata filters.
415
+ * @param params.topK - Maximum results to return (default 10).
416
+ * @param params.similarityThreshold - Minimum similarity score (default 0).
417
+ * @returns Ranked recall results with similarity scores.
418
+ * @throws {@link AuthenticationError} If the API key is invalid.
419
+ * @throws {@link Z3rnoTimeoutError} If the request times out.
420
+ *
421
+ * @example
422
+ * ```ts
423
+ * const results = await client.recall({
424
+ * agentId: "550e8400-e29b-41d4-a716-446655440000",
425
+ * query: "user preferences",
426
+ * topK: 5,
427
+ * similarityThreshold: 0.7,
428
+ * });
429
+ * for (const item of results.results) {
430
+ * console.log(`${item.content} (score: ${item.relevance_score})`);
431
+ * }
432
+ * ```
433
+ */
179
434
  async recall(params) {
180
435
  const body = {
181
436
  agent_id: params.agentId,
@@ -189,6 +444,35 @@ var Z3rnoClient = class {
189
444
  return RecallResponse.parse(resp);
190
445
  }
191
446
  // --- Forget ---
447
+ /**
448
+ * Forgets (deletes) one or more memories.
449
+ *
450
+ * By default, performs a soft delete (marks as deleted but retains data).
451
+ * Set `hardDelete: true` for permanent removal. Use `cascade: true` to
452
+ * also delete related memories in the knowledge graph.
453
+ *
454
+ * @param params - Forget parameters.
455
+ * @param params.agentId - UUID of the agent that owns the memories.
456
+ * @param params.memoryId - UUID of a single memory to delete.
457
+ * @param params.memoryIds - UUIDs of multiple memories to delete.
458
+ * @param params.hardDelete - Permanently delete (default false).
459
+ * @param params.cascade - Delete related memories too (default false).
460
+ * @param params.reason - Reason for deletion (stored in audit log).
461
+ * @returns Summary of the deletion operation.
462
+ * @throws {@link AuthenticationError} If the API key is invalid.
463
+ * @throws {@link NotFoundError} If the specified memory does not exist.
464
+ *
465
+ * @example
466
+ * ```ts
467
+ * const result = await client.forget({
468
+ * agentId: "550e8400-e29b-41d4-a716-446655440000",
469
+ * memoryId: "mem-abc123",
470
+ * hardDelete: true,
471
+ * reason: "User requested data deletion",
472
+ * });
473
+ * console.log(`Deleted ${result.deleted_count} memories`);
474
+ * ```
475
+ */
192
476
  async forget(params) {
193
477
  const body = {
194
478
  agent_id: params.agentId,
@@ -201,7 +485,193 @@ var Z3rnoClient = class {
201
485
  const resp = await this.request("POST", "/v1/memories/forget", body);
202
486
  return ForgetResponse.parse(resp);
203
487
  }
488
+ // --- Get Memory ---
489
+ /**
490
+ * Retrieves a single memory by its ID.
491
+ *
492
+ * @param memoryId - The unique identifier of the memory to retrieve.
493
+ * @returns The full memory object.
494
+ * @throws {@link NotFoundError} If no memory exists with the given ID.
495
+ * @throws {@link AuthenticationError} If the API key is invalid.
496
+ *
497
+ * @example
498
+ * ```ts
499
+ * const memory = await client.getMemory("mem-abc123");
500
+ * console.log(memory.content);
501
+ * console.log(memory.importance_score);
502
+ * ```
503
+ */
504
+ async getMemory(memoryId) {
505
+ const resp = await this.request("GET", `/v1/memories/${memoryId}`);
506
+ return MemoryResponse.parse(resp);
507
+ }
508
+ // --- Store Batch ---
509
+ /**
510
+ * Stores multiple memories in a single API call.
511
+ *
512
+ * More efficient than calling {@link store} in a loop. All memories are
513
+ * processed atomically on the server.
514
+ *
515
+ * @param memories - Array of memories to store.
516
+ * @returns The stored memories and a count of how many were created.
517
+ * @throws {@link ValidationError} If any memory in the batch is invalid.
518
+ * @throws {@link AuthenticationError} If the API key is invalid.
519
+ *
520
+ * @example
521
+ * ```ts
522
+ * const result = await client.storeBatch([
523
+ * { agentId: "agent-1", content: "Fact one" },
524
+ * { agentId: "agent-1", content: "Fact two", memoryType: "semantic" },
525
+ * ]);
526
+ * console.log(`Stored ${result.stored_count} memories`);
527
+ * ```
528
+ */
529
+ async storeBatch(memories) {
530
+ const body = {
531
+ memories: memories.map((m) => ({
532
+ agent_id: m.agentId,
533
+ content: m.content,
534
+ memory_type: m.memoryType,
535
+ metadata: m.metadata,
536
+ importance: m.importance
537
+ }))
538
+ };
539
+ const resp = await this.request("POST", "/v1/memories/batch", body);
540
+ return BatchStoreResponse.parse(resp);
541
+ }
542
+ // --- Memory History ---
543
+ /**
544
+ * Retrieves the full version history of a memory.
545
+ *
546
+ * Z3rno uses temporal versioning — every update creates a new version
547
+ * rather than overwriting. This method returns all versions ordered
548
+ * chronologically.
549
+ *
550
+ * @param memoryId - The unique identifier of the memory.
551
+ * @returns All versions of the memory with validity timestamps.
552
+ * @throws {@link NotFoundError} If no memory exists with the given ID.
553
+ * @throws {@link AuthenticationError} If the API key is invalid.
554
+ *
555
+ * @example
556
+ * ```ts
557
+ * const history = await client.getMemoryHistory("mem-abc123");
558
+ * for (const version of history.versions) {
559
+ * console.log(`${version.valid_from}: ${version.content}`);
560
+ * }
561
+ * ```
562
+ */
563
+ async getMemoryHistory(memoryId) {
564
+ const resp = await this.request("GET", `/v1/memories/${memoryId}/history`);
565
+ return MemoryHistoryResponse.parse(resp);
566
+ }
567
+ // --- Update Memory ---
568
+ /**
569
+ * Updates an existing memory's content, metadata, or importance.
570
+ *
571
+ * Creates a new temporal version of the memory. The previous version
572
+ * remains accessible via {@link getMemoryHistory}.
573
+ *
574
+ * @param memoryId - The unique identifier of the memory to update.
575
+ * @param updates - Fields to update (only provided fields are changed).
576
+ * @param updates.content - New text content.
577
+ * @param updates.metadata - New metadata (replaces existing metadata).
578
+ * @param updates.importance - New importance score (0-1).
579
+ * @returns The updated memory object.
580
+ * @throws {@link NotFoundError} If no memory exists with the given ID.
581
+ * @throws {@link ValidationError} If the update values are invalid.
582
+ * @throws {@link AuthenticationError} If the API key is invalid.
583
+ *
584
+ * @example
585
+ * ```ts
586
+ * const updated = await client.updateMemory("mem-abc123", {
587
+ * content: "User now prefers light mode",
588
+ * importance: 0.9,
589
+ * });
590
+ * ```
591
+ */
592
+ async updateMemory(memoryId, updates) {
593
+ const body = {};
594
+ if (updates.content !== void 0) body.content = updates.content;
595
+ if (updates.metadata !== void 0) body.metadata = updates.metadata;
596
+ if (updates.importance !== void 0) body.importance = updates.importance;
597
+ const resp = await this.request("PATCH", `/v1/memories/${memoryId}`, body);
598
+ return MemoryResponse.parse(resp);
599
+ }
600
+ // --- Sessions ---
601
+ /**
602
+ * Starts a new session for grouping related memory operations.
603
+ *
604
+ * Sessions are useful for tracking conversation turns or task boundaries.
605
+ * Memories created during a session are automatically associated with it.
606
+ *
607
+ * @param params - Session parameters.
608
+ * @param params.agentId - UUID of the agent to start the session for.
609
+ * @param params.sessionType - Type of session (default `"conversation"`).
610
+ * @returns The created session with its ID and start time.
611
+ * @throws {@link AuthenticationError} If the API key is invalid.
612
+ *
613
+ * @example
614
+ * ```ts
615
+ * const session = await client.startSession({ agentId: "agent-1" });
616
+ * console.log(`Session started: ${session.session_id}`);
617
+ * // ... perform operations ...
618
+ * await client.endSession(session.session_id);
619
+ * ```
620
+ */
621
+ async startSession(params) {
622
+ const body = {
623
+ agent_id: params.agentId,
624
+ session_type: params.sessionType ?? "conversation"
625
+ };
626
+ const resp = await this.request("POST", "/v1/sessions", body);
627
+ return SessionResponse.parse(resp);
628
+ }
629
+ /**
630
+ * Ends an active session.
631
+ *
632
+ * Returns summary statistics including the session duration and the
633
+ * number of memories created during the session.
634
+ *
635
+ * @param sessionId - The unique identifier of the session to end.
636
+ * @returns Session summary with duration and memory count.
637
+ * @throws {@link NotFoundError} If no active session exists with the given ID.
638
+ * @throws {@link AuthenticationError} If the API key is invalid.
639
+ *
640
+ * @example
641
+ * ```ts
642
+ * const summary = await client.endSession("sess-abc123");
643
+ * console.log(`Session lasted ${summary.duration_seconds}s, ${summary.memory_count} memories`);
644
+ * ```
645
+ */
646
+ async endSession(sessionId) {
647
+ const resp = await this.request("POST", `/v1/sessions/${sessionId}/end`);
648
+ return EndSessionResponse.parse(resp);
649
+ }
204
650
  // --- Audit ---
651
+ /**
652
+ * Retrieves a paginated audit log of memory operations.
653
+ *
654
+ * The audit log records every store, recall, forget, and update operation
655
+ * performed by any agent. Useful for compliance, debugging, and analytics.
656
+ *
657
+ * @param params - Optional pagination and filter parameters.
658
+ * @param params.agentId - Filter by agent UUID.
659
+ * @param params.page - Page number (1-indexed).
660
+ * @param params.pageSize - Number of entries per page.
661
+ * @returns A page of audit log entries with pagination metadata.
662
+ * @throws {@link AuthenticationError} If the API key is invalid.
663
+ *
664
+ * @example
665
+ * ```ts
666
+ * const page = await client.audit({ agentId: "agent-1", page: 1, pageSize: 20 });
667
+ * for (const entry of page.entries) {
668
+ * console.log(`${entry.created_at}: ${entry.operation} on ${entry.memory_id}`);
669
+ * }
670
+ * if (page.has_next) {
671
+ * const nextPage = await client.audit({ agentId: "agent-1", page: 2 });
672
+ * }
673
+ * ```
674
+ */
205
675
  async audit(params) {
206
676
  const searchParams = new URLSearchParams();
207
677
  if (params?.agentId) searchParams.set("agent_id", params.agentId);
@@ -215,26 +685,75 @@ var Z3rnoClient = class {
215
685
  }
216
686
  // --- HTTP layer ---
217
687
  async request(method, path, body) {
218
- const controller = new AbortController();
219
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
220
- try {
221
- const response = await fetch(`${this.baseUrl}${path}`, {
222
- method,
223
- headers: {
224
- Authorization: `Bearer ${this.apiKey}`,
225
- "Content-Type": "application/json",
226
- "User-Agent": "@z3rno/sdk/0.0.1"
227
- },
228
- body: body ? JSON.stringify(body) : void 0,
229
- signal: controller.signal
230
- });
231
- clearTimeout(timeoutId);
232
- return this.handleResponse(response);
233
- } catch (error) {
234
- clearTimeout(timeoutId);
235
- if (error instanceof Z3rnoError) throw error;
236
- throw new Z3rnoError(`Request failed: ${String(error)}`);
688
+ let lastError;
689
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
690
+ const controller = new AbortController();
691
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
692
+ try {
693
+ const url = `${this.baseUrl}${path}`;
694
+ let init = {
695
+ method,
696
+ headers: {
697
+ Authorization: `Bearer ${this.apiKey}`,
698
+ "Content-Type": "application/json",
699
+ "User-Agent": "@z3rno/sdk/0.0.1"
700
+ },
701
+ body: body ? JSON.stringify(body) : void 0,
702
+ signal: controller.signal
703
+ };
704
+ if (this.onRequest) {
705
+ init = this.onRequest(url, init);
706
+ }
707
+ let response = await this.fetchImpl(url, init);
708
+ if (this.onResponse) {
709
+ response = this.onResponse(response);
710
+ }
711
+ clearTimeout(timeoutId);
712
+ if (response.status === 429 && attempt < this.maxRetries) {
713
+ const retryAfter = parseInt(
714
+ response.headers.get("Retry-After") ?? "1",
715
+ 10
716
+ );
717
+ await this.sleep(retryAfter * 1e3);
718
+ continue;
719
+ }
720
+ if (response.status >= 500 && attempt < this.maxRetries) {
721
+ const delay = Math.pow(2, attempt) * 1e3;
722
+ await this.sleep(delay);
723
+ continue;
724
+ }
725
+ return this.handleResponse(response);
726
+ } catch (error) {
727
+ clearTimeout(timeoutId);
728
+ if (error instanceof Z3rnoError) throw error;
729
+ if (error instanceof DOMException && error.name === "AbortError") {
730
+ lastError = new Z3rnoTimeoutError(
731
+ `Request timed out after ${this.timeout}ms`,
732
+ this.timeout
733
+ );
734
+ } else if (error instanceof TypeError) {
735
+ lastError = new Z3rnoConnectionError(
736
+ `Connection failed: ${error.message}`
737
+ );
738
+ } else {
739
+ lastError = error instanceof Error ? error : new Error(String(error));
740
+ }
741
+ if (attempt < this.maxRetries) {
742
+ const delay = Math.pow(2, attempt) * 1e3;
743
+ await this.sleep(delay);
744
+ continue;
745
+ }
746
+ }
747
+ }
748
+ if (lastError instanceof Z3rnoError) {
749
+ throw lastError;
237
750
  }
751
+ throw new Z3rnoError(
752
+ `Request failed after ${this.maxRetries + 1} attempts: ${String(lastError)}`
753
+ );
754
+ }
755
+ sleep(ms) {
756
+ return new Promise((resolve) => setTimeout(resolve, ms));
238
757
  }
239
758
  async handleResponse(resp) {
240
759
  if (resp.ok) {
@@ -242,8 +761,16 @@ var Z3rnoClient = class {
242
761
  }
243
762
  let detail = resp.statusText;
244
763
  try {
245
- const body = await resp.json();
246
- detail = String(body.detail ?? body.error ?? resp.statusText);
764
+ const text = await resp.text();
765
+ try {
766
+ const body = JSON.parse(text);
767
+ detail = String(body.detail ?? body.error ?? resp.statusText);
768
+ } catch {
769
+ if (text.length > 0) {
770
+ const preview = text.length > 200 ? text.slice(0, 200) + "..." : text;
771
+ detail = `${resp.statusText} \u2014 ${preview}`;
772
+ }
773
+ }
247
774
  } catch {
248
775
  }
249
776
  switch (resp.status) {
@@ -276,17 +803,24 @@ var Z3rnoClient = class {
276
803
  exports.AuditEntry = AuditEntry;
277
804
  exports.AuditPageResponse = AuditPageResponse;
278
805
  exports.AuthenticationError = AuthenticationError;
806
+ exports.BatchStoreResponse = BatchStoreResponse;
807
+ exports.EndSessionResponse = EndSessionResponse;
279
808
  exports.ForgetResponse = ForgetResponse;
809
+ exports.MemoryHistoryResponse = MemoryHistoryResponse;
280
810
  exports.MemoryResponse = MemoryResponse;
281
811
  exports.MemoryType = MemoryType;
812
+ exports.MemoryVersion = MemoryVersion;
282
813
  exports.NotFoundError = NotFoundError;
283
814
  exports.RateLimitError = RateLimitError;
284
815
  exports.RecallResponse = RecallResponse;
285
816
  exports.RecallResultItem = RecallResultItem;
286
817
  exports.RelationshipType = RelationshipType;
287
818
  exports.ServerError = ServerError;
819
+ exports.SessionResponse = SessionResponse;
288
820
  exports.ValidationError = ValidationError;
289
821
  exports.Z3rnoClient = Z3rnoClient;
822
+ exports.Z3rnoConnectionError = Z3rnoConnectionError;
290
823
  exports.Z3rnoError = Z3rnoError;
824
+ exports.Z3rnoTimeoutError = Z3rnoTimeoutError;
291
825
  //# sourceMappingURL=index.cjs.map
292
826
  //# sourceMappingURL=index.cjs.map