@z3rno/sdk 0.2.0 → 0.3.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 +44 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +54 -1
- package/dist/index.d.ts +54 -1
- package/dist/index.js +44 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -103,6 +103,17 @@ var RelationshipType = zod.z.enum([
|
|
|
103
103
|
"related_to",
|
|
104
104
|
"caused_by"
|
|
105
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
|
+
]);
|
|
106
117
|
zod.z.object({
|
|
107
118
|
/** UUID of the agent that owns this memory. */
|
|
108
119
|
agentId: zod.z.string().uuid(),
|
|
@@ -148,7 +159,18 @@ zod.z.object({
|
|
|
148
159
|
/** ISO 8601 timestamp for temporal queries (point-in-time recall). */
|
|
149
160
|
asOf: zod.z.string().datetime().optional(),
|
|
150
161
|
/** Whether to include soft-deleted memories. */
|
|
151
|
-
includeDeleted: zod.z.boolean().default(false)
|
|
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)
|
|
152
174
|
});
|
|
153
175
|
zod.z.object({
|
|
154
176
|
/** UUID of the agent that owns the memories. */
|
|
@@ -204,7 +226,12 @@ var RecallResultItem = zod.z.object({
|
|
|
204
226
|
/** ISO 8601 creation timestamp. */
|
|
205
227
|
created_at: zod.z.string(),
|
|
206
228
|
/** Arbitrary metadata attached to the memory. */
|
|
207
|
-
metadata: zod.z.record(zod.z.unknown()).default({})
|
|
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({})
|
|
208
235
|
});
|
|
209
236
|
var RecallResponse = zod.z.object({
|
|
210
237
|
/** Ranked list of matching memories. */
|
|
@@ -212,7 +239,15 @@ var RecallResponse = zod.z.object({
|
|
|
212
239
|
/** Total number of matches (may exceed `topK`). */
|
|
213
240
|
total: zod.z.number(),
|
|
214
241
|
/** The query that was searched, if any. */
|
|
215
|
-
query: zod.z.string().nullable().optional()
|
|
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)
|
|
216
251
|
});
|
|
217
252
|
var ForgetResponse = zod.z.object({
|
|
218
253
|
/** Number of memories deleted. */
|
|
@@ -438,7 +473,11 @@ var Z3rnoClient = class {
|
|
|
438
473
|
memory_type: params.memoryType,
|
|
439
474
|
filters: params.filters,
|
|
440
475
|
top_k: params.topK ?? 10,
|
|
441
|
-
similarity_threshold: params.similarityThreshold ?? 0
|
|
476
|
+
similarity_threshold: params.similarityThreshold ?? 0,
|
|
477
|
+
// Always send strategy + rerank. Older servers silently ignore
|
|
478
|
+
// unknown body fields.
|
|
479
|
+
strategy: params.strategy ?? "AUTO",
|
|
480
|
+
rerank: params.rerank ?? false
|
|
442
481
|
};
|
|
443
482
|
const resp = await this.request("POST", "/v1/memories/recall", body);
|
|
444
483
|
return RecallResponse.parse(resp);
|
|
@@ -815,6 +854,7 @@ exports.RateLimitError = RateLimitError;
|
|
|
815
854
|
exports.RecallResponse = RecallResponse;
|
|
816
855
|
exports.RecallResultItem = RecallResultItem;
|
|
817
856
|
exports.RelationshipType = RelationshipType;
|
|
857
|
+
exports.RetrievalStrategy = RetrievalStrategy;
|
|
818
858
|
exports.ServerError = ServerError;
|
|
819
859
|
exports.SessionResponse = SessionResponse;
|
|
820
860
|
exports.ValidationError = ValidationError;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/models.ts","../src/client.ts"],"names":["z"],"mappings":";;;;;AA4BO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA;AAAA,EAEpC,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAA,CAAY,SAAiB,UAAA,EAAqB;AAChD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AACZ,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAAA,EACpB;AACF;AAgBO,IAAM,mBAAA,GAAN,cAAkC,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA,EAIlD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,SAAS,GAAG,CAAA;AAClB,IAAA,I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e,CAAA,qBAAA,EAAwB,MAAM,IAAI,UAAU,CAAA;AAAA,MACvE;AAAA,MACA,KAAK,GAAA;AAAA,MACL,KAAK,GAAA;AACH,QAAA,MAAM,IAAI,eAAA,CAAgB,MAAA,EAAQ,IAAA,CAAK,MAAM,CAAA;AAAA,MAC/C;AACE,QAAA,IAAI,IAAA,CAAK,UAAU,GAAA,EAAK;AACtB,UAAA,MAAM,IAAI,WAAA,CAAY,CAAA,cAAA,EAAiB,MAAM,CAAA,CAAA,EAAI,KAAK,MAAM,CAAA;AAAA,QAC9D;AACA,QAAA,MAAM,IAAI,UAAA;AAAA,UACR,CAAA,kBAAA,EAAqB,IAAA,CAAK,MAAM,CAAA,GAAA,EAAM,MAAM,CAAA,CAAA;AAAA,UAC5C,IAAA,CAAK;AAAA,SACP;AAAA;AACJ,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Z3rno SDK error hierarchy.\n *\n * All errors thrown by the SDK extend {@link Z3rnoError}, which itself extends\n * the built-in `Error` class. This lets callers catch broadly (`Z3rnoError`)\n * or narrowly (`AuthenticationError`, `RateLimitError`, etc.).\n *\n * @module errors\n */\n\n/**\n * Base error class for all Z3rno SDK errors.\n *\n * Every error produced by the SDK is an instance of this class, so you can\n * use a single `catch (e) { if (e instanceof Z3rnoError) ... }` guard to\n * handle them all.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoError) {\n * console.error(`Z3rno error (${e.statusCode}): ${e.message}`);\n * }\n * }\n * ```\n */\nexport class Z3rnoError extends Error {\n /** HTTP status code returned by the server, if applicable. */\n statusCode?: number;\n\n /**\n * @param message - Human-readable description of the error.\n * @param statusCode - HTTP status code associated with the error, if any.\n */\n constructor(message: string, statusCode?: number) {\n super(message);\n this.name = \"Z3rnoError\";\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Thrown when the API key is missing, invalid, or revoked (HTTP 401).\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof AuthenticationError) {\n * console.error(\"Check your API key\");\n * }\n * }\n * ```\n */\nexport class AuthenticationError extends Z3rnoError {\n /**\n * @param message - Description of the authentication failure.\n */\n constructor(message: string) {\n super(message, 401);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Thrown when the client exceeds the API rate limit (HTTP 429).\n *\n * The {@link retryAfter} property indicates how many seconds to wait\n * before retrying, as reported by the server's `Retry-After` header.\n *\n * @example\n * ```ts\n * try {\n * await client.recall({ agentId: \"...\", query: \"...\" });\n * } catch (e) {\n * if (e instanceof RateLimitError) {\n * console.log(`Retry after ${e.retryAfter} seconds`);\n * }\n * }\n * ```\n */\nexport class RateLimitError extends Z3rnoError {\n /** Number of seconds to wait before retrying, per the Retry-After header. */\n retryAfter: number;\n\n /**\n * @param message - Description of the rate-limit error.\n * @param retryAfter - Seconds to wait before retrying (defaults to 60).\n */\n constructor(message: string, retryAfter: number = 60) {\n super(message, 429);\n this.name = \"RateLimitError\";\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Thrown when the server rejects the request due to invalid input (HTTP 400 or 422).\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"not-a-uuid\", content: \"\" });\n * } catch (e) {\n * if (e instanceof ValidationError) {\n * console.error(`Validation failed: ${e.message}`);\n * }\n * }\n * ```\n */\nexport class ValidationError extends Z3rnoError {\n /**\n * @param message - Description of the validation failure.\n * @param statusCode - HTTP status code (400 or 422, defaults to 400).\n */\n constructor(message: string, statusCode: number = 400) {\n super(message, statusCode);\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Thrown when the requested resource does not exist (HTTP 404).\n *\n * @example\n * ```ts\n * try {\n * await client.getMemory(\"non-existent-id\");\n * } catch (e) {\n * if (e instanceof NotFoundError) {\n * console.error(\"Memory not found\");\n * }\n * }\n * ```\n */\nexport class NotFoundError extends Z3rnoError {\n /**\n * @param message - Description of what was not found.\n */\n constructor(message: string) {\n super(message, 404);\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * Thrown when the Z3rno API returns a server-side error (HTTP 5xx).\n *\n * The SDK automatically retries on 5xx errors with exponential backoff.\n * This error is only thrown after all retries are exhausted.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof ServerError) {\n * console.error(`Server error (${e.statusCode}): ${e.message}`);\n * }\n * }\n * ```\n */\nexport class ServerError extends Z3rnoError {\n /**\n * @param message - Description of the server error.\n * @param statusCode - HTTP status code (defaults to 500).\n */\n constructor(message: string, statusCode: number = 500) {\n super(message, statusCode);\n this.name = \"ServerError\";\n }\n}\n\n/**\n * Thrown when a request exceeds the configured timeout duration.\n *\n * The SDK uses an {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController | AbortController}\n * to enforce timeouts. This error is thrown after all retries are exhausted.\n *\n * @example\n * ```ts\n * const client = new Z3rnoClient({ timeout: 5000 }); // 5 seconds\n * try {\n * await client.recall({ agentId: \"...\", query: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoTimeoutError) {\n * console.error(`Timed out after ${e.timeout}ms`);\n * }\n * }\n * ```\n */\nexport class Z3rnoTimeoutError extends Z3rnoError {\n /** The timeout duration in milliseconds that was exceeded. */\n timeout: number;\n\n /**\n * @param message - Description of the timeout.\n * @param timeout - The configured timeout value in milliseconds.\n */\n constructor(message: string, timeout: number) {\n super(message, undefined);\n this.name = \"Z3rnoTimeoutError\";\n this.timeout = timeout;\n }\n}\n\n/**\n * Thrown when the SDK cannot establish a connection to the Z3rno API.\n *\n * This typically indicates a network issue, DNS failure, or the server\n * being unreachable. The SDK retries connection errors with exponential\n * backoff before throwing this error.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoConnectionError) {\n * console.error(\"Cannot reach Z3rno API — check your network\");\n * }\n * }\n * ```\n */\nexport class Z3rnoConnectionError extends Z3rnoError {\n /**\n * @param message - Description of the connection failure.\n */\n constructor(message: string) {\n super(message, undefined);\n this.name = \"Z3rnoConnectionError\";\n }\n}\n","/**\n * Zod schemas and inferred TypeScript types for the Z3rno API.\n *\n * Each export is a dual: a Zod schema (used for runtime validation) and an\n * identically-named TypeScript type (used at compile time). Request schemas\n * validate client-side input; response schemas validate server payloads.\n *\n * @module models\n */\n\nimport { z } from \"zod\";\n\n// --- Enums ---\n\n/**\n * Memory type enum.\n *\n * Controls how a memory is stored, indexed, and decayed.\n *\n * - `working` — Short-lived scratchpad memory (high decay rate).\n * - `episodic` — Event-based memory tied to a specific interaction.\n * - `semantic` — Long-term factual knowledge.\n * - `procedural` — How-to or process knowledge.\n */\nexport const MemoryType = z.enum([\n \"working\",\n \"episodic\",\n \"semantic\",\n \"procedural\",\n]);\n\n/** Memory type: `\"working\"` | `\"episodic\"` | `\"semantic\"` | `\"procedural\"`. */\nexport type MemoryType = z.infer<typeof MemoryType>;\n\n/**\n * Relationship type enum.\n *\n * Describes how two memories are related in the knowledge graph.\n *\n * - `derived_from` — This memory was created from another.\n * - `contradicts` — This memory conflicts with another.\n * - `supports` — This memory reinforces another.\n * - `supersedes` — This memory replaces another.\n * - `related_to` — General association.\n * - `caused_by` — Causal relationship.\n */\nexport const RelationshipType = z.enum([\n \"derived_from\",\n \"contradicts\",\n \"supports\",\n \"supersedes\",\n \"related_to\",\n \"caused_by\",\n]);\n\n/** Relationship type between two memories. */\nexport type RelationshipType = z.infer<typeof RelationshipType>;\n\n// --- Request schemas ---\n\n/**\n * Schema for storing a new memory.\n *\n * @example\n * ```ts\n * const request = StoreMemoryRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * memoryType: \"semantic\",\n * });\n * ```\n */\nexport const StoreMemoryRequest = z.object({\n /** UUID of the agent that owns this memory. */\n agentId: z.string().uuid(),\n /** The text content to store (1 to 100,000 characters). */\n content: z.string().min(1).max(100000),\n /** Category of memory. Defaults to `\"episodic\"`. */\n memoryType: MemoryType.default(\"episodic\"),\n /** Optional UUID of the user associated with this memory. */\n userId: z.string().uuid().optional(),\n /** Arbitrary key-value metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n /** Relationships to other memories in the knowledge graph. */\n relationships: z\n .array(\n z.object({\n /** UUID of the target memory. */\n targetMemoryId: z.string().uuid(),\n /** Type of relationship to the target memory. */\n relationshipType: RelationshipType,\n /** Relationship strength from 0 to 1. Defaults to 1.0. */\n weight: z.number().min(0).max(1).default(1.0),\n /** Arbitrary metadata for the relationship edge. */\n metadata: z.record(z.unknown()).default({}),\n }),\n )\n .default([]),\n /** Time-to-live in seconds. Memory auto-deletes after this duration. */\n ttlSeconds: z.number().int().positive().optional(),\n /** Importance score from 0 to 1. Influences recall ranking. */\n importance: z.number().min(0).max(1).optional(),\n});\n\n/** Parsed type for a store-memory request. */\nexport type StoreMemoryRequest = z.infer<typeof StoreMemoryRequest>;\n\n/**\n * Schema for recalling memories by semantic similarity.\n *\n * @example\n * ```ts\n * const request = RecallRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * topK: 5,\n * });\n * ```\n */\nexport const RecallRequest = z.object({\n /** UUID of the agent whose memories to search. */\n agentId: z.string().uuid(),\n /** Natural-language query for semantic similarity search. */\n query: z.string().optional(),\n /** Filter results to a specific memory type. */\n memoryType: z.string().optional(),\n /** Additional metadata filters. */\n filters: z.record(z.unknown()).optional(),\n /** Maximum number of results to return (1-100, default 10). */\n topK: z.number().int().min(1).max(100).default(10),\n /** Minimum similarity score threshold (0-1, default 0). */\n similarityThreshold: z.number().min(0).max(1).default(0),\n /** ISO 8601 timestamp for temporal queries (point-in-time recall). */\n asOf: z.string().datetime().optional(),\n /** Whether to include soft-deleted memories. */\n includeDeleted: z.boolean().default(false),\n});\n\n/** Parsed type for a recall request. */\nexport type RecallRequest = z.infer<typeof RecallRequest>;\n\n/**\n * Schema for forgetting (deleting) memories.\n *\n * @example\n * ```ts\n * const request = ForgetRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * memoryId: \"mem-123\",\n * hardDelete: true,\n * });\n * ```\n */\nexport const ForgetRequest = z.object({\n /** UUID of the agent that owns the memories. */\n agentId: z.string().uuid(),\n /** UUID of a single memory to delete. */\n memoryId: z.string().uuid().optional(),\n /** UUIDs of multiple memories to delete in one call. */\n memoryIds: z.array(z.string().uuid()).optional(),\n /** If true, permanently deletes (vs. soft-delete). Defaults to false. */\n hardDelete: z.boolean().default(false),\n /** If true, also deletes related memories. Defaults to false. */\n cascade: z.boolean().default(false),\n /** Optional reason for the deletion (stored in audit log). */\n reason: z.string().optional(),\n});\n\n/** Parsed type for a forget request. */\nexport type ForgetRequest = z.infer<typeof ForgetRequest>;\n\n// --- Response schemas ---\n\n/**\n * Schema for a single memory object returned by the API.\n *\n * Used by {@link Z3rnoClient.store}, {@link Z3rnoClient.getMemory}, and\n * {@link Z3rnoClient.updateMemory}.\n */\nexport const MemoryResponse = z.object({\n /** Unique identifier for this memory. */\n id: z.string(),\n /** UUID of the owning agent. */\n agent_id: z.string(),\n /** Text content of the memory. */\n content: z.string(),\n /** Category of the memory. */\n memory_type: z.string(),\n /** Server-computed importance score (0-1). */\n importance_score: z.number(),\n /** Number of times this memory has been recalled. */\n recall_count: z.number(),\n /** Name of the embedding model used, if any. */\n embedding_model: z.string().nullable().optional(),\n /** ISO 8601 creation timestamp. */\n created_at: z.string(),\n /** Arbitrary metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a memory response. */\nexport type MemoryResponse = z.infer<typeof MemoryResponse>;\n\n/**\n * Schema for a single item in recall results.\n *\n * Each item includes similarity, importance, and relevance scores\n * computed by the server's ranking algorithm.\n */\nexport const RecallResultItem = z.object({\n /** Unique identifier of the recalled memory. */\n memory_id: z.string(),\n /** Text content of the memory. */\n content: z.string(),\n /** Optional server-generated summary. */\n summary: z.string().nullable().optional(),\n /** Category of the memory. */\n memory_type: z.string(),\n /** Cosine similarity to the query (0-1). */\n similarity_score: z.number(),\n /** Server-computed importance score (0-1). */\n importance_score: z.number(),\n /** Combined relevance score used for ranking (0-1). */\n relevance_score: z.number(),\n /** Number of times this memory has been recalled. */\n recall_count: z.number(),\n /** ISO 8601 creation timestamp. */\n created_at: z.string(),\n /** Arbitrary metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a single recall result item. */\nexport type RecallResultItem = z.infer<typeof RecallResultItem>;\n\n/**\n * Schema for the full recall response.\n *\n * Contains an array of ranked results and the total count of matches.\n */\nexport const RecallResponse = z.object({\n /** Ranked list of matching memories. */\n results: z.array(RecallResultItem),\n /** Total number of matches (may exceed `topK`). */\n total: z.number(),\n /** The query that was searched, if any. */\n query: z.string().nullable().optional(),\n});\n\n/** Parsed type for a recall response. */\nexport type RecallResponse = z.infer<typeof RecallResponse>;\n\n/**\n * Schema for the forget (delete) response.\n *\n * Reports how many memories were deleted and whether cascade was applied.\n */\nexport const ForgetResponse = z.object({\n /** Number of memories deleted. */\n deleted_count: z.number(),\n /** Whether a hard delete was performed. */\n hard_deleted: z.boolean(),\n /** Number of related memories deleted via cascade. */\n cascade_count: z.number(),\n /** IDs of all deleted memories. */\n memory_ids: z.array(z.string()),\n});\n\n/** Parsed type for a forget response. */\nexport type ForgetResponse = z.infer<typeof ForgetResponse>;\n\n/**\n * Schema for a single audit log entry.\n *\n * Audit entries record every operation performed on the agent's memories.\n */\nexport const AuditEntry = z.object({\n /** Auto-incrementing audit entry ID. */\n id: z.number(),\n /** UUID of the agent, if applicable. */\n agent_id: z.string().nullable().optional(),\n /** UUID of the user, if applicable. */\n user_id: z.string().nullable().optional(),\n /** Operation type (e.g., `\"store\"`, `\"recall\"`, `\"forget\"`). */\n operation: z.string(),\n /** UUID of the affected memory, if applicable. */\n memory_id: z.string().nullable().optional(),\n /** Memory type of the affected memory, if applicable. */\n memory_type: z.string().nullable().optional(),\n /** Additional details about the operation. */\n details: z.record(z.unknown()).default({}),\n /** IP address of the caller, if available. */\n ip_address: z.string().nullable().optional(),\n /** ISO 8601 timestamp of the operation. */\n created_at: z.string(),\n});\n\n/** Parsed type for an audit entry. */\nexport type AuditEntry = z.infer<typeof AuditEntry>;\n\n/**\n * Schema for a paginated audit log response.\n *\n * Supports cursor-based pagination via `page` and `page_size`.\n */\nexport const AuditPageResponse = z.object({\n /** Audit entries on this page. */\n entries: z.array(AuditEntry),\n /** Total number of matching audit entries. */\n total: z.number(),\n /** Current page number (1-indexed). */\n page: z.number(),\n /** Number of entries per page. */\n page_size: z.number(),\n /** Whether more pages are available. */\n has_next: z.boolean(),\n});\n\n/** Parsed type for a paginated audit response. */\nexport type AuditPageResponse = z.infer<typeof AuditPageResponse>;\n\n// --- Batch Store ---\n\n/**\n * Schema for the batch store response.\n *\n * Returned by {@link Z3rnoClient.storeBatch} after storing multiple memories.\n */\nexport const BatchStoreResponse = z.object({\n /** Array of stored memory objects. */\n results: z.array(MemoryResponse),\n /** Number of memories successfully stored. */\n stored_count: z.number(),\n});\n\n/** Parsed type for a batch store response. */\nexport type BatchStoreResponse = z.infer<typeof BatchStoreResponse>;\n\n// --- Memory History ---\n\n/**\n * Schema for a single version of a memory (temporal versioning).\n *\n * Each version represents the state of a memory during a specific time range.\n */\nexport const MemoryVersion = z.object({\n /** Version identifier. */\n id: z.string(),\n /** Text content at this version. */\n content: z.string(),\n /** Memory type at this version. */\n memory_type: z.string(),\n /** Importance score at this version. */\n importance_score: z.number(),\n /** ISO 8601 timestamp when this version became active. */\n valid_from: z.string(),\n /** ISO 8601 timestamp when this version was superseded, or null if current. */\n valid_to: z.string().nullable().optional(),\n /** Metadata at this version. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a memory version. */\nexport type MemoryVersion = z.infer<typeof MemoryVersion>;\n\n/**\n * Schema for the memory history response.\n *\n * Contains all temporal versions of a single memory, ordered chronologically.\n */\nexport const MemoryHistoryResponse = z.object({\n /** UUID of the memory. */\n memory_id: z.string(),\n /** Chronologically ordered list of versions. */\n versions: z.array(MemoryVersion),\n /** Total number of versions. */\n total: z.number(),\n});\n\n/** Parsed type for a memory history response. */\nexport type MemoryHistoryResponse = z.infer<typeof MemoryHistoryResponse>;\n\n// --- Sessions ---\n\n/**\n * Schema for a session response.\n *\n * Sessions group related memory operations (e.g., a conversation turn).\n */\nexport const SessionResponse = z.object({\n /** Unique session identifier. */\n session_id: z.string(),\n /** UUID of the agent this session belongs to. */\n agent_id: z.string(),\n /** Type of session (e.g., `\"conversation\"`). */\n session_type: z.string(),\n /** ISO 8601 timestamp when the session started. */\n started_at: z.string(),\n /** Arbitrary session metadata. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a session response. */\nexport type SessionResponse = z.infer<typeof SessionResponse>;\n\n/**\n * Schema for the end-session response.\n *\n * Returned when a session is closed, including summary statistics.\n */\nexport const EndSessionResponse = z.object({\n /** The session that was ended. */\n session_id: z.string(),\n /** ISO 8601 timestamp when the session ended. */\n ended_at: z.string(),\n /** Total duration of the session in seconds. */\n duration_seconds: z.number(),\n /** Number of memories created during the session. */\n memory_count: z.number(),\n});\n\n/** Parsed type for an end-session response. */\nexport type EndSessionResponse = z.infer<typeof EndSessionResponse>;\n","/**\n * Z3rno TypeScript SDK client.\n *\n * Thin fetch wrapper — no database drivers, no embedding providers.\n * Works in Node.js 18+, Deno, Bun, and modern browsers (any runtime\n * with a global `fetch` and `AbortController`).\n *\n * @module client\n *\n * @example\n * ```ts\n * const client = new Z3rnoClient({ baseUrl: \"http://localhost:8000\", apiKey: \"z3rno_sk_...\" });\n * const memory = await client.store({ agentId: \"agent-1\", content: \"User prefers dark mode\" });\n * const results = await client.recall({ agentId: \"agent-1\", query: \"user preferences\" });\n * await client.forget({ agentId: \"agent-1\", memoryId: memory.id });\n * ```\n */\n\nimport {\n AuthenticationError,\n NotFoundError,\n RateLimitError,\n ServerError,\n ValidationError,\n Z3rnoConnectionError,\n Z3rnoError,\n Z3rnoTimeoutError,\n} from \"./errors.js\";\nimport type {\n AuditPageResponse,\n BatchStoreResponse,\n EndSessionResponse,\n ForgetResponse,\n MemoryHistoryResponse,\n MemoryResponse,\n RecallResponse,\n SessionResponse,\n StoreMemoryRequest,\n} from \"./models.js\";\nimport {\n AuditPageResponse as AuditPageSchema,\n BatchStoreResponse as BatchStoreSchema,\n EndSessionResponse as EndSessionSchema,\n ForgetResponse as ForgetSchema,\n MemoryHistoryResponse as MemoryHistorySchema,\n MemoryResponse as MemorySchema,\n RecallResponse as RecallSchema,\n SessionResponse as SessionSchema,\n} from \"./models.js\";\n\n/**\n * Configuration options for the {@link Z3rnoClient}.\n *\n * All fields are optional. When omitted, the client reads from environment\n * variables (`Z3RNO_BASE_URL`, `Z3RNO_API_KEY`) or uses sensible defaults.\n */\nexport interface Z3rnoClientConfig {\n /**\n * Base URL of the Z3rno API.\n *\n * Falls back to the `Z3RNO_BASE_URL` environment variable, then\n * to `\"https://api.z3rno.dev\"`.\n */\n baseUrl?: string;\n\n /**\n * API key for authentication.\n *\n * Falls back to the `Z3RNO_API_KEY` environment variable, then to\n * an empty string (unauthenticated).\n */\n apiKey?: string;\n\n /**\n * Request timeout in milliseconds.\n *\n * @defaultValue 30000 (30 seconds)\n */\n timeout?: number;\n\n /**\n * Maximum number of retry attempts for retryable errors (5xx, 429,\n * network failures, timeouts).\n *\n * @defaultValue 3\n */\n maxRetries?: number;\n\n /**\n * Custom fetch implementation.\n *\n * Defaults to `globalThis.fetch`. Override to use `undici`, `node-fetch`,\n * or a test double.\n *\n * @defaultValue globalThis.fetch\n */\n fetch?: typeof globalThis.fetch;\n\n /**\n * Intercept outgoing requests before they are sent.\n *\n * Use this to add custom headers, log requests, or collect metrics.\n * The callback receives the URL and the `RequestInit` and must return\n * a (possibly modified) `RequestInit`.\n */\n onRequest?: (url: string, init: RequestInit) => RequestInit;\n\n /**\n * Intercept responses before they are processed.\n *\n * Use this for logging, metrics, or response transformation.\n * The callback receives the `Response` and must return a `Response`.\n */\n onResponse?: (response: Response) => Response;\n}\n\n/**\n * Client for the Z3rno AI agent memory API.\n *\n * Uses the standard Fetch API under the hood, making it compatible with\n * Node.js 18+, Deno, Bun, and modern browsers. All responses are\n * validated at runtime with Zod schemas.\n *\n * @example\n * ```ts\n * import { Z3rnoClient } from \"@z3rno/sdk\";\n *\n * const client = new Z3rnoClient({\n * baseUrl: \"http://localhost:8000\",\n * apiKey: \"z3rno_sk_test_...\",\n * });\n *\n * // Store a memory\n * const mem = await client.store({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * });\n *\n * // Recall relevant memories\n * const results = await client.recall({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * });\n * ```\n */\nexport class Z3rnoClient {\n private baseUrl: string;\n private apiKey: string;\n private timeout: number;\n private maxRetries: number;\n private fetchImpl: typeof globalThis.fetch;\n private onRequest?: (url: string, init: RequestInit) => RequestInit;\n private onResponse?: (response: Response) => Response;\n\n /**\n * Creates a new Z3rno client instance.\n *\n * @param config - Client configuration options. All fields are optional.\n *\n * @example\n * ```ts\n * // Explicit configuration\n * const client = new Z3rnoClient({\n * baseUrl: \"http://localhost:8000\",\n * apiKey: \"z3rno_sk_test_...\",\n * timeout: 10000,\n * maxRetries: 2,\n * });\n *\n * // Or rely on environment variables (Z3RNO_BASE_URL, Z3RNO_API_KEY)\n * const client = new Z3rnoClient();\n * ```\n */\n constructor(config: Z3rnoClientConfig = {}) {\n // Resolve baseUrl: explicit > env var > default\n let resolvedUrl = config.baseUrl ?? \"\";\n if (!resolvedUrl && typeof process !== \"undefined\" && process.env) {\n resolvedUrl = process.env.Z3RNO_BASE_URL ?? \"\";\n }\n if (!resolvedUrl) {\n resolvedUrl = \"https://api.z3rno.dev\";\n }\n this.baseUrl = resolvedUrl.replace(/\\/$/, \"\");\n\n // Resolve apiKey: explicit > env var > empty\n let resolvedKey = config.apiKey ?? \"\";\n if (!resolvedKey && typeof process !== \"undefined\" && process.env) {\n resolvedKey = process.env.Z3RNO_API_KEY ?? \"\";\n }\n this.apiKey = resolvedKey;\n\n this.timeout = config.timeout ?? 30000;\n this.maxRetries = config.maxRetries ?? 3;\n this.fetchImpl = config.fetch ?? globalThis.fetch;\n this.onRequest = config.onRequest;\n this.onResponse = config.onResponse;\n }\n\n // --- Store ---\n\n /**\n * Stores a new memory for an agent.\n *\n * The server generates an embedding for the content and stores it in\n * the vector database. The memory is immediately available for recall.\n *\n * @param request - The memory to store.\n * @returns The stored memory, including the server-generated ID and scores.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link ValidationError} If the request body is invalid.\n * @throws {@link Z3rnoTimeoutError} If the request times out.\n *\n * @example\n * ```ts\n * const memory = await client.store({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * memoryType: \"semantic\",\n * metadata: { source: \"settings-page\" },\n * });\n * console.log(memory.id); // \"mem-abc123\"\n * ```\n */\n async store(request: StoreMemoryRequest): Promise<MemoryResponse> {\n const body = {\n agent_id: request.agentId,\n content: request.content,\n memory_type: request.memoryType,\n user_id: request.userId,\n metadata: request.metadata,\n relationships: request.relationships?.map((r) => ({\n target_memory_id: r.targetMemoryId,\n relationship_type: r.relationshipType,\n weight: r.weight,\n metadata: r.metadata,\n })),\n ttl_seconds: request.ttlSeconds,\n importance: request.importance,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories\", body);\n return MemorySchema.parse(resp);\n }\n\n // --- Recall ---\n\n /**\n * Recalls memories by semantic similarity to a query.\n *\n * Returns a ranked list of memories sorted by a combined relevance score\n * that factors in similarity, importance, and recency.\n *\n * @param params - Recall parameters including the query and filters.\n * @param params.agentId - UUID of the agent whose memories to search.\n * @param params.query - Natural-language query for semantic search.\n * @param params.memoryType - Filter by memory type.\n * @param params.filters - Additional metadata filters.\n * @param params.topK - Maximum results to return (default 10).\n * @param params.similarityThreshold - Minimum similarity score (default 0).\n * @returns Ranked recall results with similarity scores.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link Z3rnoTimeoutError} If the request times out.\n *\n * @example\n * ```ts\n * const results = await client.recall({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * topK: 5,\n * similarityThreshold: 0.7,\n * });\n * for (const item of results.results) {\n * console.log(`${item.content} (score: ${item.relevance_score})`);\n * }\n * ```\n */\n async recall(params: {\n agentId: string;\n query?: string;\n memoryType?: string;\n filters?: Record<string, unknown>;\n topK?: number;\n similarityThreshold?: number;\n }): Promise<RecallResponse> {\n const body = {\n agent_id: params.agentId,\n query: params.query,\n memory_type: params.memoryType,\n filters: params.filters,\n top_k: params.topK ?? 10,\n similarity_threshold: params.similarityThreshold ?? 0,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/recall\", body);\n return RecallSchema.parse(resp);\n }\n\n // --- Forget ---\n\n /**\n * Forgets (deletes) one or more memories.\n *\n * By default, performs a soft delete (marks as deleted but retains data).\n * Set `hardDelete: true` for permanent removal. Use `cascade: true` to\n * also delete related memories in the knowledge graph.\n *\n * @param params - Forget parameters.\n * @param params.agentId - UUID of the agent that owns the memories.\n * @param params.memoryId - UUID of a single memory to delete.\n * @param params.memoryIds - UUIDs of multiple memories to delete.\n * @param params.hardDelete - Permanently delete (default false).\n * @param params.cascade - Delete related memories too (default false).\n * @param params.reason - Reason for deletion (stored in audit log).\n * @returns Summary of the deletion operation.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link NotFoundError} If the specified memory does not exist.\n *\n * @example\n * ```ts\n * const result = await client.forget({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * memoryId: \"mem-abc123\",\n * hardDelete: true,\n * reason: \"User requested data deletion\",\n * });\n * console.log(`Deleted ${result.deleted_count} memories`);\n * ```\n */\n async forget(params: {\n agentId: string;\n memoryId?: string;\n memoryIds?: string[];\n hardDelete?: boolean;\n cascade?: boolean;\n reason?: string;\n }): Promise<ForgetResponse> {\n const body = {\n agent_id: params.agentId,\n memory_id: params.memoryId,\n memory_ids: params.memoryIds,\n hard_delete: params.hardDelete ?? false,\n cascade: params.cascade ?? false,\n reason: params.reason,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/forget\", body);\n return ForgetSchema.parse(resp);\n }\n\n // --- Get Memory ---\n\n /**\n * Retrieves a single memory by its ID.\n *\n * @param memoryId - The unique identifier of the memory to retrieve.\n * @returns The full memory object.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const memory = await client.getMemory(\"mem-abc123\");\n * console.log(memory.content);\n * console.log(memory.importance_score);\n * ```\n */\n async getMemory(memoryId: string): Promise<MemoryResponse> {\n const resp = await this.request(\"GET\", `/v1/memories/${memoryId}`);\n return MemorySchema.parse(resp);\n }\n\n // --- Store Batch ---\n\n /**\n * Stores multiple memories in a single API call.\n *\n * More efficient than calling {@link store} in a loop. All memories are\n * processed atomically on the server.\n *\n * @param memories - Array of memories to store.\n * @returns The stored memories and a count of how many were created.\n * @throws {@link ValidationError} If any memory in the batch is invalid.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const result = await client.storeBatch([\n * { agentId: \"agent-1\", content: \"Fact one\" },\n * { agentId: \"agent-1\", content: \"Fact two\", memoryType: \"semantic\" },\n * ]);\n * console.log(`Stored ${result.stored_count} memories`);\n * ```\n */\n async storeBatch(\n memories: StoreMemoryRequest[],\n ): Promise<BatchStoreResponse> {\n const body = {\n memories: memories.map((m) => ({\n agent_id: m.agentId,\n content: m.content,\n memory_type: m.memoryType,\n metadata: m.metadata,\n importance: m.importance,\n })),\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/batch\", body);\n return BatchStoreSchema.parse(resp);\n }\n\n // --- Memory History ---\n\n /**\n * Retrieves the full version history of a memory.\n *\n * Z3rno uses temporal versioning — every update creates a new version\n * rather than overwriting. This method returns all versions ordered\n * chronologically.\n *\n * @param memoryId - The unique identifier of the memory.\n * @returns All versions of the memory with validity timestamps.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const history = await client.getMemoryHistory(\"mem-abc123\");\n * for (const version of history.versions) {\n * console.log(`${version.valid_from}: ${version.content}`);\n * }\n * ```\n */\n async getMemoryHistory(memoryId: string): Promise<MemoryHistoryResponse> {\n const resp = await this.request(\"GET\", `/v1/memories/${memoryId}/history`);\n return MemoryHistorySchema.parse(resp);\n }\n\n // --- Update Memory ---\n\n /**\n * Updates an existing memory's content, metadata, or importance.\n *\n * Creates a new temporal version of the memory. The previous version\n * remains accessible via {@link getMemoryHistory}.\n *\n * @param memoryId - The unique identifier of the memory to update.\n * @param updates - Fields to update (only provided fields are changed).\n * @param updates.content - New text content.\n * @param updates.metadata - New metadata (replaces existing metadata).\n * @param updates.importance - New importance score (0-1).\n * @returns The updated memory object.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link ValidationError} If the update values are invalid.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const updated = await client.updateMemory(\"mem-abc123\", {\n * content: \"User now prefers light mode\",\n * importance: 0.9,\n * });\n * ```\n */\n async updateMemory(\n memoryId: string,\n updates: {\n content?: string;\n metadata?: Record<string, unknown>;\n importance?: number;\n },\n ): Promise<MemoryResponse> {\n const body: Record<string, unknown> = {};\n if (updates.content !== undefined) body.content = updates.content;\n if (updates.metadata !== undefined) body.metadata = updates.metadata;\n if (updates.importance !== undefined) body.importance = updates.importance;\n\n const resp = await this.request(\"PATCH\", `/v1/memories/${memoryId}`, body);\n return MemorySchema.parse(resp);\n }\n\n // --- Sessions ---\n\n /**\n * Starts a new session for grouping related memory operations.\n *\n * Sessions are useful for tracking conversation turns or task boundaries.\n * Memories created during a session are automatically associated with it.\n *\n * @param params - Session parameters.\n * @param params.agentId - UUID of the agent to start the session for.\n * @param params.sessionType - Type of session (default `\"conversation\"`).\n * @returns The created session with its ID and start time.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const session = await client.startSession({ agentId: \"agent-1\" });\n * console.log(`Session started: ${session.session_id}`);\n * // ... perform operations ...\n * await client.endSession(session.session_id);\n * ```\n */\n async startSession(params: {\n agentId: string;\n sessionType?: string;\n }): Promise<SessionResponse> {\n const body = {\n agent_id: params.agentId,\n session_type: params.sessionType ?? \"conversation\",\n };\n\n const resp = await this.request(\"POST\", \"/v1/sessions\", body);\n return SessionSchema.parse(resp);\n }\n\n /**\n * Ends an active session.\n *\n * Returns summary statistics including the session duration and the\n * number of memories created during the session.\n *\n * @param sessionId - The unique identifier of the session to end.\n * @returns Session summary with duration and memory count.\n * @throws {@link NotFoundError} If no active session exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const summary = await client.endSession(\"sess-abc123\");\n * console.log(`Session lasted ${summary.duration_seconds}s, ${summary.memory_count} memories`);\n * ```\n */\n async endSession(sessionId: string): Promise<EndSessionResponse> {\n const resp = await this.request(\"POST\", `/v1/sessions/${sessionId}/end`);\n return EndSessionSchema.parse(resp);\n }\n\n // --- Audit ---\n\n /**\n * Retrieves a paginated audit log of memory operations.\n *\n * The audit log records every store, recall, forget, and update operation\n * performed by any agent. Useful for compliance, debugging, and analytics.\n *\n * @param params - Optional pagination and filter parameters.\n * @param params.agentId - Filter by agent UUID.\n * @param params.page - Page number (1-indexed).\n * @param params.pageSize - Number of entries per page.\n * @returns A page of audit log entries with pagination metadata.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const page = await client.audit({ agentId: \"agent-1\", page: 1, pageSize: 20 });\n * for (const entry of page.entries) {\n * console.log(`${entry.created_at}: ${entry.operation} on ${entry.memory_id}`);\n * }\n * if (page.has_next) {\n * const nextPage = await client.audit({ agentId: \"agent-1\", page: 2 });\n * }\n * ```\n */\n async audit(params?: {\n agentId?: string;\n page?: number;\n pageSize?: number;\n }): Promise<AuditPageResponse> {\n const searchParams = new URLSearchParams();\n if (params?.agentId) searchParams.set(\"agent_id\", params.agentId);\n if (params?.page) searchParams.set(\"page\", String(params.page));\n if (params?.pageSize)\n searchParams.set(\"page_size\", String(params.pageSize));\n\n const query = searchParams.toString();\n const path = query ? `/v1/audit?${query}` : \"/v1/audit\";\n const resp = await this.request(\"GET\", path);\n return AuditPageSchema.parse(resp);\n }\n\n // --- HTTP layer ---\n\n private async request(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<unknown> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const url = `${this.baseUrl}${path}`;\n let init: RequestInit = {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"@z3rno/sdk/0.0.1\",\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n };\n\n if (this.onRequest) {\n init = this.onRequest(url, init);\n }\n\n let response = await this.fetchImpl(url, init);\n\n if (this.onResponse) {\n response = this.onResponse(response);\n }\n\n clearTimeout(timeoutId);\n\n // On 429, honor Retry-After header and retry\n if (response.status === 429 && attempt < this.maxRetries) {\n const retryAfter = parseInt(\n response.headers.get(\"Retry-After\") ?? \"1\",\n 10,\n );\n await this.sleep(retryAfter * 1000);\n continue;\n }\n\n // On 5xx, retry with exponential backoff\n if (response.status >= 500 && attempt < this.maxRetries) {\n const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s\n await this.sleep(delay);\n continue;\n }\n\n return this.handleResponse(response);\n } catch (error) {\n clearTimeout(timeoutId);\n\n // Do not retry Z3rnoError subclasses (4xx client errors)\n if (error instanceof Z3rnoError) throw error;\n\n // Classify the error before deciding whether to retry\n if (error instanceof DOMException && error.name === \"AbortError\") {\n lastError = new Z3rnoTimeoutError(\n `Request timed out after ${this.timeout}ms`,\n this.timeout,\n );\n } else if (error instanceof TypeError) {\n lastError = new Z3rnoConnectionError(\n `Connection failed: ${error.message}`,\n );\n } else {\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n\n if (attempt < this.maxRetries) {\n const delay = Math.pow(2, attempt) * 1000;\n await this.sleep(delay);\n continue;\n }\n }\n }\n\n // After all retries exhausted, throw the last classified error\n if (lastError instanceof Z3rnoError) {\n throw lastError;\n }\n throw new Z3rnoError(\n `Request failed after ${this.maxRetries + 1} attempts: ${String(lastError)}`,\n );\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private async handleResponse(resp: Response): Promise<unknown> {\n if (resp.ok) {\n return resp.json();\n }\n\n let detail = resp.statusText;\n try {\n const text = await resp.text();\n try {\n const body = JSON.parse(text) as Record<string, unknown>;\n detail = String(body.detail ?? body.error ?? resp.statusText);\n } catch {\n // Response is not JSON (e.g., nginx HTML 502). Include the\n // beginning of the body so users can diagnose proxy/gateway issues.\n if (text.length > 0) {\n const preview = text.length > 200 ? text.slice(0, 200) + \"...\" : text;\n detail = `${resp.statusText} — ${preview}`;\n }\n }\n } catch {\n // Could not read body at all\n }\n\n switch (resp.status) {\n case 401:\n throw new AuthenticationError(`Authentication failed: ${detail}`);\n case 404:\n throw new NotFoundError(`Not found: ${detail}`);\n case 429: {\n const retryAfter = parseInt(\n resp.headers.get(\"Retry-After\") ?? \"60\",\n 10,\n );\n throw new RateLimitError(`Rate limit exceeded: ${detail}`, retryAfter);\n }\n case 400:\n case 422:\n throw new ValidationError(detail, resp.status);\n default:\n if (resp.status >= 500) {\n throw new ServerError(`Server error: ${detail}`, resp.status);\n }\n throw new Z3rnoError(\n `Unexpected error (${resp.status}): ${detail}`,\n resp.status,\n );\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/models.ts","../src/client.ts"],"names":["z"],"mappings":";;;;;AA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A,MAChD,KAAK,GAAA,EAAK;AACR,QAAA,MAAM,UAAA,GAAa,QAAA;AAAA,UACjB,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA,IAAK,IAAA;AAAA,UACnC;AAAA,SACF;AACA,QAAA,MAAM,IAAI,cAAA,CAAe,CAAA,qBAAA,EAAwB,MAAM,IAAI,UAAU,CAAA;AAAA,MACvE;AAAA,MACA,KAAK,GAAA;AAAA,MACL,KAAK,GAAA;AACH,QAAA,MAAM,IAAI,eAAA,CAAgB,MAAA,EAAQ,IAAA,CAAK,MAAM,CAAA;AAAA,MAC/C;AACE,QAAA,IAAI,IAAA,CAAK,UAAU,GAAA,EAAK;AACtB,UAAA,MAAM,IAAI,WAAA,CAAY,CAAA,cAAA,EAAiB,MAAM,CAAA,CAAA,EAAI,KAAK,MAAM,CAAA;AAAA,QAC9D;AACA,QAAA,MAAM,IAAI,UAAA;AAAA,UACR,CAAA,kBAAA,EAAqB,IAAA,CAAK,MAAM,CAAA,GAAA,EAAM,MAAM,CAAA,CAAA;AAAA,UAC5C,IAAA,CAAK;AAAA,SACP;AAAA;AACJ,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Z3rno SDK error hierarchy.\n *\n * All errors thrown by the SDK extend {@link Z3rnoError}, which itself extends\n * the built-in `Error` class. This lets callers catch broadly (`Z3rnoError`)\n * or narrowly (`AuthenticationError`, `RateLimitError`, etc.).\n *\n * @module errors\n */\n\n/**\n * Base error class for all Z3rno SDK errors.\n *\n * Every error produced by the SDK is an instance of this class, so you can\n * use a single `catch (e) { if (e instanceof Z3rnoError) ... }` guard to\n * handle them all.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoError) {\n * console.error(`Z3rno error (${e.statusCode}): ${e.message}`);\n * }\n * }\n * ```\n */\nexport class Z3rnoError extends Error {\n /** HTTP status code returned by the server, if applicable. */\n statusCode?: number;\n\n /**\n * @param message - Human-readable description of the error.\n * @param statusCode - HTTP status code associated with the error, if any.\n */\n constructor(message: string, statusCode?: number) {\n super(message);\n this.name = \"Z3rnoError\";\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Thrown when the API key is missing, invalid, or revoked (HTTP 401).\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof AuthenticationError) {\n * console.error(\"Check your API key\");\n * }\n * }\n * ```\n */\nexport class AuthenticationError extends Z3rnoError {\n /**\n * @param message - Description of the authentication failure.\n */\n constructor(message: string) {\n super(message, 401);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Thrown when the client exceeds the API rate limit (HTTP 429).\n *\n * The {@link retryAfter} property indicates how many seconds to wait\n * before retrying, as reported by the server's `Retry-After` header.\n *\n * @example\n * ```ts\n * try {\n * await client.recall({ agentId: \"...\", query: \"...\" });\n * } catch (e) {\n * if (e instanceof RateLimitError) {\n * console.log(`Retry after ${e.retryAfter} seconds`);\n * }\n * }\n * ```\n */\nexport class RateLimitError extends Z3rnoError {\n /** Number of seconds to wait before retrying, per the Retry-After header. */\n retryAfter: number;\n\n /**\n * @param message - Description of the rate-limit error.\n * @param retryAfter - Seconds to wait before retrying (defaults to 60).\n */\n constructor(message: string, retryAfter: number = 60) {\n super(message, 429);\n this.name = \"RateLimitError\";\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Thrown when the server rejects the request due to invalid input (HTTP 400 or 422).\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"not-a-uuid\", content: \"\" });\n * } catch (e) {\n * if (e instanceof ValidationError) {\n * console.error(`Validation failed: ${e.message}`);\n * }\n * }\n * ```\n */\nexport class ValidationError extends Z3rnoError {\n /**\n * @param message - Description of the validation failure.\n * @param statusCode - HTTP status code (400 or 422, defaults to 400).\n */\n constructor(message: string, statusCode: number = 400) {\n super(message, statusCode);\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Thrown when the requested resource does not exist (HTTP 404).\n *\n * @example\n * ```ts\n * try {\n * await client.getMemory(\"non-existent-id\");\n * } catch (e) {\n * if (e instanceof NotFoundError) {\n * console.error(\"Memory not found\");\n * }\n * }\n * ```\n */\nexport class NotFoundError extends Z3rnoError {\n /**\n * @param message - Description of what was not found.\n */\n constructor(message: string) {\n super(message, 404);\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * Thrown when the Z3rno API returns a server-side error (HTTP 5xx).\n *\n * The SDK automatically retries on 5xx errors with exponential backoff.\n * This error is only thrown after all retries are exhausted.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof ServerError) {\n * console.error(`Server error (${e.statusCode}): ${e.message}`);\n * }\n * }\n * ```\n */\nexport class ServerError extends Z3rnoError {\n /**\n * @param message - Description of the server error.\n * @param statusCode - HTTP status code (defaults to 500).\n */\n constructor(message: string, statusCode: number = 500) {\n super(message, statusCode);\n this.name = \"ServerError\";\n }\n}\n\n/**\n * Thrown when a request exceeds the configured timeout duration.\n *\n * The SDK uses an {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController | AbortController}\n * to enforce timeouts. This error is thrown after all retries are exhausted.\n *\n * @example\n * ```ts\n * const client = new Z3rnoClient({ timeout: 5000 }); // 5 seconds\n * try {\n * await client.recall({ agentId: \"...\", query: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoTimeoutError) {\n * console.error(`Timed out after ${e.timeout}ms`);\n * }\n * }\n * ```\n */\nexport class Z3rnoTimeoutError extends Z3rnoError {\n /** The timeout duration in milliseconds that was exceeded. */\n timeout: number;\n\n /**\n * @param message - Description of the timeout.\n * @param timeout - The configured timeout value in milliseconds.\n */\n constructor(message: string, timeout: number) {\n super(message, undefined);\n this.name = \"Z3rnoTimeoutError\";\n this.timeout = timeout;\n }\n}\n\n/**\n * Thrown when the SDK cannot establish a connection to the Z3rno API.\n *\n * This typically indicates a network issue, DNS failure, or the server\n * being unreachable. The SDK retries connection errors with exponential\n * backoff before throwing this error.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoConnectionError) {\n * console.error(\"Cannot reach Z3rno API — check your network\");\n * }\n * }\n * ```\n */\nexport class Z3rnoConnectionError extends Z3rnoError {\n /**\n * @param message - Description of the connection failure.\n */\n constructor(message: string) {\n super(message, undefined);\n this.name = \"Z3rnoConnectionError\";\n }\n}\n","/**\n * Zod schemas and inferred TypeScript types for the Z3rno API.\n *\n * Each export is a dual: a Zod schema (used for runtime validation) and an\n * identically-named TypeScript type (used at compile time). Request schemas\n * validate client-side input; response schemas validate server payloads.\n *\n * @module models\n */\n\nimport { z } from \"zod\";\n\n// --- Enums ---\n\n/**\n * Memory type enum.\n *\n * Controls how a memory is stored, indexed, and decayed.\n *\n * - `working` — Short-lived scratchpad memory (high decay rate).\n * - `episodic` — Event-based memory tied to a specific interaction.\n * - `semantic` — Long-term factual knowledge.\n * - `procedural` — How-to or process knowledge.\n */\nexport const MemoryType = z.enum([\n \"working\",\n \"episodic\",\n \"semantic\",\n \"procedural\",\n]);\n\n/** Memory type: `\"working\"` | `\"episodic\"` | `\"semantic\"` | `\"procedural\"`. */\nexport type MemoryType = z.infer<typeof MemoryType>;\n\n/**\n * Relationship type enum.\n *\n * Describes how two memories are related in the knowledge graph.\n *\n * - `derived_from` — This memory was created from another.\n * - `contradicts` — This memory conflicts with another.\n * - `supports` — This memory reinforces another.\n * - `supersedes` — This memory replaces another.\n * - `related_to` — General association.\n * - `caused_by` — Causal relationship.\n */\nexport const RelationshipType = z.enum([\n \"derived_from\",\n \"contradicts\",\n \"supports\",\n \"supersedes\",\n \"related_to\",\n \"caused_by\",\n]);\n\n/** Relationship type between two memories. */\nexport type RelationshipType = z.infer<typeof RelationshipType>;\n\n/**\n * Retrieval strategy for `recall({ strategy: ... })` — Phase C.\n *\n * `AUTO` is the default; the server's LLM router picks one of the\n * others when configured. Use an explicit value to bypass routing.\n */\nexport const RetrievalStrategy = z.enum([\n \"AUTO\",\n \"VECTOR\",\n \"LEXICAL\",\n \"GRAPH\",\n \"TRIPLET\",\n \"TRACE\",\n \"TEMPORAL\",\n \"ASK\",\n \"CYPHER\",\n]);\n\n/** Retrieval strategy enum (canonical UPPERCASE names). */\nexport type RetrievalStrategy = z.infer<typeof RetrievalStrategy>;\n\n// --- Request schemas ---\n\n/**\n * Schema for storing a new memory.\n *\n * @example\n * ```ts\n * const request = StoreMemoryRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * memoryType: \"semantic\",\n * });\n * ```\n */\nexport const StoreMemoryRequest = z.object({\n /** UUID of the agent that owns this memory. */\n agentId: z.string().uuid(),\n /** The text content to store (1 to 100,000 characters). */\n content: z.string().min(1).max(100000),\n /** Category of memory. Defaults to `\"episodic\"`. */\n memoryType: MemoryType.default(\"episodic\"),\n /** Optional UUID of the user associated with this memory. */\n userId: z.string().uuid().optional(),\n /** Arbitrary key-value metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n /** Relationships to other memories in the knowledge graph. */\n relationships: z\n .array(\n z.object({\n /** UUID of the target memory. */\n targetMemoryId: z.string().uuid(),\n /** Type of relationship to the target memory. */\n relationshipType: RelationshipType,\n /** Relationship strength from 0 to 1. Defaults to 1.0. */\n weight: z.number().min(0).max(1).default(1.0),\n /** Arbitrary metadata for the relationship edge. */\n metadata: z.record(z.unknown()).default({}),\n }),\n )\n .default([]),\n /** Time-to-live in seconds. Memory auto-deletes after this duration. */\n ttlSeconds: z.number().int().positive().optional(),\n /** Importance score from 0 to 1. Influences recall ranking. */\n importance: z.number().min(0).max(1).optional(),\n});\n\n/** Parsed type for a store-memory request. */\nexport type StoreMemoryRequest = z.infer<typeof StoreMemoryRequest>;\n\n/**\n * Schema for recalling memories by semantic similarity.\n *\n * @example\n * ```ts\n * const request = RecallRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * topK: 5,\n * });\n * ```\n */\nexport const RecallRequest = z.object({\n /** UUID of the agent whose memories to search. */\n agentId: z.string().uuid(),\n /** Natural-language query for semantic similarity search. */\n query: z.string().optional(),\n /** Filter results to a specific memory type. */\n memoryType: z.string().optional(),\n /** Additional metadata filters. */\n filters: z.record(z.unknown()).optional(),\n /** Maximum number of results to return (1-100, default 10). */\n topK: z.number().int().min(1).max(100).default(10),\n /** Minimum similarity score threshold (0-1, default 0). */\n similarityThreshold: z.number().min(0).max(1).default(0),\n /** ISO 8601 timestamp for temporal queries (point-in-time recall). */\n asOf: z.string().datetime().optional(),\n /** Whether to include soft-deleted memories. */\n includeDeleted: z.boolean().default(false),\n /**\n * Phase C retrieval strategy. `AUTO` (default) lets the server's\n * LLM router pick the best fit. See {@link RetrievalStrategy}.\n */\n strategy: RetrievalStrategy.default(\"AUTO\"),\n /**\n * Phase C cross-encoder re-ranking. When `true`, the server\n * re-ranks the top results via a cross-encoder. Requires the\n * `sentence-transformers` extra on the server.\n */\n rerank: z.boolean().default(false),\n});\n\n/** Parsed type for a recall request. */\nexport type RecallRequest = z.infer<typeof RecallRequest>;\n\n/**\n * Schema for forgetting (deleting) memories.\n *\n * @example\n * ```ts\n * const request = ForgetRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * memoryId: \"mem-123\",\n * hardDelete: true,\n * });\n * ```\n */\nexport const ForgetRequest = z.object({\n /** UUID of the agent that owns the memories. */\n agentId: z.string().uuid(),\n /** UUID of a single memory to delete. */\n memoryId: z.string().uuid().optional(),\n /** UUIDs of multiple memories to delete in one call. */\n memoryIds: z.array(z.string().uuid()).optional(),\n /** If true, permanently deletes (vs. soft-delete). Defaults to false. */\n hardDelete: z.boolean().default(false),\n /** If true, also deletes related memories. Defaults to false. */\n cascade: z.boolean().default(false),\n /** Optional reason for the deletion (stored in audit log). */\n reason: z.string().optional(),\n});\n\n/** Parsed type for a forget request. */\nexport type ForgetRequest = z.infer<typeof ForgetRequest>;\n\n// --- Response schemas ---\n\n/**\n * Schema for a single memory object returned by the API.\n *\n * Used by {@link Z3rnoClient.store}, {@link Z3rnoClient.getMemory}, and\n * {@link Z3rnoClient.updateMemory}.\n */\nexport const MemoryResponse = z.object({\n /** Unique identifier for this memory. */\n id: z.string(),\n /** UUID of the owning agent. */\n agent_id: z.string(),\n /** Text content of the memory. */\n content: z.string(),\n /** Category of the memory. */\n memory_type: z.string(),\n /** Server-computed importance score (0-1). */\n importance_score: z.number(),\n /** Number of times this memory has been recalled. */\n recall_count: z.number(),\n /** Name of the embedding model used, if any. */\n embedding_model: z.string().nullable().optional(),\n /** ISO 8601 creation timestamp. */\n created_at: z.string(),\n /** Arbitrary metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a memory response. */\nexport type MemoryResponse = z.infer<typeof MemoryResponse>;\n\n/**\n * Schema for a single item in recall results.\n *\n * Each item includes similarity, importance, and relevance scores\n * computed by the server's ranking algorithm.\n */\nexport const RecallResultItem = z.object({\n /** Unique identifier of the recalled memory. */\n memory_id: z.string(),\n /** Text content of the memory. */\n content: z.string(),\n /** Optional server-generated summary. */\n summary: z.string().nullable().optional(),\n /** Category of the memory. */\n memory_type: z.string(),\n /** Cosine similarity to the query (0-1). */\n similarity_score: z.number(),\n /** Server-computed importance score (0-1). */\n importance_score: z.number(),\n /** Combined relevance score used for ranking (0-1). */\n relevance_score: z.number(),\n /** Number of times this memory has been recalled. */\n recall_count: z.number(),\n /** ISO 8601 creation timestamp. */\n created_at: z.string(),\n /** Arbitrary metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n /**\n * Phase C per-source signals — e.g. `{ vector: 0.83, lexical: 0.61 }`.\n * Optional so older servers (v0.7.x) keep parsing.\n */\n score_components: z.record(z.number()).default({}),\n});\n\n/** Parsed type for a single recall result item. */\nexport type RecallResultItem = z.infer<typeof RecallResultItem>;\n\n/**\n * Schema for the full recall response.\n *\n * Contains an array of ranked results and the total count of matches.\n */\nexport const RecallResponse = z.object({\n /** Ranked list of matching memories. */\n results: z.array(RecallResultItem),\n /** Total number of matches (may exceed `topK`). */\n total: z.number(),\n /** The query that was searched, if any. */\n query: z.string().nullable().optional(),\n /** Phase C: strategy that actually ran (after AUTO routing + re-rank). */\n strategy_used: z.string().default(\"VECTOR\"),\n /** Phase C: AUTO's candidate list (e.g. `[\"AUTO->GRAPH\"]`). */\n strategies_considered: z.array(z.string()).default([]),\n /** Phase C: whether the cross-encoder re-rank ran. */\n reranked: z.boolean().default(false),\n /** Phase C: end-to-end recall latency on the server (ms). */\n elapsed_ms: z.number().default(0),\n});\n\n/** Parsed type for a recall response. */\nexport type RecallResponse = z.infer<typeof RecallResponse>;\n\n/**\n * Schema for the forget (delete) response.\n *\n * Reports how many memories were deleted and whether cascade was applied.\n */\nexport const ForgetResponse = z.object({\n /** Number of memories deleted. */\n deleted_count: z.number(),\n /** Whether a hard delete was performed. */\n hard_deleted: z.boolean(),\n /** Number of related memories deleted via cascade. */\n cascade_count: z.number(),\n /** IDs of all deleted memories. */\n memory_ids: z.array(z.string()),\n});\n\n/** Parsed type for a forget response. */\nexport type ForgetResponse = z.infer<typeof ForgetResponse>;\n\n/**\n * Schema for a single audit log entry.\n *\n * Audit entries record every operation performed on the agent's memories.\n */\nexport const AuditEntry = z.object({\n /** Auto-incrementing audit entry ID. */\n id: z.number(),\n /** UUID of the agent, if applicable. */\n agent_id: z.string().nullable().optional(),\n /** UUID of the user, if applicable. */\n user_id: z.string().nullable().optional(),\n /** Operation type (e.g., `\"store\"`, `\"recall\"`, `\"forget\"`). */\n operation: z.string(),\n /** UUID of the affected memory, if applicable. */\n memory_id: z.string().nullable().optional(),\n /** Memory type of the affected memory, if applicable. */\n memory_type: z.string().nullable().optional(),\n /** Additional details about the operation. */\n details: z.record(z.unknown()).default({}),\n /** IP address of the caller, if available. */\n ip_address: z.string().nullable().optional(),\n /** ISO 8601 timestamp of the operation. */\n created_at: z.string(),\n});\n\n/** Parsed type for an audit entry. */\nexport type AuditEntry = z.infer<typeof AuditEntry>;\n\n/**\n * Schema for a paginated audit log response.\n *\n * Supports cursor-based pagination via `page` and `page_size`.\n */\nexport const AuditPageResponse = z.object({\n /** Audit entries on this page. */\n entries: z.array(AuditEntry),\n /** Total number of matching audit entries. */\n total: z.number(),\n /** Current page number (1-indexed). */\n page: z.number(),\n /** Number of entries per page. */\n page_size: z.number(),\n /** Whether more pages are available. */\n has_next: z.boolean(),\n});\n\n/** Parsed type for a paginated audit response. */\nexport type AuditPageResponse = z.infer<typeof AuditPageResponse>;\n\n// --- Batch Store ---\n\n/**\n * Schema for the batch store response.\n *\n * Returned by {@link Z3rnoClient.storeBatch} after storing multiple memories.\n */\nexport const BatchStoreResponse = z.object({\n /** Array of stored memory objects. */\n results: z.array(MemoryResponse),\n /** Number of memories successfully stored. */\n stored_count: z.number(),\n});\n\n/** Parsed type for a batch store response. */\nexport type BatchStoreResponse = z.infer<typeof BatchStoreResponse>;\n\n// --- Memory History ---\n\n/**\n * Schema for a single version of a memory (temporal versioning).\n *\n * Each version represents the state of a memory during a specific time range.\n */\nexport const MemoryVersion = z.object({\n /** Version identifier. */\n id: z.string(),\n /** Text content at this version. */\n content: z.string(),\n /** Memory type at this version. */\n memory_type: z.string(),\n /** Importance score at this version. */\n importance_score: z.number(),\n /** ISO 8601 timestamp when this version became active. */\n valid_from: z.string(),\n /** ISO 8601 timestamp when this version was superseded, or null if current. */\n valid_to: z.string().nullable().optional(),\n /** Metadata at this version. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a memory version. */\nexport type MemoryVersion = z.infer<typeof MemoryVersion>;\n\n/**\n * Schema for the memory history response.\n *\n * Contains all temporal versions of a single memory, ordered chronologically.\n */\nexport const MemoryHistoryResponse = z.object({\n /** UUID of the memory. */\n memory_id: z.string(),\n /** Chronologically ordered list of versions. */\n versions: z.array(MemoryVersion),\n /** Total number of versions. */\n total: z.number(),\n});\n\n/** Parsed type for a memory history response. */\nexport type MemoryHistoryResponse = z.infer<typeof MemoryHistoryResponse>;\n\n// --- Sessions ---\n\n/**\n * Schema for a session response.\n *\n * Sessions group related memory operations (e.g., a conversation turn).\n */\nexport const SessionResponse = z.object({\n /** Unique session identifier. */\n session_id: z.string(),\n /** UUID of the agent this session belongs to. */\n agent_id: z.string(),\n /** Type of session (e.g., `\"conversation\"`). */\n session_type: z.string(),\n /** ISO 8601 timestamp when the session started. */\n started_at: z.string(),\n /** Arbitrary session metadata. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a session response. */\nexport type SessionResponse = z.infer<typeof SessionResponse>;\n\n/**\n * Schema for the end-session response.\n *\n * Returned when a session is closed, including summary statistics.\n */\nexport const EndSessionResponse = z.object({\n /** The session that was ended. */\n session_id: z.string(),\n /** ISO 8601 timestamp when the session ended. */\n ended_at: z.string(),\n /** Total duration of the session in seconds. */\n duration_seconds: z.number(),\n /** Number of memories created during the session. */\n memory_count: z.number(),\n});\n\n/** Parsed type for an end-session response. */\nexport type EndSessionResponse = z.infer<typeof EndSessionResponse>;\n","/**\n * Z3rno TypeScript SDK client.\n *\n * Thin fetch wrapper — no database drivers, no embedding providers.\n * Works in Node.js 18+, Deno, Bun, and modern browsers (any runtime\n * with a global `fetch` and `AbortController`).\n *\n * @module client\n *\n * @example\n * ```ts\n * const client = new Z3rnoClient({ baseUrl: \"http://localhost:8000\", apiKey: \"z3rno_sk_...\" });\n * const memory = await client.store({ agentId: \"agent-1\", content: \"User prefers dark mode\" });\n * const results = await client.recall({ agentId: \"agent-1\", query: \"user preferences\" });\n * await client.forget({ agentId: \"agent-1\", memoryId: memory.id });\n * ```\n */\n\nimport {\n AuthenticationError,\n NotFoundError,\n RateLimitError,\n ServerError,\n ValidationError,\n Z3rnoConnectionError,\n Z3rnoError,\n Z3rnoTimeoutError,\n} from \"./errors.js\";\nimport type {\n AuditPageResponse,\n BatchStoreResponse,\n EndSessionResponse,\n ForgetResponse,\n MemoryHistoryResponse,\n MemoryResponse,\n RecallResponse,\n SessionResponse,\n StoreMemoryRequest,\n} from \"./models.js\";\nimport {\n AuditPageResponse as AuditPageSchema,\n BatchStoreResponse as BatchStoreSchema,\n EndSessionResponse as EndSessionSchema,\n ForgetResponse as ForgetSchema,\n MemoryHistoryResponse as MemoryHistorySchema,\n MemoryResponse as MemorySchema,\n RecallResponse as RecallSchema,\n SessionResponse as SessionSchema,\n} from \"./models.js\";\n\n/**\n * Configuration options for the {@link Z3rnoClient}.\n *\n * All fields are optional. When omitted, the client reads from environment\n * variables (`Z3RNO_BASE_URL`, `Z3RNO_API_KEY`) or uses sensible defaults.\n */\nexport interface Z3rnoClientConfig {\n /**\n * Base URL of the Z3rno API.\n *\n * Falls back to the `Z3RNO_BASE_URL` environment variable, then\n * to `\"https://api.z3rno.dev\"`.\n */\n baseUrl?: string;\n\n /**\n * API key for authentication.\n *\n * Falls back to the `Z3RNO_API_KEY` environment variable, then to\n * an empty string (unauthenticated).\n */\n apiKey?: string;\n\n /**\n * Request timeout in milliseconds.\n *\n * @defaultValue 30000 (30 seconds)\n */\n timeout?: number;\n\n /**\n * Maximum number of retry attempts for retryable errors (5xx, 429,\n * network failures, timeouts).\n *\n * @defaultValue 3\n */\n maxRetries?: number;\n\n /**\n * Custom fetch implementation.\n *\n * Defaults to `globalThis.fetch`. Override to use `undici`, `node-fetch`,\n * or a test double.\n *\n * @defaultValue globalThis.fetch\n */\n fetch?: typeof globalThis.fetch;\n\n /**\n * Intercept outgoing requests before they are sent.\n *\n * Use this to add custom headers, log requests, or collect metrics.\n * The callback receives the URL and the `RequestInit` and must return\n * a (possibly modified) `RequestInit`.\n */\n onRequest?: (url: string, init: RequestInit) => RequestInit;\n\n /**\n * Intercept responses before they are processed.\n *\n * Use this for logging, metrics, or response transformation.\n * The callback receives the `Response` and must return a `Response`.\n */\n onResponse?: (response: Response) => Response;\n}\n\n/**\n * Client for the Z3rno AI agent memory API.\n *\n * Uses the standard Fetch API under the hood, making it compatible with\n * Node.js 18+, Deno, Bun, and modern browsers. All responses are\n * validated at runtime with Zod schemas.\n *\n * @example\n * ```ts\n * import { Z3rnoClient } from \"@z3rno/sdk\";\n *\n * const client = new Z3rnoClient({\n * baseUrl: \"http://localhost:8000\",\n * apiKey: \"z3rno_sk_test_...\",\n * });\n *\n * // Store a memory\n * const mem = await client.store({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * });\n *\n * // Recall relevant memories\n * const results = await client.recall({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * });\n * ```\n */\nexport class Z3rnoClient {\n private baseUrl: string;\n private apiKey: string;\n private timeout: number;\n private maxRetries: number;\n private fetchImpl: typeof globalThis.fetch;\n private onRequest?: (url: string, init: RequestInit) => RequestInit;\n private onResponse?: (response: Response) => Response;\n\n /**\n * Creates a new Z3rno client instance.\n *\n * @param config - Client configuration options. All fields are optional.\n *\n * @example\n * ```ts\n * // Explicit configuration\n * const client = new Z3rnoClient({\n * baseUrl: \"http://localhost:8000\",\n * apiKey: \"z3rno_sk_test_...\",\n * timeout: 10000,\n * maxRetries: 2,\n * });\n *\n * // Or rely on environment variables (Z3RNO_BASE_URL, Z3RNO_API_KEY)\n * const client = new Z3rnoClient();\n * ```\n */\n constructor(config: Z3rnoClientConfig = {}) {\n // Resolve baseUrl: explicit > env var > default\n let resolvedUrl = config.baseUrl ?? \"\";\n if (!resolvedUrl && typeof process !== \"undefined\" && process.env) {\n resolvedUrl = process.env.Z3RNO_BASE_URL ?? \"\";\n }\n if (!resolvedUrl) {\n resolvedUrl = \"https://api.z3rno.dev\";\n }\n this.baseUrl = resolvedUrl.replace(/\\/$/, \"\");\n\n // Resolve apiKey: explicit > env var > empty\n let resolvedKey = config.apiKey ?? \"\";\n if (!resolvedKey && typeof process !== \"undefined\" && process.env) {\n resolvedKey = process.env.Z3RNO_API_KEY ?? \"\";\n }\n this.apiKey = resolvedKey;\n\n this.timeout = config.timeout ?? 30000;\n this.maxRetries = config.maxRetries ?? 3;\n this.fetchImpl = config.fetch ?? globalThis.fetch;\n this.onRequest = config.onRequest;\n this.onResponse = config.onResponse;\n }\n\n // --- Store ---\n\n /**\n * Stores a new memory for an agent.\n *\n * The server generates an embedding for the content and stores it in\n * the vector database. The memory is immediately available for recall.\n *\n * @param request - The memory to store.\n * @returns The stored memory, including the server-generated ID and scores.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link ValidationError} If the request body is invalid.\n * @throws {@link Z3rnoTimeoutError} If the request times out.\n *\n * @example\n * ```ts\n * const memory = await client.store({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * memoryType: \"semantic\",\n * metadata: { source: \"settings-page\" },\n * });\n * console.log(memory.id); // \"mem-abc123\"\n * ```\n */\n async store(request: StoreMemoryRequest): Promise<MemoryResponse> {\n const body = {\n agent_id: request.agentId,\n content: request.content,\n memory_type: request.memoryType,\n user_id: request.userId,\n metadata: request.metadata,\n relationships: request.relationships?.map((r) => ({\n target_memory_id: r.targetMemoryId,\n relationship_type: r.relationshipType,\n weight: r.weight,\n metadata: r.metadata,\n })),\n ttl_seconds: request.ttlSeconds,\n importance: request.importance,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories\", body);\n return MemorySchema.parse(resp);\n }\n\n // --- Recall ---\n\n /**\n * Recalls memories by semantic similarity to a query.\n *\n * Returns a ranked list of memories sorted by a combined relevance score\n * that factors in similarity, importance, and recency.\n *\n * @param params - Recall parameters including the query and filters.\n * @param params.agentId - UUID of the agent whose memories to search.\n * @param params.query - Natural-language query for semantic search.\n * @param params.memoryType - Filter by memory type.\n * @param params.filters - Additional metadata filters.\n * @param params.topK - Maximum results to return (default 10).\n * @param params.similarityThreshold - Minimum similarity score (default 0).\n * @returns Ranked recall results with similarity scores.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link Z3rnoTimeoutError} If the request times out.\n *\n * @example\n * ```ts\n * const results = await client.recall({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * topK: 5,\n * similarityThreshold: 0.7,\n * });\n * for (const item of results.results) {\n * console.log(`${item.content} (score: ${item.relevance_score})`);\n * }\n * ```\n */\n async recall(params: {\n agentId: string;\n query?: string;\n memoryType?: string;\n filters?: Record<string, unknown>;\n topK?: number;\n similarityThreshold?: number;\n /**\n * Phase C: retrieval strategy. One of `AUTO | VECTOR | LEXICAL |\n * GRAPH | TRIPLET | TRACE | TEMPORAL | ASK | CYPHER`. Default\n * `\"AUTO\"` — server's LLM router picks per query.\n */\n strategy?: string;\n /**\n * Phase C: cross-encoder re-ranking. When `true`, the server\n * re-ranks the strategy's top results. Requires\n * `sentence-transformers` on the server side.\n */\n rerank?: boolean;\n }): Promise<RecallResponse> {\n const body = {\n agent_id: params.agentId,\n query: params.query,\n memory_type: params.memoryType,\n filters: params.filters,\n top_k: params.topK ?? 10,\n similarity_threshold: params.similarityThreshold ?? 0,\n // Always send strategy + rerank. Older servers silently ignore\n // unknown body fields.\n strategy: params.strategy ?? \"AUTO\",\n rerank: params.rerank ?? false,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/recall\", body);\n return RecallSchema.parse(resp);\n }\n\n // --- Forget ---\n\n /**\n * Forgets (deletes) one or more memories.\n *\n * By default, performs a soft delete (marks as deleted but retains data).\n * Set `hardDelete: true` for permanent removal. Use `cascade: true` to\n * also delete related memories in the knowledge graph.\n *\n * @param params - Forget parameters.\n * @param params.agentId - UUID of the agent that owns the memories.\n * @param params.memoryId - UUID of a single memory to delete.\n * @param params.memoryIds - UUIDs of multiple memories to delete.\n * @param params.hardDelete - Permanently delete (default false).\n * @param params.cascade - Delete related memories too (default false).\n * @param params.reason - Reason for deletion (stored in audit log).\n * @returns Summary of the deletion operation.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link NotFoundError} If the specified memory does not exist.\n *\n * @example\n * ```ts\n * const result = await client.forget({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * memoryId: \"mem-abc123\",\n * hardDelete: true,\n * reason: \"User requested data deletion\",\n * });\n * console.log(`Deleted ${result.deleted_count} memories`);\n * ```\n */\n async forget(params: {\n agentId: string;\n memoryId?: string;\n memoryIds?: string[];\n hardDelete?: boolean;\n cascade?: boolean;\n reason?: string;\n }): Promise<ForgetResponse> {\n const body = {\n agent_id: params.agentId,\n memory_id: params.memoryId,\n memory_ids: params.memoryIds,\n hard_delete: params.hardDelete ?? false,\n cascade: params.cascade ?? false,\n reason: params.reason,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/forget\", body);\n return ForgetSchema.parse(resp);\n }\n\n // --- Get Memory ---\n\n /**\n * Retrieves a single memory by its ID.\n *\n * @param memoryId - The unique identifier of the memory to retrieve.\n * @returns The full memory object.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const memory = await client.getMemory(\"mem-abc123\");\n * console.log(memory.content);\n * console.log(memory.importance_score);\n * ```\n */\n async getMemory(memoryId: string): Promise<MemoryResponse> {\n const resp = await this.request(\"GET\", `/v1/memories/${memoryId}`);\n return MemorySchema.parse(resp);\n }\n\n // --- Store Batch ---\n\n /**\n * Stores multiple memories in a single API call.\n *\n * More efficient than calling {@link store} in a loop. All memories are\n * processed atomically on the server.\n *\n * @param memories - Array of memories to store.\n * @returns The stored memories and a count of how many were created.\n * @throws {@link ValidationError} If any memory in the batch is invalid.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const result = await client.storeBatch([\n * { agentId: \"agent-1\", content: \"Fact one\" },\n * { agentId: \"agent-1\", content: \"Fact two\", memoryType: \"semantic\" },\n * ]);\n * console.log(`Stored ${result.stored_count} memories`);\n * ```\n */\n async storeBatch(\n memories: StoreMemoryRequest[],\n ): Promise<BatchStoreResponse> {\n const body = {\n memories: memories.map((m) => ({\n agent_id: m.agentId,\n content: m.content,\n memory_type: m.memoryType,\n metadata: m.metadata,\n importance: m.importance,\n })),\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/batch\", body);\n return BatchStoreSchema.parse(resp);\n }\n\n // --- Memory History ---\n\n /**\n * Retrieves the full version history of a memory.\n *\n * Z3rno uses temporal versioning — every update creates a new version\n * rather than overwriting. This method returns all versions ordered\n * chronologically.\n *\n * @param memoryId - The unique identifier of the memory.\n * @returns All versions of the memory with validity timestamps.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const history = await client.getMemoryHistory(\"mem-abc123\");\n * for (const version of history.versions) {\n * console.log(`${version.valid_from}: ${version.content}`);\n * }\n * ```\n */\n async getMemoryHistory(memoryId: string): Promise<MemoryHistoryResponse> {\n const resp = await this.request(\"GET\", `/v1/memories/${memoryId}/history`);\n return MemoryHistorySchema.parse(resp);\n }\n\n // --- Update Memory ---\n\n /**\n * Updates an existing memory's content, metadata, or importance.\n *\n * Creates a new temporal version of the memory. The previous version\n * remains accessible via {@link getMemoryHistory}.\n *\n * @param memoryId - The unique identifier of the memory to update.\n * @param updates - Fields to update (only provided fields are changed).\n * @param updates.content - New text content.\n * @param updates.metadata - New metadata (replaces existing metadata).\n * @param updates.importance - New importance score (0-1).\n * @returns The updated memory object.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link ValidationError} If the update values are invalid.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const updated = await client.updateMemory(\"mem-abc123\", {\n * content: \"User now prefers light mode\",\n * importance: 0.9,\n * });\n * ```\n */\n async updateMemory(\n memoryId: string,\n updates: {\n content?: string;\n metadata?: Record<string, unknown>;\n importance?: number;\n },\n ): Promise<MemoryResponse> {\n const body: Record<string, unknown> = {};\n if (updates.content !== undefined) body.content = updates.content;\n if (updates.metadata !== undefined) body.metadata = updates.metadata;\n if (updates.importance !== undefined) body.importance = updates.importance;\n\n const resp = await this.request(\"PATCH\", `/v1/memories/${memoryId}`, body);\n return MemorySchema.parse(resp);\n }\n\n // --- Sessions ---\n\n /**\n * Starts a new session for grouping related memory operations.\n *\n * Sessions are useful for tracking conversation turns or task boundaries.\n * Memories created during a session are automatically associated with it.\n *\n * @param params - Session parameters.\n * @param params.agentId - UUID of the agent to start the session for.\n * @param params.sessionType - Type of session (default `\"conversation\"`).\n * @returns The created session with its ID and start time.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const session = await client.startSession({ agentId: \"agent-1\" });\n * console.log(`Session started: ${session.session_id}`);\n * // ... perform operations ...\n * await client.endSession(session.session_id);\n * ```\n */\n async startSession(params: {\n agentId: string;\n sessionType?: string;\n }): Promise<SessionResponse> {\n const body = {\n agent_id: params.agentId,\n session_type: params.sessionType ?? \"conversation\",\n };\n\n const resp = await this.request(\"POST\", \"/v1/sessions\", body);\n return SessionSchema.parse(resp);\n }\n\n /**\n * Ends an active session.\n *\n * Returns summary statistics including the session duration and the\n * number of memories created during the session.\n *\n * @param sessionId - The unique identifier of the session to end.\n * @returns Session summary with duration and memory count.\n * @throws {@link NotFoundError} If no active session exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const summary = await client.endSession(\"sess-abc123\");\n * console.log(`Session lasted ${summary.duration_seconds}s, ${summary.memory_count} memories`);\n * ```\n */\n async endSession(sessionId: string): Promise<EndSessionResponse> {\n const resp = await this.request(\"POST\", `/v1/sessions/${sessionId}/end`);\n return EndSessionSchema.parse(resp);\n }\n\n // --- Audit ---\n\n /**\n * Retrieves a paginated audit log of memory operations.\n *\n * The audit log records every store, recall, forget, and update operation\n * performed by any agent. Useful for compliance, debugging, and analytics.\n *\n * @param params - Optional pagination and filter parameters.\n * @param params.agentId - Filter by agent UUID.\n * @param params.page - Page number (1-indexed).\n * @param params.pageSize - Number of entries per page.\n * @returns A page of audit log entries with pagination metadata.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const page = await client.audit({ agentId: \"agent-1\", page: 1, pageSize: 20 });\n * for (const entry of page.entries) {\n * console.log(`${entry.created_at}: ${entry.operation} on ${entry.memory_id}`);\n * }\n * if (page.has_next) {\n * const nextPage = await client.audit({ agentId: \"agent-1\", page: 2 });\n * }\n * ```\n */\n async audit(params?: {\n agentId?: string;\n page?: number;\n pageSize?: number;\n }): Promise<AuditPageResponse> {\n const searchParams = new URLSearchParams();\n if (params?.agentId) searchParams.set(\"agent_id\", params.agentId);\n if (params?.page) searchParams.set(\"page\", String(params.page));\n if (params?.pageSize)\n searchParams.set(\"page_size\", String(params.pageSize));\n\n const query = searchParams.toString();\n const path = query ? `/v1/audit?${query}` : \"/v1/audit\";\n const resp = await this.request(\"GET\", path);\n return AuditPageSchema.parse(resp);\n }\n\n // --- HTTP layer ---\n\n private async request(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<unknown> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const url = `${this.baseUrl}${path}`;\n let init: RequestInit = {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"@z3rno/sdk/0.0.1\",\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n };\n\n if (this.onRequest) {\n init = this.onRequest(url, init);\n }\n\n let response = await this.fetchImpl(url, init);\n\n if (this.onResponse) {\n response = this.onResponse(response);\n }\n\n clearTimeout(timeoutId);\n\n // On 429, honor Retry-After header and retry\n if (response.status === 429 && attempt < this.maxRetries) {\n const retryAfter = parseInt(\n response.headers.get(\"Retry-After\") ?? \"1\",\n 10,\n );\n await this.sleep(retryAfter * 1000);\n continue;\n }\n\n // On 5xx, retry with exponential backoff\n if (response.status >= 500 && attempt < this.maxRetries) {\n const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s\n await this.sleep(delay);\n continue;\n }\n\n return this.handleResponse(response);\n } catch (error) {\n clearTimeout(timeoutId);\n\n // Do not retry Z3rnoError subclasses (4xx client errors)\n if (error instanceof Z3rnoError) throw error;\n\n // Classify the error before deciding whether to retry\n if (error instanceof DOMException && error.name === \"AbortError\") {\n lastError = new Z3rnoTimeoutError(\n `Request timed out after ${this.timeout}ms`,\n this.timeout,\n );\n } else if (error instanceof TypeError) {\n lastError = new Z3rnoConnectionError(\n `Connection failed: ${error.message}`,\n );\n } else {\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n\n if (attempt < this.maxRetries) {\n const delay = Math.pow(2, attempt) * 1000;\n await this.sleep(delay);\n continue;\n }\n }\n }\n\n // After all retries exhausted, throw the last classified error\n if (lastError instanceof Z3rnoError) {\n throw lastError;\n }\n throw new Z3rnoError(\n `Request failed after ${this.maxRetries + 1} attempts: ${String(lastError)}`,\n );\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private async handleResponse(resp: Response): Promise<unknown> {\n if (resp.ok) {\n return resp.json();\n }\n\n let detail = resp.statusText;\n try {\n const text = await resp.text();\n try {\n const body = JSON.parse(text) as Record<string, unknown>;\n detail = String(body.detail ?? body.error ?? resp.statusText);\n } catch {\n // Response is not JSON (e.g., nginx HTML 502). Include the\n // beginning of the body so users can diagnose proxy/gateway issues.\n if (text.length > 0) {\n const preview = text.length > 200 ? text.slice(0, 200) + \"...\" : text;\n detail = `${resp.statusText} — ${preview}`;\n }\n }\n } catch {\n // Could not read body at all\n }\n\n switch (resp.status) {\n case 401:\n throw new AuthenticationError(`Authentication failed: ${detail}`);\n case 404:\n throw new NotFoundError(`Not found: ${detail}`);\n case 429: {\n const retryAfter = parseInt(\n resp.headers.get(\"Retry-After\") ?? \"60\",\n 10,\n );\n throw new RateLimitError(`Rate limit exceeded: ${detail}`, retryAfter);\n }\n case 400:\n case 422:\n throw new ValidationError(detail, resp.status);\n default:\n if (resp.status >= 500) {\n throw new ServerError(`Server error: ${detail}`, resp.status);\n }\n throw new Z3rnoError(\n `Unexpected error (${resp.status}): ${detail}`,\n resp.status,\n );\n }\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -38,6 +38,15 @@ type MemoryType = z.infer<typeof MemoryType>;
|
|
|
38
38
|
declare const RelationshipType: z.ZodEnum<["derived_from", "contradicts", "supports", "supersedes", "related_to", "caused_by"]>;
|
|
39
39
|
/** Relationship type between two memories. */
|
|
40
40
|
type RelationshipType = z.infer<typeof RelationshipType>;
|
|
41
|
+
/**
|
|
42
|
+
* Retrieval strategy for `recall({ strategy: ... })` — Phase C.
|
|
43
|
+
*
|
|
44
|
+
* `AUTO` is the default; the server's LLM router picks one of the
|
|
45
|
+
* others when configured. Use an explicit value to bypass routing.
|
|
46
|
+
*/
|
|
47
|
+
declare const RetrievalStrategy: z.ZodEnum<["AUTO", "VECTOR", "LEXICAL", "GRAPH", "TRIPLET", "TRACE", "TEMPORAL", "ASK", "CYPHER"]>;
|
|
48
|
+
/** Retrieval strategy enum (canonical UPPERCASE names). */
|
|
49
|
+
type RetrievalStrategy = z.infer<typeof RetrievalStrategy>;
|
|
41
50
|
/**
|
|
42
51
|
* Schema for storing a new memory.
|
|
43
52
|
*
|
|
@@ -192,6 +201,11 @@ declare const RecallResultItem: z.ZodObject<{
|
|
|
192
201
|
created_at: z.ZodString;
|
|
193
202
|
/** Arbitrary metadata attached to the memory. */
|
|
194
203
|
metadata: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
204
|
+
/**
|
|
205
|
+
* Phase C per-source signals — e.g. `{ vector: 0.83, lexical: 0.61 }`.
|
|
206
|
+
* Optional so older servers (v0.7.x) keep parsing.
|
|
207
|
+
*/
|
|
208
|
+
score_components: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
195
209
|
}, "strip", z.ZodTypeAny, {
|
|
196
210
|
content: string;
|
|
197
211
|
metadata: Record<string, unknown>;
|
|
@@ -202,6 +216,7 @@ declare const RecallResultItem: z.ZodObject<{
|
|
|
202
216
|
memory_id: string;
|
|
203
217
|
similarity_score: number;
|
|
204
218
|
relevance_score: number;
|
|
219
|
+
score_components: Record<string, number>;
|
|
205
220
|
summary?: string | null | undefined;
|
|
206
221
|
}, {
|
|
207
222
|
content: string;
|
|
@@ -214,6 +229,7 @@ declare const RecallResultItem: z.ZodObject<{
|
|
|
214
229
|
relevance_score: number;
|
|
215
230
|
metadata?: Record<string, unknown> | undefined;
|
|
216
231
|
summary?: string | null | undefined;
|
|
232
|
+
score_components?: Record<string, number> | undefined;
|
|
217
233
|
}>;
|
|
218
234
|
/** Parsed type for a single recall result item. */
|
|
219
235
|
type RecallResultItem = z.infer<typeof RecallResultItem>;
|
|
@@ -245,6 +261,11 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
245
261
|
created_at: z.ZodString;
|
|
246
262
|
/** Arbitrary metadata attached to the memory. */
|
|
247
263
|
metadata: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
264
|
+
/**
|
|
265
|
+
* Phase C per-source signals — e.g. `{ vector: 0.83, lexical: 0.61 }`.
|
|
266
|
+
* Optional so older servers (v0.7.x) keep parsing.
|
|
267
|
+
*/
|
|
268
|
+
score_components: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
248
269
|
}, "strip", z.ZodTypeAny, {
|
|
249
270
|
content: string;
|
|
250
271
|
metadata: Record<string, unknown>;
|
|
@@ -255,6 +276,7 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
255
276
|
memory_id: string;
|
|
256
277
|
similarity_score: number;
|
|
257
278
|
relevance_score: number;
|
|
279
|
+
score_components: Record<string, number>;
|
|
258
280
|
summary?: string | null | undefined;
|
|
259
281
|
}, {
|
|
260
282
|
content: string;
|
|
@@ -267,11 +289,20 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
267
289
|
relevance_score: number;
|
|
268
290
|
metadata?: Record<string, unknown> | undefined;
|
|
269
291
|
summary?: string | null | undefined;
|
|
292
|
+
score_components?: Record<string, number> | undefined;
|
|
270
293
|
}>, "many">;
|
|
271
294
|
/** Total number of matches (may exceed `topK`). */
|
|
272
295
|
total: z.ZodNumber;
|
|
273
296
|
/** The query that was searched, if any. */
|
|
274
297
|
query: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
298
|
+
/** Phase C: strategy that actually ran (after AUTO routing + re-rank). */
|
|
299
|
+
strategy_used: z.ZodDefault<z.ZodString>;
|
|
300
|
+
/** Phase C: AUTO's candidate list (e.g. `["AUTO->GRAPH"]`). */
|
|
301
|
+
strategies_considered: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
302
|
+
/** Phase C: whether the cross-encoder re-rank ran. */
|
|
303
|
+
reranked: z.ZodDefault<z.ZodBoolean>;
|
|
304
|
+
/** Phase C: end-to-end recall latency on the server (ms). */
|
|
305
|
+
elapsed_ms: z.ZodDefault<z.ZodNumber>;
|
|
275
306
|
}, "strip", z.ZodTypeAny, {
|
|
276
307
|
results: {
|
|
277
308
|
content: string;
|
|
@@ -283,9 +314,14 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
283
314
|
memory_id: string;
|
|
284
315
|
similarity_score: number;
|
|
285
316
|
relevance_score: number;
|
|
317
|
+
score_components: Record<string, number>;
|
|
286
318
|
summary?: string | null | undefined;
|
|
287
319
|
}[];
|
|
288
320
|
total: number;
|
|
321
|
+
strategy_used: string;
|
|
322
|
+
strategies_considered: string[];
|
|
323
|
+
reranked: boolean;
|
|
324
|
+
elapsed_ms: number;
|
|
289
325
|
query?: string | null | undefined;
|
|
290
326
|
}, {
|
|
291
327
|
results: {
|
|
@@ -299,9 +335,14 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
299
335
|
relevance_score: number;
|
|
300
336
|
metadata?: Record<string, unknown> | undefined;
|
|
301
337
|
summary?: string | null | undefined;
|
|
338
|
+
score_components?: Record<string, number> | undefined;
|
|
302
339
|
}[];
|
|
303
340
|
total: number;
|
|
304
341
|
query?: string | null | undefined;
|
|
342
|
+
strategy_used?: string | undefined;
|
|
343
|
+
strategies_considered?: string[] | undefined;
|
|
344
|
+
reranked?: boolean | undefined;
|
|
345
|
+
elapsed_ms?: number | undefined;
|
|
305
346
|
}>;
|
|
306
347
|
/** Parsed type for a recall response. */
|
|
307
348
|
type RecallResponse = z.infer<typeof RecallResponse>;
|
|
@@ -910,6 +951,18 @@ declare class Z3rnoClient {
|
|
|
910
951
|
filters?: Record<string, unknown>;
|
|
911
952
|
topK?: number;
|
|
912
953
|
similarityThreshold?: number;
|
|
954
|
+
/**
|
|
955
|
+
* Phase C: retrieval strategy. One of `AUTO | VECTOR | LEXICAL |
|
|
956
|
+
* GRAPH | TRIPLET | TRACE | TEMPORAL | ASK | CYPHER`. Default
|
|
957
|
+
* `"AUTO"` — server's LLM router picks per query.
|
|
958
|
+
*/
|
|
959
|
+
strategy?: string;
|
|
960
|
+
/**
|
|
961
|
+
* Phase C: cross-encoder re-ranking. When `true`, the server
|
|
962
|
+
* re-ranks the strategy's top results. Requires
|
|
963
|
+
* `sentence-transformers` on the server side.
|
|
964
|
+
*/
|
|
965
|
+
rerank?: boolean;
|
|
913
966
|
}): Promise<RecallResponse>;
|
|
914
967
|
/**
|
|
915
968
|
* Forgets (deletes) one or more memories.
|
|
@@ -1310,4 +1363,4 @@ declare class Z3rnoConnectionError extends Z3rnoError {
|
|
|
1310
1363
|
constructor(message: string);
|
|
1311
1364
|
}
|
|
1312
1365
|
|
|
1313
|
-
export { AuditEntry, AuditPageResponse, AuthenticationError, BatchStoreResponse, EndSessionResponse, ForgetResponse, MemoryHistoryResponse, MemoryResponse, MemoryType, MemoryVersion, NotFoundError, RateLimitError, RecallResponse, RecallResultItem, RelationshipType, ServerError, SessionResponse, StoreMemoryRequest, ValidationError, Z3rnoClient, type Z3rnoClientConfig, Z3rnoConnectionError, Z3rnoError, Z3rnoTimeoutError };
|
|
1366
|
+
export { AuditEntry, AuditPageResponse, AuthenticationError, BatchStoreResponse, EndSessionResponse, ForgetResponse, MemoryHistoryResponse, MemoryResponse, MemoryType, MemoryVersion, NotFoundError, RateLimitError, RecallResponse, RecallResultItem, RelationshipType, RetrievalStrategy, ServerError, SessionResponse, StoreMemoryRequest, ValidationError, Z3rnoClient, type Z3rnoClientConfig, Z3rnoConnectionError, Z3rnoError, Z3rnoTimeoutError };
|
package/dist/index.d.ts
CHANGED
|
@@ -38,6 +38,15 @@ type MemoryType = z.infer<typeof MemoryType>;
|
|
|
38
38
|
declare const RelationshipType: z.ZodEnum<["derived_from", "contradicts", "supports", "supersedes", "related_to", "caused_by"]>;
|
|
39
39
|
/** Relationship type between two memories. */
|
|
40
40
|
type RelationshipType = z.infer<typeof RelationshipType>;
|
|
41
|
+
/**
|
|
42
|
+
* Retrieval strategy for `recall({ strategy: ... })` — Phase C.
|
|
43
|
+
*
|
|
44
|
+
* `AUTO` is the default; the server's LLM router picks one of the
|
|
45
|
+
* others when configured. Use an explicit value to bypass routing.
|
|
46
|
+
*/
|
|
47
|
+
declare const RetrievalStrategy: z.ZodEnum<["AUTO", "VECTOR", "LEXICAL", "GRAPH", "TRIPLET", "TRACE", "TEMPORAL", "ASK", "CYPHER"]>;
|
|
48
|
+
/** Retrieval strategy enum (canonical UPPERCASE names). */
|
|
49
|
+
type RetrievalStrategy = z.infer<typeof RetrievalStrategy>;
|
|
41
50
|
/**
|
|
42
51
|
* Schema for storing a new memory.
|
|
43
52
|
*
|
|
@@ -192,6 +201,11 @@ declare const RecallResultItem: z.ZodObject<{
|
|
|
192
201
|
created_at: z.ZodString;
|
|
193
202
|
/** Arbitrary metadata attached to the memory. */
|
|
194
203
|
metadata: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
204
|
+
/**
|
|
205
|
+
* Phase C per-source signals — e.g. `{ vector: 0.83, lexical: 0.61 }`.
|
|
206
|
+
* Optional so older servers (v0.7.x) keep parsing.
|
|
207
|
+
*/
|
|
208
|
+
score_components: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
195
209
|
}, "strip", z.ZodTypeAny, {
|
|
196
210
|
content: string;
|
|
197
211
|
metadata: Record<string, unknown>;
|
|
@@ -202,6 +216,7 @@ declare const RecallResultItem: z.ZodObject<{
|
|
|
202
216
|
memory_id: string;
|
|
203
217
|
similarity_score: number;
|
|
204
218
|
relevance_score: number;
|
|
219
|
+
score_components: Record<string, number>;
|
|
205
220
|
summary?: string | null | undefined;
|
|
206
221
|
}, {
|
|
207
222
|
content: string;
|
|
@@ -214,6 +229,7 @@ declare const RecallResultItem: z.ZodObject<{
|
|
|
214
229
|
relevance_score: number;
|
|
215
230
|
metadata?: Record<string, unknown> | undefined;
|
|
216
231
|
summary?: string | null | undefined;
|
|
232
|
+
score_components?: Record<string, number> | undefined;
|
|
217
233
|
}>;
|
|
218
234
|
/** Parsed type for a single recall result item. */
|
|
219
235
|
type RecallResultItem = z.infer<typeof RecallResultItem>;
|
|
@@ -245,6 +261,11 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
245
261
|
created_at: z.ZodString;
|
|
246
262
|
/** Arbitrary metadata attached to the memory. */
|
|
247
263
|
metadata: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
264
|
+
/**
|
|
265
|
+
* Phase C per-source signals — e.g. `{ vector: 0.83, lexical: 0.61 }`.
|
|
266
|
+
* Optional so older servers (v0.7.x) keep parsing.
|
|
267
|
+
*/
|
|
268
|
+
score_components: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;
|
|
248
269
|
}, "strip", z.ZodTypeAny, {
|
|
249
270
|
content: string;
|
|
250
271
|
metadata: Record<string, unknown>;
|
|
@@ -255,6 +276,7 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
255
276
|
memory_id: string;
|
|
256
277
|
similarity_score: number;
|
|
257
278
|
relevance_score: number;
|
|
279
|
+
score_components: Record<string, number>;
|
|
258
280
|
summary?: string | null | undefined;
|
|
259
281
|
}, {
|
|
260
282
|
content: string;
|
|
@@ -267,11 +289,20 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
267
289
|
relevance_score: number;
|
|
268
290
|
metadata?: Record<string, unknown> | undefined;
|
|
269
291
|
summary?: string | null | undefined;
|
|
292
|
+
score_components?: Record<string, number> | undefined;
|
|
270
293
|
}>, "many">;
|
|
271
294
|
/** Total number of matches (may exceed `topK`). */
|
|
272
295
|
total: z.ZodNumber;
|
|
273
296
|
/** The query that was searched, if any. */
|
|
274
297
|
query: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
298
|
+
/** Phase C: strategy that actually ran (after AUTO routing + re-rank). */
|
|
299
|
+
strategy_used: z.ZodDefault<z.ZodString>;
|
|
300
|
+
/** Phase C: AUTO's candidate list (e.g. `["AUTO->GRAPH"]`). */
|
|
301
|
+
strategies_considered: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
302
|
+
/** Phase C: whether the cross-encoder re-rank ran. */
|
|
303
|
+
reranked: z.ZodDefault<z.ZodBoolean>;
|
|
304
|
+
/** Phase C: end-to-end recall latency on the server (ms). */
|
|
305
|
+
elapsed_ms: z.ZodDefault<z.ZodNumber>;
|
|
275
306
|
}, "strip", z.ZodTypeAny, {
|
|
276
307
|
results: {
|
|
277
308
|
content: string;
|
|
@@ -283,9 +314,14 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
283
314
|
memory_id: string;
|
|
284
315
|
similarity_score: number;
|
|
285
316
|
relevance_score: number;
|
|
317
|
+
score_components: Record<string, number>;
|
|
286
318
|
summary?: string | null | undefined;
|
|
287
319
|
}[];
|
|
288
320
|
total: number;
|
|
321
|
+
strategy_used: string;
|
|
322
|
+
strategies_considered: string[];
|
|
323
|
+
reranked: boolean;
|
|
324
|
+
elapsed_ms: number;
|
|
289
325
|
query?: string | null | undefined;
|
|
290
326
|
}, {
|
|
291
327
|
results: {
|
|
@@ -299,9 +335,14 @@ declare const RecallResponse: z.ZodObject<{
|
|
|
299
335
|
relevance_score: number;
|
|
300
336
|
metadata?: Record<string, unknown> | undefined;
|
|
301
337
|
summary?: string | null | undefined;
|
|
338
|
+
score_components?: Record<string, number> | undefined;
|
|
302
339
|
}[];
|
|
303
340
|
total: number;
|
|
304
341
|
query?: string | null | undefined;
|
|
342
|
+
strategy_used?: string | undefined;
|
|
343
|
+
strategies_considered?: string[] | undefined;
|
|
344
|
+
reranked?: boolean | undefined;
|
|
345
|
+
elapsed_ms?: number | undefined;
|
|
305
346
|
}>;
|
|
306
347
|
/** Parsed type for a recall response. */
|
|
307
348
|
type RecallResponse = z.infer<typeof RecallResponse>;
|
|
@@ -910,6 +951,18 @@ declare class Z3rnoClient {
|
|
|
910
951
|
filters?: Record<string, unknown>;
|
|
911
952
|
topK?: number;
|
|
912
953
|
similarityThreshold?: number;
|
|
954
|
+
/**
|
|
955
|
+
* Phase C: retrieval strategy. One of `AUTO | VECTOR | LEXICAL |
|
|
956
|
+
* GRAPH | TRIPLET | TRACE | TEMPORAL | ASK | CYPHER`. Default
|
|
957
|
+
* `"AUTO"` — server's LLM router picks per query.
|
|
958
|
+
*/
|
|
959
|
+
strategy?: string;
|
|
960
|
+
/**
|
|
961
|
+
* Phase C: cross-encoder re-ranking. When `true`, the server
|
|
962
|
+
* re-ranks the strategy's top results. Requires
|
|
963
|
+
* `sentence-transformers` on the server side.
|
|
964
|
+
*/
|
|
965
|
+
rerank?: boolean;
|
|
913
966
|
}): Promise<RecallResponse>;
|
|
914
967
|
/**
|
|
915
968
|
* Forgets (deletes) one or more memories.
|
|
@@ -1310,4 +1363,4 @@ declare class Z3rnoConnectionError extends Z3rnoError {
|
|
|
1310
1363
|
constructor(message: string);
|
|
1311
1364
|
}
|
|
1312
1365
|
|
|
1313
|
-
export { AuditEntry, AuditPageResponse, AuthenticationError, BatchStoreResponse, EndSessionResponse, ForgetResponse, MemoryHistoryResponse, MemoryResponse, MemoryType, MemoryVersion, NotFoundError, RateLimitError, RecallResponse, RecallResultItem, RelationshipType, ServerError, SessionResponse, StoreMemoryRequest, ValidationError, Z3rnoClient, type Z3rnoClientConfig, Z3rnoConnectionError, Z3rnoError, Z3rnoTimeoutError };
|
|
1366
|
+
export { AuditEntry, AuditPageResponse, AuthenticationError, BatchStoreResponse, EndSessionResponse, ForgetResponse, MemoryHistoryResponse, MemoryResponse, MemoryType, MemoryVersion, NotFoundError, RateLimitError, RecallResponse, RecallResultItem, RelationshipType, RetrievalStrategy, ServerError, SessionResponse, StoreMemoryRequest, ValidationError, Z3rnoClient, type Z3rnoClientConfig, Z3rnoConnectionError, Z3rnoError, Z3rnoTimeoutError };
|
package/dist/index.js
CHANGED
|
@@ -101,6 +101,17 @@ var RelationshipType = z.enum([
|
|
|
101
101
|
"related_to",
|
|
102
102
|
"caused_by"
|
|
103
103
|
]);
|
|
104
|
+
var RetrievalStrategy = z.enum([
|
|
105
|
+
"AUTO",
|
|
106
|
+
"VECTOR",
|
|
107
|
+
"LEXICAL",
|
|
108
|
+
"GRAPH",
|
|
109
|
+
"TRIPLET",
|
|
110
|
+
"TRACE",
|
|
111
|
+
"TEMPORAL",
|
|
112
|
+
"ASK",
|
|
113
|
+
"CYPHER"
|
|
114
|
+
]);
|
|
104
115
|
z.object({
|
|
105
116
|
/** UUID of the agent that owns this memory. */
|
|
106
117
|
agentId: z.string().uuid(),
|
|
@@ -146,7 +157,18 @@ z.object({
|
|
|
146
157
|
/** ISO 8601 timestamp for temporal queries (point-in-time recall). */
|
|
147
158
|
asOf: z.string().datetime().optional(),
|
|
148
159
|
/** Whether to include soft-deleted memories. */
|
|
149
|
-
includeDeleted: z.boolean().default(false)
|
|
160
|
+
includeDeleted: z.boolean().default(false),
|
|
161
|
+
/**
|
|
162
|
+
* Phase C retrieval strategy. `AUTO` (default) lets the server's
|
|
163
|
+
* LLM router pick the best fit. See {@link RetrievalStrategy}.
|
|
164
|
+
*/
|
|
165
|
+
strategy: RetrievalStrategy.default("AUTO"),
|
|
166
|
+
/**
|
|
167
|
+
* Phase C cross-encoder re-ranking. When `true`, the server
|
|
168
|
+
* re-ranks the top results via a cross-encoder. Requires the
|
|
169
|
+
* `sentence-transformers` extra on the server.
|
|
170
|
+
*/
|
|
171
|
+
rerank: z.boolean().default(false)
|
|
150
172
|
});
|
|
151
173
|
z.object({
|
|
152
174
|
/** UUID of the agent that owns the memories. */
|
|
@@ -202,7 +224,12 @@ var RecallResultItem = z.object({
|
|
|
202
224
|
/** ISO 8601 creation timestamp. */
|
|
203
225
|
created_at: z.string(),
|
|
204
226
|
/** Arbitrary metadata attached to the memory. */
|
|
205
|
-
metadata: z.record(z.unknown()).default({})
|
|
227
|
+
metadata: z.record(z.unknown()).default({}),
|
|
228
|
+
/**
|
|
229
|
+
* Phase C per-source signals — e.g. `{ vector: 0.83, lexical: 0.61 }`.
|
|
230
|
+
* Optional so older servers (v0.7.x) keep parsing.
|
|
231
|
+
*/
|
|
232
|
+
score_components: z.record(z.number()).default({})
|
|
206
233
|
});
|
|
207
234
|
var RecallResponse = z.object({
|
|
208
235
|
/** Ranked list of matching memories. */
|
|
@@ -210,7 +237,15 @@ var RecallResponse = z.object({
|
|
|
210
237
|
/** Total number of matches (may exceed `topK`). */
|
|
211
238
|
total: z.number(),
|
|
212
239
|
/** The query that was searched, if any. */
|
|
213
|
-
query: z.string().nullable().optional()
|
|
240
|
+
query: z.string().nullable().optional(),
|
|
241
|
+
/** Phase C: strategy that actually ran (after AUTO routing + re-rank). */
|
|
242
|
+
strategy_used: z.string().default("VECTOR"),
|
|
243
|
+
/** Phase C: AUTO's candidate list (e.g. `["AUTO->GRAPH"]`). */
|
|
244
|
+
strategies_considered: z.array(z.string()).default([]),
|
|
245
|
+
/** Phase C: whether the cross-encoder re-rank ran. */
|
|
246
|
+
reranked: z.boolean().default(false),
|
|
247
|
+
/** Phase C: end-to-end recall latency on the server (ms). */
|
|
248
|
+
elapsed_ms: z.number().default(0)
|
|
214
249
|
});
|
|
215
250
|
var ForgetResponse = z.object({
|
|
216
251
|
/** Number of memories deleted. */
|
|
@@ -436,7 +471,11 @@ var Z3rnoClient = class {
|
|
|
436
471
|
memory_type: params.memoryType,
|
|
437
472
|
filters: params.filters,
|
|
438
473
|
top_k: params.topK ?? 10,
|
|
439
|
-
similarity_threshold: params.similarityThreshold ?? 0
|
|
474
|
+
similarity_threshold: params.similarityThreshold ?? 0,
|
|
475
|
+
// Always send strategy + rerank. Older servers silently ignore
|
|
476
|
+
// unknown body fields.
|
|
477
|
+
strategy: params.strategy ?? "AUTO",
|
|
478
|
+
rerank: params.rerank ?? false
|
|
440
479
|
};
|
|
441
480
|
const resp = await this.request("POST", "/v1/memories/recall", body);
|
|
442
481
|
return RecallResponse.parse(resp);
|
|
@@ -798,6 +837,6 @@ var Z3rnoClient = class {
|
|
|
798
837
|
}
|
|
799
838
|
};
|
|
800
839
|
|
|
801
|
-
export { AuditEntry, AuditPageResponse, AuthenticationError, BatchStoreResponse, EndSessionResponse, ForgetResponse, MemoryHistoryResponse, MemoryResponse, MemoryType, MemoryVersion, NotFoundError, RateLimitError, RecallResponse, RecallResultItem, RelationshipType, ServerError, SessionResponse, ValidationError, Z3rnoClient, Z3rnoConnectionError, Z3rnoError, Z3rnoTimeoutError };
|
|
840
|
+
export { AuditEntry, AuditPageResponse, AuthenticationError, BatchStoreResponse, EndSessionResponse, ForgetResponse, MemoryHistoryResponse, MemoryResponse, MemoryType, MemoryVersion, NotFoundError, RateLimitError, RecallResponse, RecallResultItem, RelationshipType, RetrievalStrategy, ServerError, SessionResponse, ValidationError, Z3rnoClient, Z3rnoConnectionError, Z3rnoError, Z3rnoTimeoutError };
|
|
802
841
|
//# sourceMappingURL=index.js.map
|
|
803
842
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/models.ts","../src/client.ts"],"names":[],"mappings":";;;AA4BO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA;AAAA,EAEp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AAI,aAAA,CAAc,CAAA,WAAA,EAAc,MAAM,CAAA,CAAE,CAAA;AAAA,MAChD,KAAK,GAAA,EAAK;AACR,QAAA,MAAM,UAAA,GAAa,QAAA;AAAA,UACjB,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA,IAAK,IAAA;AAAA,UACnC;AAAA,SACF;AACA,QAAA,MAAM,IAAI,cAAA,CAAe,CAAA,qBAAA,EAAwB,MAAM,IAAI,UAAU,CAAA;AAAA,MACvE;AAAA,MACA,KAAK,GAAA;AAAA,MACL,KAAK,GAAA;AACH,QAAA,MAAM,IAAI,eAAA,CAAgB,MAAA,EAAQ,IAAA,CAAK,MAAM,CAAA;AAAA,MAC/C;AACE,QAAA,IAAI,IAAA,CAAK,UAAU,GAAA,EAAK;AACtB,UAAA,MAAM,IAAI,WAAA,CAAY,CAAA,cAAA,EAAiB,MAAM,CAAA,CAAA,EAAI,KAAK,MAAM,CAAA;AAAA,QAC9D;AACA,QAAA,MAAM,IAAI,UAAA;AAAA,UACR,CAAA,kBAAA,EAAqB,IAAA,CAAK,MAAM,CAAA,GAAA,EAAM,MAAM,CAAA,CAAA;AAAA,UAC5C,IAAA,CAAK;AAAA,SACP;AAAA;AACJ,EACF;AACF","file":"index.js","sourcesContent":["/**\n * Z3rno SDK error hierarchy.\n *\n * All errors thrown by the SDK extend {@link Z3rnoError}, which itself extends\n * the built-in `Error` class. This lets callers catch broadly (`Z3rnoError`)\n * or narrowly (`AuthenticationError`, `RateLimitError`, etc.).\n *\n * @module errors\n */\n\n/**\n * Base error class for all Z3rno SDK errors.\n *\n * Every error produced by the SDK is an instance of this class, so you can\n * use a single `catch (e) { if (e instanceof Z3rnoError) ... }` guard to\n * handle them all.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoError) {\n * console.error(`Z3rno error (${e.statusCode}): ${e.message}`);\n * }\n * }\n * ```\n */\nexport class Z3rnoError extends Error {\n /** HTTP status code returned by the server, if applicable. */\n statusCode?: number;\n\n /**\n * @param message - Human-readable description of the error.\n * @param statusCode - HTTP status code associated with the error, if any.\n */\n constructor(message: string, statusCode?: number) {\n super(message);\n this.name = \"Z3rnoError\";\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Thrown when the API key is missing, invalid, or revoked (HTTP 401).\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof AuthenticationError) {\n * console.error(\"Check your API key\");\n * }\n * }\n * ```\n */\nexport class AuthenticationError extends Z3rnoError {\n /**\n * @param message - Description of the authentication failure.\n */\n constructor(message: string) {\n super(message, 401);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Thrown when the client exceeds the API rate limit (HTTP 429).\n *\n * The {@link retryAfter} property indicates how many seconds to wait\n * before retrying, as reported by the server's `Retry-After` header.\n *\n * @example\n * ```ts\n * try {\n * await client.recall({ agentId: \"...\", query: \"...\" });\n * } catch (e) {\n * if (e instanceof RateLimitError) {\n * console.log(`Retry after ${e.retryAfter} seconds`);\n * }\n * }\n * ```\n */\nexport class RateLimitError extends Z3rnoError {\n /** Number of seconds to wait before retrying, per the Retry-After header. */\n retryAfter: number;\n\n /**\n * @param message - Description of the rate-limit error.\n * @param retryAfter - Seconds to wait before retrying (defaults to 60).\n */\n constructor(message: string, retryAfter: number = 60) {\n super(message, 429);\n this.name = \"RateLimitError\";\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Thrown when the server rejects the request due to invalid input (HTTP 400 or 422).\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"not-a-uuid\", content: \"\" });\n * } catch (e) {\n * if (e instanceof ValidationError) {\n * console.error(`Validation failed: ${e.message}`);\n * }\n * }\n * ```\n */\nexport class ValidationError extends Z3rnoError {\n /**\n * @param message - Description of the validation failure.\n * @param statusCode - HTTP status code (400 or 422, defaults to 400).\n */\n constructor(message: string, statusCode: number = 400) {\n super(message, statusCode);\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Thrown when the requested resource does not exist (HTTP 404).\n *\n * @example\n * ```ts\n * try {\n * await client.getMemory(\"non-existent-id\");\n * } catch (e) {\n * if (e instanceof NotFoundError) {\n * console.error(\"Memory not found\");\n * }\n * }\n * ```\n */\nexport class NotFoundError extends Z3rnoError {\n /**\n * @param message - Description of what was not found.\n */\n constructor(message: string) {\n super(message, 404);\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * Thrown when the Z3rno API returns a server-side error (HTTP 5xx).\n *\n * The SDK automatically retries on 5xx errors with exponential backoff.\n * This error is only thrown after all retries are exhausted.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof ServerError) {\n * console.error(`Server error (${e.statusCode}): ${e.message}`);\n * }\n * }\n * ```\n */\nexport class ServerError extends Z3rnoError {\n /**\n * @param message - Description of the server error.\n * @param statusCode - HTTP status code (defaults to 500).\n */\n constructor(message: string, statusCode: number = 500) {\n super(message, statusCode);\n this.name = \"ServerError\";\n }\n}\n\n/**\n * Thrown when a request exceeds the configured timeout duration.\n *\n * The SDK uses an {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController | AbortController}\n * to enforce timeouts. This error is thrown after all retries are exhausted.\n *\n * @example\n * ```ts\n * const client = new Z3rnoClient({ timeout: 5000 }); // 5 seconds\n * try {\n * await client.recall({ agentId: \"...\", query: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoTimeoutError) {\n * console.error(`Timed out after ${e.timeout}ms`);\n * }\n * }\n * ```\n */\nexport class Z3rnoTimeoutError extends Z3rnoError {\n /** The timeout duration in milliseconds that was exceeded. */\n timeout: number;\n\n /**\n * @param message - Description of the timeout.\n * @param timeout - The configured timeout value in milliseconds.\n */\n constructor(message: string, timeout: number) {\n super(message, undefined);\n this.name = \"Z3rnoTimeoutError\";\n this.timeout = timeout;\n }\n}\n\n/**\n * Thrown when the SDK cannot establish a connection to the Z3rno API.\n *\n * This typically indicates a network issue, DNS failure, or the server\n * being unreachable. The SDK retries connection errors with exponential\n * backoff before throwing this error.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoConnectionError) {\n * console.error(\"Cannot reach Z3rno API — check your network\");\n * }\n * }\n * ```\n */\nexport class Z3rnoConnectionError extends Z3rnoError {\n /**\n * @param message - Description of the connection failure.\n */\n constructor(message: string) {\n super(message, undefined);\n this.name = \"Z3rnoConnectionError\";\n }\n}\n","/**\n * Zod schemas and inferred TypeScript types for the Z3rno API.\n *\n * Each export is a dual: a Zod schema (used for runtime validation) and an\n * identically-named TypeScript type (used at compile time). Request schemas\n * validate client-side input; response schemas validate server payloads.\n *\n * @module models\n */\n\nimport { z } from \"zod\";\n\n// --- Enums ---\n\n/**\n * Memory type enum.\n *\n * Controls how a memory is stored, indexed, and decayed.\n *\n * - `working` — Short-lived scratchpad memory (high decay rate).\n * - `episodic` — Event-based memory tied to a specific interaction.\n * - `semantic` — Long-term factual knowledge.\n * - `procedural` — How-to or process knowledge.\n */\nexport const MemoryType = z.enum([\n \"working\",\n \"episodic\",\n \"semantic\",\n \"procedural\",\n]);\n\n/** Memory type: `\"working\"` | `\"episodic\"` | `\"semantic\"` | `\"procedural\"`. */\nexport type MemoryType = z.infer<typeof MemoryType>;\n\n/**\n * Relationship type enum.\n *\n * Describes how two memories are related in the knowledge graph.\n *\n * - `derived_from` — This memory was created from another.\n * - `contradicts` — This memory conflicts with another.\n * - `supports` — This memory reinforces another.\n * - `supersedes` — This memory replaces another.\n * - `related_to` — General association.\n * - `caused_by` — Causal relationship.\n */\nexport const RelationshipType = z.enum([\n \"derived_from\",\n \"contradicts\",\n \"supports\",\n \"supersedes\",\n \"related_to\",\n \"caused_by\",\n]);\n\n/** Relationship type between two memories. */\nexport type RelationshipType = z.infer<typeof RelationshipType>;\n\n// --- Request schemas ---\n\n/**\n * Schema for storing a new memory.\n *\n * @example\n * ```ts\n * const request = StoreMemoryRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * memoryType: \"semantic\",\n * });\n * ```\n */\nexport const StoreMemoryRequest = z.object({\n /** UUID of the agent that owns this memory. */\n agentId: z.string().uuid(),\n /** The text content to store (1 to 100,000 characters). */\n content: z.string().min(1).max(100000),\n /** Category of memory. Defaults to `\"episodic\"`. */\n memoryType: MemoryType.default(\"episodic\"),\n /** Optional UUID of the user associated with this memory. */\n userId: z.string().uuid().optional(),\n /** Arbitrary key-value metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n /** Relationships to other memories in the knowledge graph. */\n relationships: z\n .array(\n z.object({\n /** UUID of the target memory. */\n targetMemoryId: z.string().uuid(),\n /** Type of relationship to the target memory. */\n relationshipType: RelationshipType,\n /** Relationship strength from 0 to 1. Defaults to 1.0. */\n weight: z.number().min(0).max(1).default(1.0),\n /** Arbitrary metadata for the relationship edge. */\n metadata: z.record(z.unknown()).default({}),\n }),\n )\n .default([]),\n /** Time-to-live in seconds. Memory auto-deletes after this duration. */\n ttlSeconds: z.number().int().positive().optional(),\n /** Importance score from 0 to 1. Influences recall ranking. */\n importance: z.number().min(0).max(1).optional(),\n});\n\n/** Parsed type for a store-memory request. */\nexport type StoreMemoryRequest = z.infer<typeof StoreMemoryRequest>;\n\n/**\n * Schema for recalling memories by semantic similarity.\n *\n * @example\n * ```ts\n * const request = RecallRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * topK: 5,\n * });\n * ```\n */\nexport const RecallRequest = z.object({\n /** UUID of the agent whose memories to search. */\n agentId: z.string().uuid(),\n /** Natural-language query for semantic similarity search. */\n query: z.string().optional(),\n /** Filter results to a specific memory type. */\n memoryType: z.string().optional(),\n /** Additional metadata filters. */\n filters: z.record(z.unknown()).optional(),\n /** Maximum number of results to return (1-100, default 10). */\n topK: z.number().int().min(1).max(100).default(10),\n /** Minimum similarity score threshold (0-1, default 0). */\n similarityThreshold: z.number().min(0).max(1).default(0),\n /** ISO 8601 timestamp for temporal queries (point-in-time recall). */\n asOf: z.string().datetime().optional(),\n /** Whether to include soft-deleted memories. */\n includeDeleted: z.boolean().default(false),\n});\n\n/** Parsed type for a recall request. */\nexport type RecallRequest = z.infer<typeof RecallRequest>;\n\n/**\n * Schema for forgetting (deleting) memories.\n *\n * @example\n * ```ts\n * const request = ForgetRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * memoryId: \"mem-123\",\n * hardDelete: true,\n * });\n * ```\n */\nexport const ForgetRequest = z.object({\n /** UUID of the agent that owns the memories. */\n agentId: z.string().uuid(),\n /** UUID of a single memory to delete. */\n memoryId: z.string().uuid().optional(),\n /** UUIDs of multiple memories to delete in one call. */\n memoryIds: z.array(z.string().uuid()).optional(),\n /** If true, permanently deletes (vs. soft-delete). Defaults to false. */\n hardDelete: z.boolean().default(false),\n /** If true, also deletes related memories. Defaults to false. */\n cascade: z.boolean().default(false),\n /** Optional reason for the deletion (stored in audit log). */\n reason: z.string().optional(),\n});\n\n/** Parsed type for a forget request. */\nexport type ForgetRequest = z.infer<typeof ForgetRequest>;\n\n// --- Response schemas ---\n\n/**\n * Schema for a single memory object returned by the API.\n *\n * Used by {@link Z3rnoClient.store}, {@link Z3rnoClient.getMemory}, and\n * {@link Z3rnoClient.updateMemory}.\n */\nexport const MemoryResponse = z.object({\n /** Unique identifier for this memory. */\n id: z.string(),\n /** UUID of the owning agent. */\n agent_id: z.string(),\n /** Text content of the memory. */\n content: z.string(),\n /** Category of the memory. */\n memory_type: z.string(),\n /** Server-computed importance score (0-1). */\n importance_score: z.number(),\n /** Number of times this memory has been recalled. */\n recall_count: z.number(),\n /** Name of the embedding model used, if any. */\n embedding_model: z.string().nullable().optional(),\n /** ISO 8601 creation timestamp. */\n created_at: z.string(),\n /** Arbitrary metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a memory response. */\nexport type MemoryResponse = z.infer<typeof MemoryResponse>;\n\n/**\n * Schema for a single item in recall results.\n *\n * Each item includes similarity, importance, and relevance scores\n * computed by the server's ranking algorithm.\n */\nexport const RecallResultItem = z.object({\n /** Unique identifier of the recalled memory. */\n memory_id: z.string(),\n /** Text content of the memory. */\n content: z.string(),\n /** Optional server-generated summary. */\n summary: z.string().nullable().optional(),\n /** Category of the memory. */\n memory_type: z.string(),\n /** Cosine similarity to the query (0-1). */\n similarity_score: z.number(),\n /** Server-computed importance score (0-1). */\n importance_score: z.number(),\n /** Combined relevance score used for ranking (0-1). */\n relevance_score: z.number(),\n /** Number of times this memory has been recalled. */\n recall_count: z.number(),\n /** ISO 8601 creation timestamp. */\n created_at: z.string(),\n /** Arbitrary metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a single recall result item. */\nexport type RecallResultItem = z.infer<typeof RecallResultItem>;\n\n/**\n * Schema for the full recall response.\n *\n * Contains an array of ranked results and the total count of matches.\n */\nexport const RecallResponse = z.object({\n /** Ranked list of matching memories. */\n results: z.array(RecallResultItem),\n /** Total number of matches (may exceed `topK`). */\n total: z.number(),\n /** The query that was searched, if any. */\n query: z.string().nullable().optional(),\n});\n\n/** Parsed type for a recall response. */\nexport type RecallResponse = z.infer<typeof RecallResponse>;\n\n/**\n * Schema for the forget (delete) response.\n *\n * Reports how many memories were deleted and whether cascade was applied.\n */\nexport const ForgetResponse = z.object({\n /** Number of memories deleted. */\n deleted_count: z.number(),\n /** Whether a hard delete was performed. */\n hard_deleted: z.boolean(),\n /** Number of related memories deleted via cascade. */\n cascade_count: z.number(),\n /** IDs of all deleted memories. */\n memory_ids: z.array(z.string()),\n});\n\n/** Parsed type for a forget response. */\nexport type ForgetResponse = z.infer<typeof ForgetResponse>;\n\n/**\n * Schema for a single audit log entry.\n *\n * Audit entries record every operation performed on the agent's memories.\n */\nexport const AuditEntry = z.object({\n /** Auto-incrementing audit entry ID. */\n id: z.number(),\n /** UUID of the agent, if applicable. */\n agent_id: z.string().nullable().optional(),\n /** UUID of the user, if applicable. */\n user_id: z.string().nullable().optional(),\n /** Operation type (e.g., `\"store\"`, `\"recall\"`, `\"forget\"`). */\n operation: z.string(),\n /** UUID of the affected memory, if applicable. */\n memory_id: z.string().nullable().optional(),\n /** Memory type of the affected memory, if applicable. */\n memory_type: z.string().nullable().optional(),\n /** Additional details about the operation. */\n details: z.record(z.unknown()).default({}),\n /** IP address of the caller, if available. */\n ip_address: z.string().nullable().optional(),\n /** ISO 8601 timestamp of the operation. */\n created_at: z.string(),\n});\n\n/** Parsed type for an audit entry. */\nexport type AuditEntry = z.infer<typeof AuditEntry>;\n\n/**\n * Schema for a paginated audit log response.\n *\n * Supports cursor-based pagination via `page` and `page_size`.\n */\nexport const AuditPageResponse = z.object({\n /** Audit entries on this page. */\n entries: z.array(AuditEntry),\n /** Total number of matching audit entries. */\n total: z.number(),\n /** Current page number (1-indexed). */\n page: z.number(),\n /** Number of entries per page. */\n page_size: z.number(),\n /** Whether more pages are available. */\n has_next: z.boolean(),\n});\n\n/** Parsed type for a paginated audit response. */\nexport type AuditPageResponse = z.infer<typeof AuditPageResponse>;\n\n// --- Batch Store ---\n\n/**\n * Schema for the batch store response.\n *\n * Returned by {@link Z3rnoClient.storeBatch} after storing multiple memories.\n */\nexport const BatchStoreResponse = z.object({\n /** Array of stored memory objects. */\n results: z.array(MemoryResponse),\n /** Number of memories successfully stored. */\n stored_count: z.number(),\n});\n\n/** Parsed type for a batch store response. */\nexport type BatchStoreResponse = z.infer<typeof BatchStoreResponse>;\n\n// --- Memory History ---\n\n/**\n * Schema for a single version of a memory (temporal versioning).\n *\n * Each version represents the state of a memory during a specific time range.\n */\nexport const MemoryVersion = z.object({\n /** Version identifier. */\n id: z.string(),\n /** Text content at this version. */\n content: z.string(),\n /** Memory type at this version. */\n memory_type: z.string(),\n /** Importance score at this version. */\n importance_score: z.number(),\n /** ISO 8601 timestamp when this version became active. */\n valid_from: z.string(),\n /** ISO 8601 timestamp when this version was superseded, or null if current. */\n valid_to: z.string().nullable().optional(),\n /** Metadata at this version. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a memory version. */\nexport type MemoryVersion = z.infer<typeof MemoryVersion>;\n\n/**\n * Schema for the memory history response.\n *\n * Contains all temporal versions of a single memory, ordered chronologically.\n */\nexport const MemoryHistoryResponse = z.object({\n /** UUID of the memory. */\n memory_id: z.string(),\n /** Chronologically ordered list of versions. */\n versions: z.array(MemoryVersion),\n /** Total number of versions. */\n total: z.number(),\n});\n\n/** Parsed type for a memory history response. */\nexport type MemoryHistoryResponse = z.infer<typeof MemoryHistoryResponse>;\n\n// --- Sessions ---\n\n/**\n * Schema for a session response.\n *\n * Sessions group related memory operations (e.g., a conversation turn).\n */\nexport const SessionResponse = z.object({\n /** Unique session identifier. */\n session_id: z.string(),\n /** UUID of the agent this session belongs to. */\n agent_id: z.string(),\n /** Type of session (e.g., `\"conversation\"`). */\n session_type: z.string(),\n /** ISO 8601 timestamp when the session started. */\n started_at: z.string(),\n /** Arbitrary session metadata. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a session response. */\nexport type SessionResponse = z.infer<typeof SessionResponse>;\n\n/**\n * Schema for the end-session response.\n *\n * Returned when a session is closed, including summary statistics.\n */\nexport const EndSessionResponse = z.object({\n /** The session that was ended. */\n session_id: z.string(),\n /** ISO 8601 timestamp when the session ended. */\n ended_at: z.string(),\n /** Total duration of the session in seconds. */\n duration_seconds: z.number(),\n /** Number of memories created during the session. */\n memory_count: z.number(),\n});\n\n/** Parsed type for an end-session response. */\nexport type EndSessionResponse = z.infer<typeof EndSessionResponse>;\n","/**\n * Z3rno TypeScript SDK client.\n *\n * Thin fetch wrapper — no database drivers, no embedding providers.\n * Works in Node.js 18+, Deno, Bun, and modern browsers (any runtime\n * with a global `fetch` and `AbortController`).\n *\n * @module client\n *\n * @example\n * ```ts\n * const client = new Z3rnoClient({ baseUrl: \"http://localhost:8000\", apiKey: \"z3rno_sk_...\" });\n * const memory = await client.store({ agentId: \"agent-1\", content: \"User prefers dark mode\" });\n * const results = await client.recall({ agentId: \"agent-1\", query: \"user preferences\" });\n * await client.forget({ agentId: \"agent-1\", memoryId: memory.id });\n * ```\n */\n\nimport {\n AuthenticationError,\n NotFoundError,\n RateLimitError,\n ServerError,\n ValidationError,\n Z3rnoConnectionError,\n Z3rnoError,\n Z3rnoTimeoutError,\n} from \"./errors.js\";\nimport type {\n AuditPageResponse,\n BatchStoreResponse,\n EndSessionResponse,\n ForgetResponse,\n MemoryHistoryResponse,\n MemoryResponse,\n RecallResponse,\n SessionResponse,\n StoreMemoryRequest,\n} from \"./models.js\";\nimport {\n AuditPageResponse as AuditPageSchema,\n BatchStoreResponse as BatchStoreSchema,\n EndSessionResponse as EndSessionSchema,\n ForgetResponse as ForgetSchema,\n MemoryHistoryResponse as MemoryHistorySchema,\n MemoryResponse as MemorySchema,\n RecallResponse as RecallSchema,\n SessionResponse as SessionSchema,\n} from \"./models.js\";\n\n/**\n * Configuration options for the {@link Z3rnoClient}.\n *\n * All fields are optional. When omitted, the client reads from environment\n * variables (`Z3RNO_BASE_URL`, `Z3RNO_API_KEY`) or uses sensible defaults.\n */\nexport interface Z3rnoClientConfig {\n /**\n * Base URL of the Z3rno API.\n *\n * Falls back to the `Z3RNO_BASE_URL` environment variable, then\n * to `\"https://api.z3rno.dev\"`.\n */\n baseUrl?: string;\n\n /**\n * API key for authentication.\n *\n * Falls back to the `Z3RNO_API_KEY` environment variable, then to\n * an empty string (unauthenticated).\n */\n apiKey?: string;\n\n /**\n * Request timeout in milliseconds.\n *\n * @defaultValue 30000 (30 seconds)\n */\n timeout?: number;\n\n /**\n * Maximum number of retry attempts for retryable errors (5xx, 429,\n * network failures, timeouts).\n *\n * @defaultValue 3\n */\n maxRetries?: number;\n\n /**\n * Custom fetch implementation.\n *\n * Defaults to `globalThis.fetch`. Override to use `undici`, `node-fetch`,\n * or a test double.\n *\n * @defaultValue globalThis.fetch\n */\n fetch?: typeof globalThis.fetch;\n\n /**\n * Intercept outgoing requests before they are sent.\n *\n * Use this to add custom headers, log requests, or collect metrics.\n * The callback receives the URL and the `RequestInit` and must return\n * a (possibly modified) `RequestInit`.\n */\n onRequest?: (url: string, init: RequestInit) => RequestInit;\n\n /**\n * Intercept responses before they are processed.\n *\n * Use this for logging, metrics, or response transformation.\n * The callback receives the `Response` and must return a `Response`.\n */\n onResponse?: (response: Response) => Response;\n}\n\n/**\n * Client for the Z3rno AI agent memory API.\n *\n * Uses the standard Fetch API under the hood, making it compatible with\n * Node.js 18+, Deno, Bun, and modern browsers. All responses are\n * validated at runtime with Zod schemas.\n *\n * @example\n * ```ts\n * import { Z3rnoClient } from \"@z3rno/sdk\";\n *\n * const client = new Z3rnoClient({\n * baseUrl: \"http://localhost:8000\",\n * apiKey: \"z3rno_sk_test_...\",\n * });\n *\n * // Store a memory\n * const mem = await client.store({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * });\n *\n * // Recall relevant memories\n * const results = await client.recall({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * });\n * ```\n */\nexport class Z3rnoClient {\n private baseUrl: string;\n private apiKey: string;\n private timeout: number;\n private maxRetries: number;\n private fetchImpl: typeof globalThis.fetch;\n private onRequest?: (url: string, init: RequestInit) => RequestInit;\n private onResponse?: (response: Response) => Response;\n\n /**\n * Creates a new Z3rno client instance.\n *\n * @param config - Client configuration options. All fields are optional.\n *\n * @example\n * ```ts\n * // Explicit configuration\n * const client = new Z3rnoClient({\n * baseUrl: \"http://localhost:8000\",\n * apiKey: \"z3rno_sk_test_...\",\n * timeout: 10000,\n * maxRetries: 2,\n * });\n *\n * // Or rely on environment variables (Z3RNO_BASE_URL, Z3RNO_API_KEY)\n * const client = new Z3rnoClient();\n * ```\n */\n constructor(config: Z3rnoClientConfig = {}) {\n // Resolve baseUrl: explicit > env var > default\n let resolvedUrl = config.baseUrl ?? \"\";\n if (!resolvedUrl && typeof process !== \"undefined\" && process.env) {\n resolvedUrl = process.env.Z3RNO_BASE_URL ?? \"\";\n }\n if (!resolvedUrl) {\n resolvedUrl = \"https://api.z3rno.dev\";\n }\n this.baseUrl = resolvedUrl.replace(/\\/$/, \"\");\n\n // Resolve apiKey: explicit > env var > empty\n let resolvedKey = config.apiKey ?? \"\";\n if (!resolvedKey && typeof process !== \"undefined\" && process.env) {\n resolvedKey = process.env.Z3RNO_API_KEY ?? \"\";\n }\n this.apiKey = resolvedKey;\n\n this.timeout = config.timeout ?? 30000;\n this.maxRetries = config.maxRetries ?? 3;\n this.fetchImpl = config.fetch ?? globalThis.fetch;\n this.onRequest = config.onRequest;\n this.onResponse = config.onResponse;\n }\n\n // --- Store ---\n\n /**\n * Stores a new memory for an agent.\n *\n * The server generates an embedding for the content and stores it in\n * the vector database. The memory is immediately available for recall.\n *\n * @param request - The memory to store.\n * @returns The stored memory, including the server-generated ID and scores.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link ValidationError} If the request body is invalid.\n * @throws {@link Z3rnoTimeoutError} If the request times out.\n *\n * @example\n * ```ts\n * const memory = await client.store({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * memoryType: \"semantic\",\n * metadata: { source: \"settings-page\" },\n * });\n * console.log(memory.id); // \"mem-abc123\"\n * ```\n */\n async store(request: StoreMemoryRequest): Promise<MemoryResponse> {\n const body = {\n agent_id: request.agentId,\n content: request.content,\n memory_type: request.memoryType,\n user_id: request.userId,\n metadata: request.metadata,\n relationships: request.relationships?.map((r) => ({\n target_memory_id: r.targetMemoryId,\n relationship_type: r.relationshipType,\n weight: r.weight,\n metadata: r.metadata,\n })),\n ttl_seconds: request.ttlSeconds,\n importance: request.importance,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories\", body);\n return MemorySchema.parse(resp);\n }\n\n // --- Recall ---\n\n /**\n * Recalls memories by semantic similarity to a query.\n *\n * Returns a ranked list of memories sorted by a combined relevance score\n * that factors in similarity, importance, and recency.\n *\n * @param params - Recall parameters including the query and filters.\n * @param params.agentId - UUID of the agent whose memories to search.\n * @param params.query - Natural-language query for semantic search.\n * @param params.memoryType - Filter by memory type.\n * @param params.filters - Additional metadata filters.\n * @param params.topK - Maximum results to return (default 10).\n * @param params.similarityThreshold - Minimum similarity score (default 0).\n * @returns Ranked recall results with similarity scores.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link Z3rnoTimeoutError} If the request times out.\n *\n * @example\n * ```ts\n * const results = await client.recall({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * topK: 5,\n * similarityThreshold: 0.7,\n * });\n * for (const item of results.results) {\n * console.log(`${item.content} (score: ${item.relevance_score})`);\n * }\n * ```\n */\n async recall(params: {\n agentId: string;\n query?: string;\n memoryType?: string;\n filters?: Record<string, unknown>;\n topK?: number;\n similarityThreshold?: number;\n }): Promise<RecallResponse> {\n const body = {\n agent_id: params.agentId,\n query: params.query,\n memory_type: params.memoryType,\n filters: params.filters,\n top_k: params.topK ?? 10,\n similarity_threshold: params.similarityThreshold ?? 0,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/recall\", body);\n return RecallSchema.parse(resp);\n }\n\n // --- Forget ---\n\n /**\n * Forgets (deletes) one or more memories.\n *\n * By default, performs a soft delete (marks as deleted but retains data).\n * Set `hardDelete: true` for permanent removal. Use `cascade: true` to\n * also delete related memories in the knowledge graph.\n *\n * @param params - Forget parameters.\n * @param params.agentId - UUID of the agent that owns the memories.\n * @param params.memoryId - UUID of a single memory to delete.\n * @param params.memoryIds - UUIDs of multiple memories to delete.\n * @param params.hardDelete - Permanently delete (default false).\n * @param params.cascade - Delete related memories too (default false).\n * @param params.reason - Reason for deletion (stored in audit log).\n * @returns Summary of the deletion operation.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link NotFoundError} If the specified memory does not exist.\n *\n * @example\n * ```ts\n * const result = await client.forget({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * memoryId: \"mem-abc123\",\n * hardDelete: true,\n * reason: \"User requested data deletion\",\n * });\n * console.log(`Deleted ${result.deleted_count} memories`);\n * ```\n */\n async forget(params: {\n agentId: string;\n memoryId?: string;\n memoryIds?: string[];\n hardDelete?: boolean;\n cascade?: boolean;\n reason?: string;\n }): Promise<ForgetResponse> {\n const body = {\n agent_id: params.agentId,\n memory_id: params.memoryId,\n memory_ids: params.memoryIds,\n hard_delete: params.hardDelete ?? false,\n cascade: params.cascade ?? false,\n reason: params.reason,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/forget\", body);\n return ForgetSchema.parse(resp);\n }\n\n // --- Get Memory ---\n\n /**\n * Retrieves a single memory by its ID.\n *\n * @param memoryId - The unique identifier of the memory to retrieve.\n * @returns The full memory object.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const memory = await client.getMemory(\"mem-abc123\");\n * console.log(memory.content);\n * console.log(memory.importance_score);\n * ```\n */\n async getMemory(memoryId: string): Promise<MemoryResponse> {\n const resp = await this.request(\"GET\", `/v1/memories/${memoryId}`);\n return MemorySchema.parse(resp);\n }\n\n // --- Store Batch ---\n\n /**\n * Stores multiple memories in a single API call.\n *\n * More efficient than calling {@link store} in a loop. All memories are\n * processed atomically on the server.\n *\n * @param memories - Array of memories to store.\n * @returns The stored memories and a count of how many were created.\n * @throws {@link ValidationError} If any memory in the batch is invalid.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const result = await client.storeBatch([\n * { agentId: \"agent-1\", content: \"Fact one\" },\n * { agentId: \"agent-1\", content: \"Fact two\", memoryType: \"semantic\" },\n * ]);\n * console.log(`Stored ${result.stored_count} memories`);\n * ```\n */\n async storeBatch(\n memories: StoreMemoryRequest[],\n ): Promise<BatchStoreResponse> {\n const body = {\n memories: memories.map((m) => ({\n agent_id: m.agentId,\n content: m.content,\n memory_type: m.memoryType,\n metadata: m.metadata,\n importance: m.importance,\n })),\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/batch\", body);\n return BatchStoreSchema.parse(resp);\n }\n\n // --- Memory History ---\n\n /**\n * Retrieves the full version history of a memory.\n *\n * Z3rno uses temporal versioning — every update creates a new version\n * rather than overwriting. This method returns all versions ordered\n * chronologically.\n *\n * @param memoryId - The unique identifier of the memory.\n * @returns All versions of the memory with validity timestamps.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const history = await client.getMemoryHistory(\"mem-abc123\");\n * for (const version of history.versions) {\n * console.log(`${version.valid_from}: ${version.content}`);\n * }\n * ```\n */\n async getMemoryHistory(memoryId: string): Promise<MemoryHistoryResponse> {\n const resp = await this.request(\"GET\", `/v1/memories/${memoryId}/history`);\n return MemoryHistorySchema.parse(resp);\n }\n\n // --- Update Memory ---\n\n /**\n * Updates an existing memory's content, metadata, or importance.\n *\n * Creates a new temporal version of the memory. The previous version\n * remains accessible via {@link getMemoryHistory}.\n *\n * @param memoryId - The unique identifier of the memory to update.\n * @param updates - Fields to update (only provided fields are changed).\n * @param updates.content - New text content.\n * @param updates.metadata - New metadata (replaces existing metadata).\n * @param updates.importance - New importance score (0-1).\n * @returns The updated memory object.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link ValidationError} If the update values are invalid.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const updated = await client.updateMemory(\"mem-abc123\", {\n * content: \"User now prefers light mode\",\n * importance: 0.9,\n * });\n * ```\n */\n async updateMemory(\n memoryId: string,\n updates: {\n content?: string;\n metadata?: Record<string, unknown>;\n importance?: number;\n },\n ): Promise<MemoryResponse> {\n const body: Record<string, unknown> = {};\n if (updates.content !== undefined) body.content = updates.content;\n if (updates.metadata !== undefined) body.metadata = updates.metadata;\n if (updates.importance !== undefined) body.importance = updates.importance;\n\n const resp = await this.request(\"PATCH\", `/v1/memories/${memoryId}`, body);\n return MemorySchema.parse(resp);\n }\n\n // --- Sessions ---\n\n /**\n * Starts a new session for grouping related memory operations.\n *\n * Sessions are useful for tracking conversation turns or task boundaries.\n * Memories created during a session are automatically associated with it.\n *\n * @param params - Session parameters.\n * @param params.agentId - UUID of the agent to start the session for.\n * @param params.sessionType - Type of session (default `\"conversation\"`).\n * @returns The created session with its ID and start time.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const session = await client.startSession({ agentId: \"agent-1\" });\n * console.log(`Session started: ${session.session_id}`);\n * // ... perform operations ...\n * await client.endSession(session.session_id);\n * ```\n */\n async startSession(params: {\n agentId: string;\n sessionType?: string;\n }): Promise<SessionResponse> {\n const body = {\n agent_id: params.agentId,\n session_type: params.sessionType ?? \"conversation\",\n };\n\n const resp = await this.request(\"POST\", \"/v1/sessions\", body);\n return SessionSchema.parse(resp);\n }\n\n /**\n * Ends an active session.\n *\n * Returns summary statistics including the session duration and the\n * number of memories created during the session.\n *\n * @param sessionId - The unique identifier of the session to end.\n * @returns Session summary with duration and memory count.\n * @throws {@link NotFoundError} If no active session exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const summary = await client.endSession(\"sess-abc123\");\n * console.log(`Session lasted ${summary.duration_seconds}s, ${summary.memory_count} memories`);\n * ```\n */\n async endSession(sessionId: string): Promise<EndSessionResponse> {\n const resp = await this.request(\"POST\", `/v1/sessions/${sessionId}/end`);\n return EndSessionSchema.parse(resp);\n }\n\n // --- Audit ---\n\n /**\n * Retrieves a paginated audit log of memory operations.\n *\n * The audit log records every store, recall, forget, and update operation\n * performed by any agent. Useful for compliance, debugging, and analytics.\n *\n * @param params - Optional pagination and filter parameters.\n * @param params.agentId - Filter by agent UUID.\n * @param params.page - Page number (1-indexed).\n * @param params.pageSize - Number of entries per page.\n * @returns A page of audit log entries with pagination metadata.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const page = await client.audit({ agentId: \"agent-1\", page: 1, pageSize: 20 });\n * for (const entry of page.entries) {\n * console.log(`${entry.created_at}: ${entry.operation} on ${entry.memory_id}`);\n * }\n * if (page.has_next) {\n * const nextPage = await client.audit({ agentId: \"agent-1\", page: 2 });\n * }\n * ```\n */\n async audit(params?: {\n agentId?: string;\n page?: number;\n pageSize?: number;\n }): Promise<AuditPageResponse> {\n const searchParams = new URLSearchParams();\n if (params?.agentId) searchParams.set(\"agent_id\", params.agentId);\n if (params?.page) searchParams.set(\"page\", String(params.page));\n if (params?.pageSize)\n searchParams.set(\"page_size\", String(params.pageSize));\n\n const query = searchParams.toString();\n const path = query ? `/v1/audit?${query}` : \"/v1/audit\";\n const resp = await this.request(\"GET\", path);\n return AuditPageSchema.parse(resp);\n }\n\n // --- HTTP layer ---\n\n private async request(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<unknown> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const url = `${this.baseUrl}${path}`;\n let init: RequestInit = {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"@z3rno/sdk/0.0.1\",\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n };\n\n if (this.onRequest) {\n init = this.onRequest(url, init);\n }\n\n let response = await this.fetchImpl(url, init);\n\n if (this.onResponse) {\n response = this.onResponse(response);\n }\n\n clearTimeout(timeoutId);\n\n // On 429, honor Retry-After header and retry\n if (response.status === 429 && attempt < this.maxRetries) {\n const retryAfter = parseInt(\n response.headers.get(\"Retry-After\") ?? \"1\",\n 10,\n );\n await this.sleep(retryAfter * 1000);\n continue;\n }\n\n // On 5xx, retry with exponential backoff\n if (response.status >= 500 && attempt < this.maxRetries) {\n const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s\n await this.sleep(delay);\n continue;\n }\n\n return this.handleResponse(response);\n } catch (error) {\n clearTimeout(timeoutId);\n\n // Do not retry Z3rnoError subclasses (4xx client errors)\n if (error instanceof Z3rnoError) throw error;\n\n // Classify the error before deciding whether to retry\n if (error instanceof DOMException && error.name === \"AbortError\") {\n lastError = new Z3rnoTimeoutError(\n `Request timed out after ${this.timeout}ms`,\n this.timeout,\n );\n } else if (error instanceof TypeError) {\n lastError = new Z3rnoConnectionError(\n `Connection failed: ${error.message}`,\n );\n } else {\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n\n if (attempt < this.maxRetries) {\n const delay = Math.pow(2, attempt) * 1000;\n await this.sleep(delay);\n continue;\n }\n }\n }\n\n // After all retries exhausted, throw the last classified error\n if (lastError instanceof Z3rnoError) {\n throw lastError;\n }\n throw new Z3rnoError(\n `Request failed after ${this.maxRetries + 1} attempts: ${String(lastError)}`,\n );\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private async handleResponse(resp: Response): Promise<unknown> {\n if (resp.ok) {\n return resp.json();\n }\n\n let detail = resp.statusText;\n try {\n const text = await resp.text();\n try {\n const body = JSON.parse(text) as Record<string, unknown>;\n detail = String(body.detail ?? body.error ?? resp.statusText);\n } catch {\n // Response is not JSON (e.g., nginx HTML 502). Include the\n // beginning of the body so users can diagnose proxy/gateway issues.\n if (text.length > 0) {\n const preview = text.length > 200 ? text.slice(0, 200) + \"...\" : text;\n detail = `${resp.statusText} — ${preview}`;\n }\n }\n } catch {\n // Could not read body at all\n }\n\n switch (resp.status) {\n case 401:\n throw new AuthenticationError(`Authentication failed: ${detail}`);\n case 404:\n throw new NotFoundError(`Not found: ${detail}`);\n case 429: {\n const retryAfter = parseInt(\n resp.headers.get(\"Retry-After\") ?? \"60\",\n 10,\n );\n throw new RateLimitError(`Rate limit exceeded: ${detail}`, retryAfter);\n }\n case 400:\n case 422:\n throw new ValidationError(detail, resp.status);\n default:\n if (resp.status >= 500) {\n throw new ServerError(`Server error: ${detail}`, resp.status);\n }\n throw new Z3rnoError(\n `Unexpected error (${resp.status}): ${detail}`,\n resp.status,\n );\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/models.ts","../src/client.ts"],"names":[],"mappings":";;;AA4BO,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA;AAAA,EAEpC,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAA,CAAY,SAAiB,UAAA,EAAqB;AAChD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AACZ,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAAA,EACpB;AACF;AAgBO,IAAM,mBAAA,GAAN,cAAkC,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA,EAIlD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,SAAS,GAAG,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAmBO,IAAM,cAAA,GAAN,cAA6B,UAAA,CAAW;AAAA;AAAA,EAE7C,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAA,CAAY,OAAA,EAAiB,UAAA,GAAqB,EAAA,EAAI;AACpD,IAAA,KAAA,CAAM,SAAS,GAAG,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAAA,EACpB;AACF;AAgBO,IAAM,eAAA,GAAN,cAA8B,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9C,WAAA,CAAY,OAAA,EAAiB,UAAA,GAAqB,GAAA,EAAK;AACrD,IAAA,KAAA,CAAM,SAAS,UAAU,CAAA;AACzB,IAAA,IAAA,CAAK,IAAA,GAAO,iBAA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CAAA,CAAE,CAAA;AAAA,MAClE,KAAK,GAAA;AACH,QAAA,MAAM,IAAI,aAAA,CAAc,CAAA,WAAA,EAAc,MAAM,CAAA,CAAE,CAAA;AAAA,MAChD,KAAK,GAAA,EAAK;AACR,QAAA,MAAM,UAAA,GAAa,QAAA;AAAA,UACjB,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA,IAAK,IAAA;AAAA,UACnC;AAAA,SACF;AACA,QAAA,MAAM,IAAI,cAAA,CAAe,CAAA,qBAAA,EAAwB,MAAM,IAAI,UAAU,CAAA;AAAA,MACvE;AAAA,MACA,KAAK,GAAA;AAAA,MACL,KAAK,GAAA;AACH,QAAA,MAAM,IAAI,eAAA,CAAgB,MAAA,EAAQ,IAAA,CAAK,MAAM,CAAA;AAAA,MAC/C;AACE,QAAA,IAAI,IAAA,CAAK,UAAU,GAAA,EAAK;AACtB,UAAA,MAAM,IAAI,WAAA,CAAY,CAAA,cAAA,EAAiB,MAAM,CAAA,CAAA,EAAI,KAAK,MAAM,CAAA;AAAA,QAC9D;AACA,QAAA,MAAM,IAAI,UAAA;AAAA,UACR,CAAA,kBAAA,EAAqB,IAAA,CAAK,MAAM,CAAA,GAAA,EAAM,MAAM,CAAA,CAAA;AAAA,UAC5C,IAAA,CAAK;AAAA,SACP;AAAA;AACJ,EACF;AACF","file":"index.js","sourcesContent":["/**\n * Z3rno SDK error hierarchy.\n *\n * All errors thrown by the SDK extend {@link Z3rnoError}, which itself extends\n * the built-in `Error` class. This lets callers catch broadly (`Z3rnoError`)\n * or narrowly (`AuthenticationError`, `RateLimitError`, etc.).\n *\n * @module errors\n */\n\n/**\n * Base error class for all Z3rno SDK errors.\n *\n * Every error produced by the SDK is an instance of this class, so you can\n * use a single `catch (e) { if (e instanceof Z3rnoError) ... }` guard to\n * handle them all.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoError) {\n * console.error(`Z3rno error (${e.statusCode}): ${e.message}`);\n * }\n * }\n * ```\n */\nexport class Z3rnoError extends Error {\n /** HTTP status code returned by the server, if applicable. */\n statusCode?: number;\n\n /**\n * @param message - Human-readable description of the error.\n * @param statusCode - HTTP status code associated with the error, if any.\n */\n constructor(message: string, statusCode?: number) {\n super(message);\n this.name = \"Z3rnoError\";\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Thrown when the API key is missing, invalid, or revoked (HTTP 401).\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof AuthenticationError) {\n * console.error(\"Check your API key\");\n * }\n * }\n * ```\n */\nexport class AuthenticationError extends Z3rnoError {\n /**\n * @param message - Description of the authentication failure.\n */\n constructor(message: string) {\n super(message, 401);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Thrown when the client exceeds the API rate limit (HTTP 429).\n *\n * The {@link retryAfter} property indicates how many seconds to wait\n * before retrying, as reported by the server's `Retry-After` header.\n *\n * @example\n * ```ts\n * try {\n * await client.recall({ agentId: \"...\", query: \"...\" });\n * } catch (e) {\n * if (e instanceof RateLimitError) {\n * console.log(`Retry after ${e.retryAfter} seconds`);\n * }\n * }\n * ```\n */\nexport class RateLimitError extends Z3rnoError {\n /** Number of seconds to wait before retrying, per the Retry-After header. */\n retryAfter: number;\n\n /**\n * @param message - Description of the rate-limit error.\n * @param retryAfter - Seconds to wait before retrying (defaults to 60).\n */\n constructor(message: string, retryAfter: number = 60) {\n super(message, 429);\n this.name = \"RateLimitError\";\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Thrown when the server rejects the request due to invalid input (HTTP 400 or 422).\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"not-a-uuid\", content: \"\" });\n * } catch (e) {\n * if (e instanceof ValidationError) {\n * console.error(`Validation failed: ${e.message}`);\n * }\n * }\n * ```\n */\nexport class ValidationError extends Z3rnoError {\n /**\n * @param message - Description of the validation failure.\n * @param statusCode - HTTP status code (400 or 422, defaults to 400).\n */\n constructor(message: string, statusCode: number = 400) {\n super(message, statusCode);\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Thrown when the requested resource does not exist (HTTP 404).\n *\n * @example\n * ```ts\n * try {\n * await client.getMemory(\"non-existent-id\");\n * } catch (e) {\n * if (e instanceof NotFoundError) {\n * console.error(\"Memory not found\");\n * }\n * }\n * ```\n */\nexport class NotFoundError extends Z3rnoError {\n /**\n * @param message - Description of what was not found.\n */\n constructor(message: string) {\n super(message, 404);\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * Thrown when the Z3rno API returns a server-side error (HTTP 5xx).\n *\n * The SDK automatically retries on 5xx errors with exponential backoff.\n * This error is only thrown after all retries are exhausted.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof ServerError) {\n * console.error(`Server error (${e.statusCode}): ${e.message}`);\n * }\n * }\n * ```\n */\nexport class ServerError extends Z3rnoError {\n /**\n * @param message - Description of the server error.\n * @param statusCode - HTTP status code (defaults to 500).\n */\n constructor(message: string, statusCode: number = 500) {\n super(message, statusCode);\n this.name = \"ServerError\";\n }\n}\n\n/**\n * Thrown when a request exceeds the configured timeout duration.\n *\n * The SDK uses an {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController | AbortController}\n * to enforce timeouts. This error is thrown after all retries are exhausted.\n *\n * @example\n * ```ts\n * const client = new Z3rnoClient({ timeout: 5000 }); // 5 seconds\n * try {\n * await client.recall({ agentId: \"...\", query: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoTimeoutError) {\n * console.error(`Timed out after ${e.timeout}ms`);\n * }\n * }\n * ```\n */\nexport class Z3rnoTimeoutError extends Z3rnoError {\n /** The timeout duration in milliseconds that was exceeded. */\n timeout: number;\n\n /**\n * @param message - Description of the timeout.\n * @param timeout - The configured timeout value in milliseconds.\n */\n constructor(message: string, timeout: number) {\n super(message, undefined);\n this.name = \"Z3rnoTimeoutError\";\n this.timeout = timeout;\n }\n}\n\n/**\n * Thrown when the SDK cannot establish a connection to the Z3rno API.\n *\n * This typically indicates a network issue, DNS failure, or the server\n * being unreachable. The SDK retries connection errors with exponential\n * backoff before throwing this error.\n *\n * @example\n * ```ts\n * try {\n * await client.store({ agentId: \"...\", content: \"...\" });\n * } catch (e) {\n * if (e instanceof Z3rnoConnectionError) {\n * console.error(\"Cannot reach Z3rno API — check your network\");\n * }\n * }\n * ```\n */\nexport class Z3rnoConnectionError extends Z3rnoError {\n /**\n * @param message - Description of the connection failure.\n */\n constructor(message: string) {\n super(message, undefined);\n this.name = \"Z3rnoConnectionError\";\n }\n}\n","/**\n * Zod schemas and inferred TypeScript types for the Z3rno API.\n *\n * Each export is a dual: a Zod schema (used for runtime validation) and an\n * identically-named TypeScript type (used at compile time). Request schemas\n * validate client-side input; response schemas validate server payloads.\n *\n * @module models\n */\n\nimport { z } from \"zod\";\n\n// --- Enums ---\n\n/**\n * Memory type enum.\n *\n * Controls how a memory is stored, indexed, and decayed.\n *\n * - `working` — Short-lived scratchpad memory (high decay rate).\n * - `episodic` — Event-based memory tied to a specific interaction.\n * - `semantic` — Long-term factual knowledge.\n * - `procedural` — How-to or process knowledge.\n */\nexport const MemoryType = z.enum([\n \"working\",\n \"episodic\",\n \"semantic\",\n \"procedural\",\n]);\n\n/** Memory type: `\"working\"` | `\"episodic\"` | `\"semantic\"` | `\"procedural\"`. */\nexport type MemoryType = z.infer<typeof MemoryType>;\n\n/**\n * Relationship type enum.\n *\n * Describes how two memories are related in the knowledge graph.\n *\n * - `derived_from` — This memory was created from another.\n * - `contradicts` — This memory conflicts with another.\n * - `supports` — This memory reinforces another.\n * - `supersedes` — This memory replaces another.\n * - `related_to` — General association.\n * - `caused_by` — Causal relationship.\n */\nexport const RelationshipType = z.enum([\n \"derived_from\",\n \"contradicts\",\n \"supports\",\n \"supersedes\",\n \"related_to\",\n \"caused_by\",\n]);\n\n/** Relationship type between two memories. */\nexport type RelationshipType = z.infer<typeof RelationshipType>;\n\n/**\n * Retrieval strategy for `recall({ strategy: ... })` — Phase C.\n *\n * `AUTO` is the default; the server's LLM router picks one of the\n * others when configured. Use an explicit value to bypass routing.\n */\nexport const RetrievalStrategy = z.enum([\n \"AUTO\",\n \"VECTOR\",\n \"LEXICAL\",\n \"GRAPH\",\n \"TRIPLET\",\n \"TRACE\",\n \"TEMPORAL\",\n \"ASK\",\n \"CYPHER\",\n]);\n\n/** Retrieval strategy enum (canonical UPPERCASE names). */\nexport type RetrievalStrategy = z.infer<typeof RetrievalStrategy>;\n\n// --- Request schemas ---\n\n/**\n * Schema for storing a new memory.\n *\n * @example\n * ```ts\n * const request = StoreMemoryRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * memoryType: \"semantic\",\n * });\n * ```\n */\nexport const StoreMemoryRequest = z.object({\n /** UUID of the agent that owns this memory. */\n agentId: z.string().uuid(),\n /** The text content to store (1 to 100,000 characters). */\n content: z.string().min(1).max(100000),\n /** Category of memory. Defaults to `\"episodic\"`. */\n memoryType: MemoryType.default(\"episodic\"),\n /** Optional UUID of the user associated with this memory. */\n userId: z.string().uuid().optional(),\n /** Arbitrary key-value metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n /** Relationships to other memories in the knowledge graph. */\n relationships: z\n .array(\n z.object({\n /** UUID of the target memory. */\n targetMemoryId: z.string().uuid(),\n /** Type of relationship to the target memory. */\n relationshipType: RelationshipType,\n /** Relationship strength from 0 to 1. Defaults to 1.0. */\n weight: z.number().min(0).max(1).default(1.0),\n /** Arbitrary metadata for the relationship edge. */\n metadata: z.record(z.unknown()).default({}),\n }),\n )\n .default([]),\n /** Time-to-live in seconds. Memory auto-deletes after this duration. */\n ttlSeconds: z.number().int().positive().optional(),\n /** Importance score from 0 to 1. Influences recall ranking. */\n importance: z.number().min(0).max(1).optional(),\n});\n\n/** Parsed type for a store-memory request. */\nexport type StoreMemoryRequest = z.infer<typeof StoreMemoryRequest>;\n\n/**\n * Schema for recalling memories by semantic similarity.\n *\n * @example\n * ```ts\n * const request = RecallRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * topK: 5,\n * });\n * ```\n */\nexport const RecallRequest = z.object({\n /** UUID of the agent whose memories to search. */\n agentId: z.string().uuid(),\n /** Natural-language query for semantic similarity search. */\n query: z.string().optional(),\n /** Filter results to a specific memory type. */\n memoryType: z.string().optional(),\n /** Additional metadata filters. */\n filters: z.record(z.unknown()).optional(),\n /** Maximum number of results to return (1-100, default 10). */\n topK: z.number().int().min(1).max(100).default(10),\n /** Minimum similarity score threshold (0-1, default 0). */\n similarityThreshold: z.number().min(0).max(1).default(0),\n /** ISO 8601 timestamp for temporal queries (point-in-time recall). */\n asOf: z.string().datetime().optional(),\n /** Whether to include soft-deleted memories. */\n includeDeleted: z.boolean().default(false),\n /**\n * Phase C retrieval strategy. `AUTO` (default) lets the server's\n * LLM router pick the best fit. See {@link RetrievalStrategy}.\n */\n strategy: RetrievalStrategy.default(\"AUTO\"),\n /**\n * Phase C cross-encoder re-ranking. When `true`, the server\n * re-ranks the top results via a cross-encoder. Requires the\n * `sentence-transformers` extra on the server.\n */\n rerank: z.boolean().default(false),\n});\n\n/** Parsed type for a recall request. */\nexport type RecallRequest = z.infer<typeof RecallRequest>;\n\n/**\n * Schema for forgetting (deleting) memories.\n *\n * @example\n * ```ts\n * const request = ForgetRequest.parse({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * memoryId: \"mem-123\",\n * hardDelete: true,\n * });\n * ```\n */\nexport const ForgetRequest = z.object({\n /** UUID of the agent that owns the memories. */\n agentId: z.string().uuid(),\n /** UUID of a single memory to delete. */\n memoryId: z.string().uuid().optional(),\n /** UUIDs of multiple memories to delete in one call. */\n memoryIds: z.array(z.string().uuid()).optional(),\n /** If true, permanently deletes (vs. soft-delete). Defaults to false. */\n hardDelete: z.boolean().default(false),\n /** If true, also deletes related memories. Defaults to false. */\n cascade: z.boolean().default(false),\n /** Optional reason for the deletion (stored in audit log). */\n reason: z.string().optional(),\n});\n\n/** Parsed type for a forget request. */\nexport type ForgetRequest = z.infer<typeof ForgetRequest>;\n\n// --- Response schemas ---\n\n/**\n * Schema for a single memory object returned by the API.\n *\n * Used by {@link Z3rnoClient.store}, {@link Z3rnoClient.getMemory}, and\n * {@link Z3rnoClient.updateMemory}.\n */\nexport const MemoryResponse = z.object({\n /** Unique identifier for this memory. */\n id: z.string(),\n /** UUID of the owning agent. */\n agent_id: z.string(),\n /** Text content of the memory. */\n content: z.string(),\n /** Category of the memory. */\n memory_type: z.string(),\n /** Server-computed importance score (0-1). */\n importance_score: z.number(),\n /** Number of times this memory has been recalled. */\n recall_count: z.number(),\n /** Name of the embedding model used, if any. */\n embedding_model: z.string().nullable().optional(),\n /** ISO 8601 creation timestamp. */\n created_at: z.string(),\n /** Arbitrary metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a memory response. */\nexport type MemoryResponse = z.infer<typeof MemoryResponse>;\n\n/**\n * Schema for a single item in recall results.\n *\n * Each item includes similarity, importance, and relevance scores\n * computed by the server's ranking algorithm.\n */\nexport const RecallResultItem = z.object({\n /** Unique identifier of the recalled memory. */\n memory_id: z.string(),\n /** Text content of the memory. */\n content: z.string(),\n /** Optional server-generated summary. */\n summary: z.string().nullable().optional(),\n /** Category of the memory. */\n memory_type: z.string(),\n /** Cosine similarity to the query (0-1). */\n similarity_score: z.number(),\n /** Server-computed importance score (0-1). */\n importance_score: z.number(),\n /** Combined relevance score used for ranking (0-1). */\n relevance_score: z.number(),\n /** Number of times this memory has been recalled. */\n recall_count: z.number(),\n /** ISO 8601 creation timestamp. */\n created_at: z.string(),\n /** Arbitrary metadata attached to the memory. */\n metadata: z.record(z.unknown()).default({}),\n /**\n * Phase C per-source signals — e.g. `{ vector: 0.83, lexical: 0.61 }`.\n * Optional so older servers (v0.7.x) keep parsing.\n */\n score_components: z.record(z.number()).default({}),\n});\n\n/** Parsed type for a single recall result item. */\nexport type RecallResultItem = z.infer<typeof RecallResultItem>;\n\n/**\n * Schema for the full recall response.\n *\n * Contains an array of ranked results and the total count of matches.\n */\nexport const RecallResponse = z.object({\n /** Ranked list of matching memories. */\n results: z.array(RecallResultItem),\n /** Total number of matches (may exceed `topK`). */\n total: z.number(),\n /** The query that was searched, if any. */\n query: z.string().nullable().optional(),\n /** Phase C: strategy that actually ran (after AUTO routing + re-rank). */\n strategy_used: z.string().default(\"VECTOR\"),\n /** Phase C: AUTO's candidate list (e.g. `[\"AUTO->GRAPH\"]`). */\n strategies_considered: z.array(z.string()).default([]),\n /** Phase C: whether the cross-encoder re-rank ran. */\n reranked: z.boolean().default(false),\n /** Phase C: end-to-end recall latency on the server (ms). */\n elapsed_ms: z.number().default(0),\n});\n\n/** Parsed type for a recall response. */\nexport type RecallResponse = z.infer<typeof RecallResponse>;\n\n/**\n * Schema for the forget (delete) response.\n *\n * Reports how many memories were deleted and whether cascade was applied.\n */\nexport const ForgetResponse = z.object({\n /** Number of memories deleted. */\n deleted_count: z.number(),\n /** Whether a hard delete was performed. */\n hard_deleted: z.boolean(),\n /** Number of related memories deleted via cascade. */\n cascade_count: z.number(),\n /** IDs of all deleted memories. */\n memory_ids: z.array(z.string()),\n});\n\n/** Parsed type for a forget response. */\nexport type ForgetResponse = z.infer<typeof ForgetResponse>;\n\n/**\n * Schema for a single audit log entry.\n *\n * Audit entries record every operation performed on the agent's memories.\n */\nexport const AuditEntry = z.object({\n /** Auto-incrementing audit entry ID. */\n id: z.number(),\n /** UUID of the agent, if applicable. */\n agent_id: z.string().nullable().optional(),\n /** UUID of the user, if applicable. */\n user_id: z.string().nullable().optional(),\n /** Operation type (e.g., `\"store\"`, `\"recall\"`, `\"forget\"`). */\n operation: z.string(),\n /** UUID of the affected memory, if applicable. */\n memory_id: z.string().nullable().optional(),\n /** Memory type of the affected memory, if applicable. */\n memory_type: z.string().nullable().optional(),\n /** Additional details about the operation. */\n details: z.record(z.unknown()).default({}),\n /** IP address of the caller, if available. */\n ip_address: z.string().nullable().optional(),\n /** ISO 8601 timestamp of the operation. */\n created_at: z.string(),\n});\n\n/** Parsed type for an audit entry. */\nexport type AuditEntry = z.infer<typeof AuditEntry>;\n\n/**\n * Schema for a paginated audit log response.\n *\n * Supports cursor-based pagination via `page` and `page_size`.\n */\nexport const AuditPageResponse = z.object({\n /** Audit entries on this page. */\n entries: z.array(AuditEntry),\n /** Total number of matching audit entries. */\n total: z.number(),\n /** Current page number (1-indexed). */\n page: z.number(),\n /** Number of entries per page. */\n page_size: z.number(),\n /** Whether more pages are available. */\n has_next: z.boolean(),\n});\n\n/** Parsed type for a paginated audit response. */\nexport type AuditPageResponse = z.infer<typeof AuditPageResponse>;\n\n// --- Batch Store ---\n\n/**\n * Schema for the batch store response.\n *\n * Returned by {@link Z3rnoClient.storeBatch} after storing multiple memories.\n */\nexport const BatchStoreResponse = z.object({\n /** Array of stored memory objects. */\n results: z.array(MemoryResponse),\n /** Number of memories successfully stored. */\n stored_count: z.number(),\n});\n\n/** Parsed type for a batch store response. */\nexport type BatchStoreResponse = z.infer<typeof BatchStoreResponse>;\n\n// --- Memory History ---\n\n/**\n * Schema for a single version of a memory (temporal versioning).\n *\n * Each version represents the state of a memory during a specific time range.\n */\nexport const MemoryVersion = z.object({\n /** Version identifier. */\n id: z.string(),\n /** Text content at this version. */\n content: z.string(),\n /** Memory type at this version. */\n memory_type: z.string(),\n /** Importance score at this version. */\n importance_score: z.number(),\n /** ISO 8601 timestamp when this version became active. */\n valid_from: z.string(),\n /** ISO 8601 timestamp when this version was superseded, or null if current. */\n valid_to: z.string().nullable().optional(),\n /** Metadata at this version. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a memory version. */\nexport type MemoryVersion = z.infer<typeof MemoryVersion>;\n\n/**\n * Schema for the memory history response.\n *\n * Contains all temporal versions of a single memory, ordered chronologically.\n */\nexport const MemoryHistoryResponse = z.object({\n /** UUID of the memory. */\n memory_id: z.string(),\n /** Chronologically ordered list of versions. */\n versions: z.array(MemoryVersion),\n /** Total number of versions. */\n total: z.number(),\n});\n\n/** Parsed type for a memory history response. */\nexport type MemoryHistoryResponse = z.infer<typeof MemoryHistoryResponse>;\n\n// --- Sessions ---\n\n/**\n * Schema for a session response.\n *\n * Sessions group related memory operations (e.g., a conversation turn).\n */\nexport const SessionResponse = z.object({\n /** Unique session identifier. */\n session_id: z.string(),\n /** UUID of the agent this session belongs to. */\n agent_id: z.string(),\n /** Type of session (e.g., `\"conversation\"`). */\n session_type: z.string(),\n /** ISO 8601 timestamp when the session started. */\n started_at: z.string(),\n /** Arbitrary session metadata. */\n metadata: z.record(z.unknown()).default({}),\n});\n\n/** Parsed type for a session response. */\nexport type SessionResponse = z.infer<typeof SessionResponse>;\n\n/**\n * Schema for the end-session response.\n *\n * Returned when a session is closed, including summary statistics.\n */\nexport const EndSessionResponse = z.object({\n /** The session that was ended. */\n session_id: z.string(),\n /** ISO 8601 timestamp when the session ended. */\n ended_at: z.string(),\n /** Total duration of the session in seconds. */\n duration_seconds: z.number(),\n /** Number of memories created during the session. */\n memory_count: z.number(),\n});\n\n/** Parsed type for an end-session response. */\nexport type EndSessionResponse = z.infer<typeof EndSessionResponse>;\n","/**\n * Z3rno TypeScript SDK client.\n *\n * Thin fetch wrapper — no database drivers, no embedding providers.\n * Works in Node.js 18+, Deno, Bun, and modern browsers (any runtime\n * with a global `fetch` and `AbortController`).\n *\n * @module client\n *\n * @example\n * ```ts\n * const client = new Z3rnoClient({ baseUrl: \"http://localhost:8000\", apiKey: \"z3rno_sk_...\" });\n * const memory = await client.store({ agentId: \"agent-1\", content: \"User prefers dark mode\" });\n * const results = await client.recall({ agentId: \"agent-1\", query: \"user preferences\" });\n * await client.forget({ agentId: \"agent-1\", memoryId: memory.id });\n * ```\n */\n\nimport {\n AuthenticationError,\n NotFoundError,\n RateLimitError,\n ServerError,\n ValidationError,\n Z3rnoConnectionError,\n Z3rnoError,\n Z3rnoTimeoutError,\n} from \"./errors.js\";\nimport type {\n AuditPageResponse,\n BatchStoreResponse,\n EndSessionResponse,\n ForgetResponse,\n MemoryHistoryResponse,\n MemoryResponse,\n RecallResponse,\n SessionResponse,\n StoreMemoryRequest,\n} from \"./models.js\";\nimport {\n AuditPageResponse as AuditPageSchema,\n BatchStoreResponse as BatchStoreSchema,\n EndSessionResponse as EndSessionSchema,\n ForgetResponse as ForgetSchema,\n MemoryHistoryResponse as MemoryHistorySchema,\n MemoryResponse as MemorySchema,\n RecallResponse as RecallSchema,\n SessionResponse as SessionSchema,\n} from \"./models.js\";\n\n/**\n * Configuration options for the {@link Z3rnoClient}.\n *\n * All fields are optional. When omitted, the client reads from environment\n * variables (`Z3RNO_BASE_URL`, `Z3RNO_API_KEY`) or uses sensible defaults.\n */\nexport interface Z3rnoClientConfig {\n /**\n * Base URL of the Z3rno API.\n *\n * Falls back to the `Z3RNO_BASE_URL` environment variable, then\n * to `\"https://api.z3rno.dev\"`.\n */\n baseUrl?: string;\n\n /**\n * API key for authentication.\n *\n * Falls back to the `Z3RNO_API_KEY` environment variable, then to\n * an empty string (unauthenticated).\n */\n apiKey?: string;\n\n /**\n * Request timeout in milliseconds.\n *\n * @defaultValue 30000 (30 seconds)\n */\n timeout?: number;\n\n /**\n * Maximum number of retry attempts for retryable errors (5xx, 429,\n * network failures, timeouts).\n *\n * @defaultValue 3\n */\n maxRetries?: number;\n\n /**\n * Custom fetch implementation.\n *\n * Defaults to `globalThis.fetch`. Override to use `undici`, `node-fetch`,\n * or a test double.\n *\n * @defaultValue globalThis.fetch\n */\n fetch?: typeof globalThis.fetch;\n\n /**\n * Intercept outgoing requests before they are sent.\n *\n * Use this to add custom headers, log requests, or collect metrics.\n * The callback receives the URL and the `RequestInit` and must return\n * a (possibly modified) `RequestInit`.\n */\n onRequest?: (url: string, init: RequestInit) => RequestInit;\n\n /**\n * Intercept responses before they are processed.\n *\n * Use this for logging, metrics, or response transformation.\n * The callback receives the `Response` and must return a `Response`.\n */\n onResponse?: (response: Response) => Response;\n}\n\n/**\n * Client for the Z3rno AI agent memory API.\n *\n * Uses the standard Fetch API under the hood, making it compatible with\n * Node.js 18+, Deno, Bun, and modern browsers. All responses are\n * validated at runtime with Zod schemas.\n *\n * @example\n * ```ts\n * import { Z3rnoClient } from \"@z3rno/sdk\";\n *\n * const client = new Z3rnoClient({\n * baseUrl: \"http://localhost:8000\",\n * apiKey: \"z3rno_sk_test_...\",\n * });\n *\n * // Store a memory\n * const mem = await client.store({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * });\n *\n * // Recall relevant memories\n * const results = await client.recall({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * });\n * ```\n */\nexport class Z3rnoClient {\n private baseUrl: string;\n private apiKey: string;\n private timeout: number;\n private maxRetries: number;\n private fetchImpl: typeof globalThis.fetch;\n private onRequest?: (url: string, init: RequestInit) => RequestInit;\n private onResponse?: (response: Response) => Response;\n\n /**\n * Creates a new Z3rno client instance.\n *\n * @param config - Client configuration options. All fields are optional.\n *\n * @example\n * ```ts\n * // Explicit configuration\n * const client = new Z3rnoClient({\n * baseUrl: \"http://localhost:8000\",\n * apiKey: \"z3rno_sk_test_...\",\n * timeout: 10000,\n * maxRetries: 2,\n * });\n *\n * // Or rely on environment variables (Z3RNO_BASE_URL, Z3RNO_API_KEY)\n * const client = new Z3rnoClient();\n * ```\n */\n constructor(config: Z3rnoClientConfig = {}) {\n // Resolve baseUrl: explicit > env var > default\n let resolvedUrl = config.baseUrl ?? \"\";\n if (!resolvedUrl && typeof process !== \"undefined\" && process.env) {\n resolvedUrl = process.env.Z3RNO_BASE_URL ?? \"\";\n }\n if (!resolvedUrl) {\n resolvedUrl = \"https://api.z3rno.dev\";\n }\n this.baseUrl = resolvedUrl.replace(/\\/$/, \"\");\n\n // Resolve apiKey: explicit > env var > empty\n let resolvedKey = config.apiKey ?? \"\";\n if (!resolvedKey && typeof process !== \"undefined\" && process.env) {\n resolvedKey = process.env.Z3RNO_API_KEY ?? \"\";\n }\n this.apiKey = resolvedKey;\n\n this.timeout = config.timeout ?? 30000;\n this.maxRetries = config.maxRetries ?? 3;\n this.fetchImpl = config.fetch ?? globalThis.fetch;\n this.onRequest = config.onRequest;\n this.onResponse = config.onResponse;\n }\n\n // --- Store ---\n\n /**\n * Stores a new memory for an agent.\n *\n * The server generates an embedding for the content and stores it in\n * the vector database. The memory is immediately available for recall.\n *\n * @param request - The memory to store.\n * @returns The stored memory, including the server-generated ID and scores.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link ValidationError} If the request body is invalid.\n * @throws {@link Z3rnoTimeoutError} If the request times out.\n *\n * @example\n * ```ts\n * const memory = await client.store({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * content: \"User prefers dark mode\",\n * memoryType: \"semantic\",\n * metadata: { source: \"settings-page\" },\n * });\n * console.log(memory.id); // \"mem-abc123\"\n * ```\n */\n async store(request: StoreMemoryRequest): Promise<MemoryResponse> {\n const body = {\n agent_id: request.agentId,\n content: request.content,\n memory_type: request.memoryType,\n user_id: request.userId,\n metadata: request.metadata,\n relationships: request.relationships?.map((r) => ({\n target_memory_id: r.targetMemoryId,\n relationship_type: r.relationshipType,\n weight: r.weight,\n metadata: r.metadata,\n })),\n ttl_seconds: request.ttlSeconds,\n importance: request.importance,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories\", body);\n return MemorySchema.parse(resp);\n }\n\n // --- Recall ---\n\n /**\n * Recalls memories by semantic similarity to a query.\n *\n * Returns a ranked list of memories sorted by a combined relevance score\n * that factors in similarity, importance, and recency.\n *\n * @param params - Recall parameters including the query and filters.\n * @param params.agentId - UUID of the agent whose memories to search.\n * @param params.query - Natural-language query for semantic search.\n * @param params.memoryType - Filter by memory type.\n * @param params.filters - Additional metadata filters.\n * @param params.topK - Maximum results to return (default 10).\n * @param params.similarityThreshold - Minimum similarity score (default 0).\n * @returns Ranked recall results with similarity scores.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link Z3rnoTimeoutError} If the request times out.\n *\n * @example\n * ```ts\n * const results = await client.recall({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * query: \"user preferences\",\n * topK: 5,\n * similarityThreshold: 0.7,\n * });\n * for (const item of results.results) {\n * console.log(`${item.content} (score: ${item.relevance_score})`);\n * }\n * ```\n */\n async recall(params: {\n agentId: string;\n query?: string;\n memoryType?: string;\n filters?: Record<string, unknown>;\n topK?: number;\n similarityThreshold?: number;\n /**\n * Phase C: retrieval strategy. One of `AUTO | VECTOR | LEXICAL |\n * GRAPH | TRIPLET | TRACE | TEMPORAL | ASK | CYPHER`. Default\n * `\"AUTO\"` — server's LLM router picks per query.\n */\n strategy?: string;\n /**\n * Phase C: cross-encoder re-ranking. When `true`, the server\n * re-ranks the strategy's top results. Requires\n * `sentence-transformers` on the server side.\n */\n rerank?: boolean;\n }): Promise<RecallResponse> {\n const body = {\n agent_id: params.agentId,\n query: params.query,\n memory_type: params.memoryType,\n filters: params.filters,\n top_k: params.topK ?? 10,\n similarity_threshold: params.similarityThreshold ?? 0,\n // Always send strategy + rerank. Older servers silently ignore\n // unknown body fields.\n strategy: params.strategy ?? \"AUTO\",\n rerank: params.rerank ?? false,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/recall\", body);\n return RecallSchema.parse(resp);\n }\n\n // --- Forget ---\n\n /**\n * Forgets (deletes) one or more memories.\n *\n * By default, performs a soft delete (marks as deleted but retains data).\n * Set `hardDelete: true` for permanent removal. Use `cascade: true` to\n * also delete related memories in the knowledge graph.\n *\n * @param params - Forget parameters.\n * @param params.agentId - UUID of the agent that owns the memories.\n * @param params.memoryId - UUID of a single memory to delete.\n * @param params.memoryIds - UUIDs of multiple memories to delete.\n * @param params.hardDelete - Permanently delete (default false).\n * @param params.cascade - Delete related memories too (default false).\n * @param params.reason - Reason for deletion (stored in audit log).\n * @returns Summary of the deletion operation.\n * @throws {@link AuthenticationError} If the API key is invalid.\n * @throws {@link NotFoundError} If the specified memory does not exist.\n *\n * @example\n * ```ts\n * const result = await client.forget({\n * agentId: \"550e8400-e29b-41d4-a716-446655440000\",\n * memoryId: \"mem-abc123\",\n * hardDelete: true,\n * reason: \"User requested data deletion\",\n * });\n * console.log(`Deleted ${result.deleted_count} memories`);\n * ```\n */\n async forget(params: {\n agentId: string;\n memoryId?: string;\n memoryIds?: string[];\n hardDelete?: boolean;\n cascade?: boolean;\n reason?: string;\n }): Promise<ForgetResponse> {\n const body = {\n agent_id: params.agentId,\n memory_id: params.memoryId,\n memory_ids: params.memoryIds,\n hard_delete: params.hardDelete ?? false,\n cascade: params.cascade ?? false,\n reason: params.reason,\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/forget\", body);\n return ForgetSchema.parse(resp);\n }\n\n // --- Get Memory ---\n\n /**\n * Retrieves a single memory by its ID.\n *\n * @param memoryId - The unique identifier of the memory to retrieve.\n * @returns The full memory object.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const memory = await client.getMemory(\"mem-abc123\");\n * console.log(memory.content);\n * console.log(memory.importance_score);\n * ```\n */\n async getMemory(memoryId: string): Promise<MemoryResponse> {\n const resp = await this.request(\"GET\", `/v1/memories/${memoryId}`);\n return MemorySchema.parse(resp);\n }\n\n // --- Store Batch ---\n\n /**\n * Stores multiple memories in a single API call.\n *\n * More efficient than calling {@link store} in a loop. All memories are\n * processed atomically on the server.\n *\n * @param memories - Array of memories to store.\n * @returns The stored memories and a count of how many were created.\n * @throws {@link ValidationError} If any memory in the batch is invalid.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const result = await client.storeBatch([\n * { agentId: \"agent-1\", content: \"Fact one\" },\n * { agentId: \"agent-1\", content: \"Fact two\", memoryType: \"semantic\" },\n * ]);\n * console.log(`Stored ${result.stored_count} memories`);\n * ```\n */\n async storeBatch(\n memories: StoreMemoryRequest[],\n ): Promise<BatchStoreResponse> {\n const body = {\n memories: memories.map((m) => ({\n agent_id: m.agentId,\n content: m.content,\n memory_type: m.memoryType,\n metadata: m.metadata,\n importance: m.importance,\n })),\n };\n\n const resp = await this.request(\"POST\", \"/v1/memories/batch\", body);\n return BatchStoreSchema.parse(resp);\n }\n\n // --- Memory History ---\n\n /**\n * Retrieves the full version history of a memory.\n *\n * Z3rno uses temporal versioning — every update creates a new version\n * rather than overwriting. This method returns all versions ordered\n * chronologically.\n *\n * @param memoryId - The unique identifier of the memory.\n * @returns All versions of the memory with validity timestamps.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const history = await client.getMemoryHistory(\"mem-abc123\");\n * for (const version of history.versions) {\n * console.log(`${version.valid_from}: ${version.content}`);\n * }\n * ```\n */\n async getMemoryHistory(memoryId: string): Promise<MemoryHistoryResponse> {\n const resp = await this.request(\"GET\", `/v1/memories/${memoryId}/history`);\n return MemoryHistorySchema.parse(resp);\n }\n\n // --- Update Memory ---\n\n /**\n * Updates an existing memory's content, metadata, or importance.\n *\n * Creates a new temporal version of the memory. The previous version\n * remains accessible via {@link getMemoryHistory}.\n *\n * @param memoryId - The unique identifier of the memory to update.\n * @param updates - Fields to update (only provided fields are changed).\n * @param updates.content - New text content.\n * @param updates.metadata - New metadata (replaces existing metadata).\n * @param updates.importance - New importance score (0-1).\n * @returns The updated memory object.\n * @throws {@link NotFoundError} If no memory exists with the given ID.\n * @throws {@link ValidationError} If the update values are invalid.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const updated = await client.updateMemory(\"mem-abc123\", {\n * content: \"User now prefers light mode\",\n * importance: 0.9,\n * });\n * ```\n */\n async updateMemory(\n memoryId: string,\n updates: {\n content?: string;\n metadata?: Record<string, unknown>;\n importance?: number;\n },\n ): Promise<MemoryResponse> {\n const body: Record<string, unknown> = {};\n if (updates.content !== undefined) body.content = updates.content;\n if (updates.metadata !== undefined) body.metadata = updates.metadata;\n if (updates.importance !== undefined) body.importance = updates.importance;\n\n const resp = await this.request(\"PATCH\", `/v1/memories/${memoryId}`, body);\n return MemorySchema.parse(resp);\n }\n\n // --- Sessions ---\n\n /**\n * Starts a new session for grouping related memory operations.\n *\n * Sessions are useful for tracking conversation turns or task boundaries.\n * Memories created during a session are automatically associated with it.\n *\n * @param params - Session parameters.\n * @param params.agentId - UUID of the agent to start the session for.\n * @param params.sessionType - Type of session (default `\"conversation\"`).\n * @returns The created session with its ID and start time.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const session = await client.startSession({ agentId: \"agent-1\" });\n * console.log(`Session started: ${session.session_id}`);\n * // ... perform operations ...\n * await client.endSession(session.session_id);\n * ```\n */\n async startSession(params: {\n agentId: string;\n sessionType?: string;\n }): Promise<SessionResponse> {\n const body = {\n agent_id: params.agentId,\n session_type: params.sessionType ?? \"conversation\",\n };\n\n const resp = await this.request(\"POST\", \"/v1/sessions\", body);\n return SessionSchema.parse(resp);\n }\n\n /**\n * Ends an active session.\n *\n * Returns summary statistics including the session duration and the\n * number of memories created during the session.\n *\n * @param sessionId - The unique identifier of the session to end.\n * @returns Session summary with duration and memory count.\n * @throws {@link NotFoundError} If no active session exists with the given ID.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const summary = await client.endSession(\"sess-abc123\");\n * console.log(`Session lasted ${summary.duration_seconds}s, ${summary.memory_count} memories`);\n * ```\n */\n async endSession(sessionId: string): Promise<EndSessionResponse> {\n const resp = await this.request(\"POST\", `/v1/sessions/${sessionId}/end`);\n return EndSessionSchema.parse(resp);\n }\n\n // --- Audit ---\n\n /**\n * Retrieves a paginated audit log of memory operations.\n *\n * The audit log records every store, recall, forget, and update operation\n * performed by any agent. Useful for compliance, debugging, and analytics.\n *\n * @param params - Optional pagination and filter parameters.\n * @param params.agentId - Filter by agent UUID.\n * @param params.page - Page number (1-indexed).\n * @param params.pageSize - Number of entries per page.\n * @returns A page of audit log entries with pagination metadata.\n * @throws {@link AuthenticationError} If the API key is invalid.\n *\n * @example\n * ```ts\n * const page = await client.audit({ agentId: \"agent-1\", page: 1, pageSize: 20 });\n * for (const entry of page.entries) {\n * console.log(`${entry.created_at}: ${entry.operation} on ${entry.memory_id}`);\n * }\n * if (page.has_next) {\n * const nextPage = await client.audit({ agentId: \"agent-1\", page: 2 });\n * }\n * ```\n */\n async audit(params?: {\n agentId?: string;\n page?: number;\n pageSize?: number;\n }): Promise<AuditPageResponse> {\n const searchParams = new URLSearchParams();\n if (params?.agentId) searchParams.set(\"agent_id\", params.agentId);\n if (params?.page) searchParams.set(\"page\", String(params.page));\n if (params?.pageSize)\n searchParams.set(\"page_size\", String(params.pageSize));\n\n const query = searchParams.toString();\n const path = query ? `/v1/audit?${query}` : \"/v1/audit\";\n const resp = await this.request(\"GET\", path);\n return AuditPageSchema.parse(resp);\n }\n\n // --- HTTP layer ---\n\n private async request(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<unknown> {\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const url = `${this.baseUrl}${path}`;\n let init: RequestInit = {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"@z3rno/sdk/0.0.1\",\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n };\n\n if (this.onRequest) {\n init = this.onRequest(url, init);\n }\n\n let response = await this.fetchImpl(url, init);\n\n if (this.onResponse) {\n response = this.onResponse(response);\n }\n\n clearTimeout(timeoutId);\n\n // On 429, honor Retry-After header and retry\n if (response.status === 429 && attempt < this.maxRetries) {\n const retryAfter = parseInt(\n response.headers.get(\"Retry-After\") ?? \"1\",\n 10,\n );\n await this.sleep(retryAfter * 1000);\n continue;\n }\n\n // On 5xx, retry with exponential backoff\n if (response.status >= 500 && attempt < this.maxRetries) {\n const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s\n await this.sleep(delay);\n continue;\n }\n\n return this.handleResponse(response);\n } catch (error) {\n clearTimeout(timeoutId);\n\n // Do not retry Z3rnoError subclasses (4xx client errors)\n if (error instanceof Z3rnoError) throw error;\n\n // Classify the error before deciding whether to retry\n if (error instanceof DOMException && error.name === \"AbortError\") {\n lastError = new Z3rnoTimeoutError(\n `Request timed out after ${this.timeout}ms`,\n this.timeout,\n );\n } else if (error instanceof TypeError) {\n lastError = new Z3rnoConnectionError(\n `Connection failed: ${error.message}`,\n );\n } else {\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n\n if (attempt < this.maxRetries) {\n const delay = Math.pow(2, attempt) * 1000;\n await this.sleep(delay);\n continue;\n }\n }\n }\n\n // After all retries exhausted, throw the last classified error\n if (lastError instanceof Z3rnoError) {\n throw lastError;\n }\n throw new Z3rnoError(\n `Request failed after ${this.maxRetries + 1} attempts: ${String(lastError)}`,\n );\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private async handleResponse(resp: Response): Promise<unknown> {\n if (resp.ok) {\n return resp.json();\n }\n\n let detail = resp.statusText;\n try {\n const text = await resp.text();\n try {\n const body = JSON.parse(text) as Record<string, unknown>;\n detail = String(body.detail ?? body.error ?? resp.statusText);\n } catch {\n // Response is not JSON (e.g., nginx HTML 502). Include the\n // beginning of the body so users can diagnose proxy/gateway issues.\n if (text.length > 0) {\n const preview = text.length > 200 ? text.slice(0, 200) + \"...\" : text;\n detail = `${resp.statusText} — ${preview}`;\n }\n }\n } catch {\n // Could not read body at all\n }\n\n switch (resp.status) {\n case 401:\n throw new AuthenticationError(`Authentication failed: ${detail}`);\n case 404:\n throw new NotFoundError(`Not found: ${detail}`);\n case 429: {\n const retryAfter = parseInt(\n resp.headers.get(\"Retry-After\") ?? \"60\",\n 10,\n );\n throw new RateLimitError(`Rate limit exceeded: ${detail}`, retryAfter);\n }\n case 400:\n case 422:\n throw new ValidationError(detail, resp.status);\n default:\n if (resp.status >= 500) {\n throw new ServerError(`Server error: ${detail}`, resp.status);\n }\n throw new Z3rnoError(\n `Unexpected error (${resp.status}): ${detail}`,\n resp.status,\n );\n }\n }\n}\n"]}
|