@z3rno/sdk 0.3.0 → 0.4.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 +144 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +260 -1
- package/dist/index.d.ts +260 -1
- package/dist/index.js +139 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -343,6 +343,84 @@ var EndSessionResponse = zod.z.object({
|
|
|
343
343
|
/** Number of memories created during the session. */
|
|
344
344
|
memory_count: zod.z.number()
|
|
345
345
|
});
|
|
346
|
+
var IngestJobResponse = zod.z.object({
|
|
347
|
+
job_id: zod.z.string(),
|
|
348
|
+
kind: zod.z.string(),
|
|
349
|
+
status: zod.z.string(),
|
|
350
|
+
dataset_id: zod.z.string().nullable().optional(),
|
|
351
|
+
enqueued_at: zod.z.string()
|
|
352
|
+
});
|
|
353
|
+
var IngestJobStatusResponse = zod.z.object({
|
|
354
|
+
job_id: zod.z.string(),
|
|
355
|
+
agent_id: zod.z.string(),
|
|
356
|
+
dataset_id: zod.z.string().nullable().optional(),
|
|
357
|
+
kind: zod.z.string(),
|
|
358
|
+
status: zod.z.string(),
|
|
359
|
+
source_uri: zod.z.string().nullable().optional(),
|
|
360
|
+
content_type: zod.z.string().nullable().optional(),
|
|
361
|
+
filename: zod.z.string().nullable().optional(),
|
|
362
|
+
file_size: zod.z.number().nullable().optional(),
|
|
363
|
+
memory_ids: zod.z.array(zod.z.string()).default([]),
|
|
364
|
+
memos_written: zod.z.number().default(0),
|
|
365
|
+
distill_job_id: zod.z.string().nullable().optional(),
|
|
366
|
+
codegraph_memos_written: zod.z.number().default(0),
|
|
367
|
+
codegraph_edges_written: zod.z.number().default(0),
|
|
368
|
+
error: zod.z.string().nullable().optional(),
|
|
369
|
+
warnings: zod.z.array(zod.z.record(zod.z.unknown())).default([]),
|
|
370
|
+
started_at: zod.z.string().nullable().optional(),
|
|
371
|
+
completed_at: zod.z.string().nullable().optional(),
|
|
372
|
+
created_at: zod.z.string().nullable().optional(),
|
|
373
|
+
updated_at: zod.z.string().nullable().optional()
|
|
374
|
+
});
|
|
375
|
+
var DistillJobResponse = zod.z.object({
|
|
376
|
+
job_id: zod.z.string(),
|
|
377
|
+
status: zod.z.string(),
|
|
378
|
+
memory_ids: zod.z.array(zod.z.string()),
|
|
379
|
+
enqueued_at: zod.z.string()
|
|
380
|
+
});
|
|
381
|
+
var DistillJobStatusResponse = zod.z.object({
|
|
382
|
+
job_id: zod.z.string(),
|
|
383
|
+
agent_id: zod.z.string(),
|
|
384
|
+
status: zod.z.string(),
|
|
385
|
+
model: zod.z.string(),
|
|
386
|
+
memory_ids: zod.z.array(zod.z.string()),
|
|
387
|
+
chunk_size: zod.z.number(),
|
|
388
|
+
chunk_overlap: zod.z.number(),
|
|
389
|
+
max_concurrency: zod.z.number(),
|
|
390
|
+
chunks_total: zod.z.number(),
|
|
391
|
+
chunks_failed: zod.z.number(),
|
|
392
|
+
entities_extracted: zod.z.number(),
|
|
393
|
+
relationships_extracted: zod.z.number(),
|
|
394
|
+
memos_written: zod.z.number(),
|
|
395
|
+
error: zod.z.string().nullable().optional(),
|
|
396
|
+
started_at: zod.z.string().nullable().optional(),
|
|
397
|
+
completed_at: zod.z.string().nullable().optional(),
|
|
398
|
+
created_at: zod.z.string().nullable().optional(),
|
|
399
|
+
updated_at: zod.z.string().nullable().optional()
|
|
400
|
+
});
|
|
401
|
+
var RefineJobResponse = zod.z.object({
|
|
402
|
+
job_id: zod.z.string(),
|
|
403
|
+
status: zod.z.string(),
|
|
404
|
+
dataset_id: zod.z.string().nullable().optional(),
|
|
405
|
+
enqueued_at: zod.z.string()
|
|
406
|
+
});
|
|
407
|
+
var RefineJobStatusResponse = zod.z.object({
|
|
408
|
+
job_id: zod.z.string(),
|
|
409
|
+
status: zod.z.string(),
|
|
410
|
+
dataset_id: zod.z.string().nullable().optional(),
|
|
411
|
+
trigger: zod.z.string(),
|
|
412
|
+
memos_scanned: zod.z.number().default(0),
|
|
413
|
+
memos_deduped: zod.z.number().default(0),
|
|
414
|
+
edges_reweighted: zod.z.number().default(0),
|
|
415
|
+
edges_pruned: zod.z.number().default(0),
|
|
416
|
+
feedback_drained: zod.z.number().default(0),
|
|
417
|
+
job_metadata: zod.z.record(zod.z.unknown()).default({}),
|
|
418
|
+
error: zod.z.string().nullable().optional(),
|
|
419
|
+
started_at: zod.z.string().nullable().optional(),
|
|
420
|
+
completed_at: zod.z.string().nullable().optional(),
|
|
421
|
+
created_at: zod.z.string().nullable().optional(),
|
|
422
|
+
updated_at: zod.z.string().nullable().optional()
|
|
423
|
+
});
|
|
346
424
|
|
|
347
425
|
// src/client.ts
|
|
348
426
|
var Z3rnoClient = class {
|
|
@@ -722,6 +800,66 @@ var Z3rnoClient = class {
|
|
|
722
800
|
const resp = await this.request("GET", path);
|
|
723
801
|
return AuditPageResponse.parse(resp);
|
|
724
802
|
}
|
|
803
|
+
// --- Forge: ingest / distill / refine -------------------------------
|
|
804
|
+
//
|
|
805
|
+
// Wrap the server's POST /v1/ingest, /v1/distill, /v1/refine plus the
|
|
806
|
+
// matching GET status endpoints. The server gates each verb behind an
|
|
807
|
+
// operator flag (INGEST_ENABLED / DISTILL_ENABLED / REFINE_ENABLED);
|
|
808
|
+
// when off, these methods throw NotFoundError.
|
|
809
|
+
async ingestText(params) {
|
|
810
|
+
const body = {
|
|
811
|
+
kind: "text",
|
|
812
|
+
agent_id: params.agentId,
|
|
813
|
+
text: params.text
|
|
814
|
+
};
|
|
815
|
+
if (params.datasetId) body.dataset_id = params.datasetId;
|
|
816
|
+
const resp = await this.request("POST", "/v1/ingest", body);
|
|
817
|
+
return IngestJobResponse.parse(resp);
|
|
818
|
+
}
|
|
819
|
+
async ingestUrl(params) {
|
|
820
|
+
const body = {
|
|
821
|
+
kind: "url",
|
|
822
|
+
agent_id: params.agentId,
|
|
823
|
+
url: params.url
|
|
824
|
+
};
|
|
825
|
+
if (params.datasetId) body.dataset_id = params.datasetId;
|
|
826
|
+
const resp = await this.request("POST", "/v1/ingest", body);
|
|
827
|
+
return IngestJobResponse.parse(resp);
|
|
828
|
+
}
|
|
829
|
+
async getIngestStatus(jobId) {
|
|
830
|
+
const resp = await this.request("GET", `/v1/ingest/${jobId}`);
|
|
831
|
+
return IngestJobStatusResponse.parse(resp);
|
|
832
|
+
}
|
|
833
|
+
async distill(params) {
|
|
834
|
+
const body = {
|
|
835
|
+
agent_id: params.agentId,
|
|
836
|
+
memory_ids: params.memoryIds,
|
|
837
|
+
include_summary: params.includeSummary ?? true
|
|
838
|
+
};
|
|
839
|
+
if (params.chunkSize !== void 0) body.chunk_size = params.chunkSize;
|
|
840
|
+
if (params.chunkOverlap !== void 0)
|
|
841
|
+
body.chunk_overlap = params.chunkOverlap;
|
|
842
|
+
if (params.maxConcurrency !== void 0)
|
|
843
|
+
body.max_concurrency = params.maxConcurrency;
|
|
844
|
+
if (params.summaryStyle !== void 0)
|
|
845
|
+
body.summary_style = params.summaryStyle;
|
|
846
|
+
const resp = await this.request("POST", "/v1/distill", body);
|
|
847
|
+
return DistillJobResponse.parse(resp);
|
|
848
|
+
}
|
|
849
|
+
async getDistillStatus(jobId) {
|
|
850
|
+
const resp = await this.request("GET", `/v1/distill/${jobId}`);
|
|
851
|
+
return DistillJobStatusResponse.parse(resp);
|
|
852
|
+
}
|
|
853
|
+
async refine(params) {
|
|
854
|
+
const body = {};
|
|
855
|
+
if (params?.datasetId) body.dataset_id = params.datasetId;
|
|
856
|
+
const resp = await this.request("POST", "/v1/refine", body);
|
|
857
|
+
return RefineJobResponse.parse(resp);
|
|
858
|
+
}
|
|
859
|
+
async getRefineStatus(jobId) {
|
|
860
|
+
const resp = await this.request("GET", `/v1/refine/${jobId}`);
|
|
861
|
+
return RefineJobStatusResponse.parse(resp);
|
|
862
|
+
}
|
|
725
863
|
// --- HTTP layer ---
|
|
726
864
|
async request(method, path, body) {
|
|
727
865
|
let lastError;
|
|
@@ -843,8 +981,12 @@ exports.AuditEntry = AuditEntry;
|
|
|
843
981
|
exports.AuditPageResponse = AuditPageResponse;
|
|
844
982
|
exports.AuthenticationError = AuthenticationError;
|
|
845
983
|
exports.BatchStoreResponse = BatchStoreResponse;
|
|
984
|
+
exports.DistillJobResponse = DistillJobResponse;
|
|
985
|
+
exports.DistillJobStatusResponse = DistillJobStatusResponse;
|
|
846
986
|
exports.EndSessionResponse = EndSessionResponse;
|
|
847
987
|
exports.ForgetResponse = ForgetResponse;
|
|
988
|
+
exports.IngestJobResponse = IngestJobResponse;
|
|
989
|
+
exports.IngestJobStatusResponse = IngestJobStatusResponse;
|
|
848
990
|
exports.MemoryHistoryResponse = MemoryHistoryResponse;
|
|
849
991
|
exports.MemoryResponse = MemoryResponse;
|
|
850
992
|
exports.MemoryType = MemoryType;
|
|
@@ -853,6 +995,8 @@ exports.NotFoundError = NotFoundError;
|
|
|
853
995
|
exports.RateLimitError = RateLimitError;
|
|
854
996
|
exports.RecallResponse = RecallResponse;
|
|
855
997
|
exports.RecallResultItem = RecallResultItem;
|
|
998
|
+
exports.RefineJobResponse = RefineJobResponse;
|
|
999
|
+
exports.RefineJobStatusResponse = RefineJobStatusResponse;
|
|
856
1000
|
exports.RelationshipType = RelationshipType;
|
|
857
1001
|
exports.RetrievalStrategy = RetrievalStrategy;
|
|
858
1002
|
exports.ServerError = ServerError;
|
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,U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AAA,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"]}
|
|
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,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A,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// ---------------------------------------------------------------------------\n// Forge verbs — ingest / distill / refine (Phase A / B / D)\n// ---------------------------------------------------------------------------\n\n/** Response to POST /v1/ingest — the enqueue ack. */\nexport const IngestJobResponse = z.object({\n job_id: z.string(),\n kind: z.string(),\n status: z.string(),\n dataset_id: z.string().nullable().optional(),\n enqueued_at: z.string(),\n});\n\nexport type IngestJobResponse = z.infer<typeof IngestJobResponse>;\n\n/** Full state from GET /v1/ingest/{job_id}. */\nexport const IngestJobStatusResponse = z.object({\n job_id: z.string(),\n agent_id: z.string(),\n dataset_id: z.string().nullable().optional(),\n kind: z.string(),\n status: z.string(),\n source_uri: z.string().nullable().optional(),\n content_type: z.string().nullable().optional(),\n filename: z.string().nullable().optional(),\n file_size: z.number().nullable().optional(),\n memory_ids: z.array(z.string()).default([]),\n memos_written: z.number().default(0),\n distill_job_id: z.string().nullable().optional(),\n codegraph_memos_written: z.number().default(0),\n codegraph_edges_written: z.number().default(0),\n error: z.string().nullable().optional(),\n warnings: z.array(z.record(z.unknown())).default([]),\n started_at: z.string().nullable().optional(),\n completed_at: z.string().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n});\n\nexport type IngestJobStatusResponse = z.infer<typeof IngestJobStatusResponse>;\n\n/** Distill enqueue ack. */\nexport const DistillJobResponse = z.object({\n job_id: z.string(),\n status: z.string(),\n memory_ids: z.array(z.string()),\n enqueued_at: z.string(),\n});\n\nexport type DistillJobResponse = z.infer<typeof DistillJobResponse>;\n\n/** Full distill job state. */\nexport const DistillJobStatusResponse = z.object({\n job_id: z.string(),\n agent_id: z.string(),\n status: z.string(),\n model: z.string(),\n memory_ids: z.array(z.string()),\n chunk_size: z.number(),\n chunk_overlap: z.number(),\n max_concurrency: z.number(),\n chunks_total: z.number(),\n chunks_failed: z.number(),\n entities_extracted: z.number(),\n relationships_extracted: z.number(),\n memos_written: z.number(),\n error: z.string().nullable().optional(),\n started_at: z.string().nullable().optional(),\n completed_at: z.string().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n});\n\nexport type DistillJobStatusResponse = z.infer<typeof DistillJobStatusResponse>;\n\n/** Refine enqueue ack. */\nexport const RefineJobResponse = z.object({\n job_id: z.string(),\n status: z.string(),\n dataset_id: z.string().nullable().optional(),\n enqueued_at: z.string(),\n});\n\nexport type RefineJobResponse = z.infer<typeof RefineJobResponse>;\n\n/** Full refine job state. */\nexport const RefineJobStatusResponse = z.object({\n job_id: z.string(),\n status: z.string(),\n dataset_id: z.string().nullable().optional(),\n trigger: z.string(),\n memos_scanned: z.number().default(0),\n memos_deduped: z.number().default(0),\n edges_reweighted: z.number().default(0),\n edges_pruned: z.number().default(0),\n feedback_drained: z.number().default(0),\n job_metadata: z.record(z.unknown()).default({}),\n error: z.string().nullable().optional(),\n started_at: z.string().nullable().optional(),\n completed_at: z.string().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n});\n\nexport type RefineJobStatusResponse = z.infer<typeof RefineJobStatusResponse>;\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 DistillJobResponse,\n DistillJobStatusResponse,\n EndSessionResponse,\n ForgetResponse,\n IngestJobResponse,\n IngestJobStatusResponse,\n MemoryHistoryResponse,\n MemoryResponse,\n RecallResponse,\n RefineJobResponse,\n RefineJobStatusResponse,\n SessionResponse,\n StoreMemoryRequest,\n} from \"./models.js\";\nimport {\n AuditPageResponse as AuditPageSchema,\n BatchStoreResponse as BatchStoreSchema,\n DistillJobResponse as DistillJobSchema,\n DistillJobStatusResponse as DistillJobStatusSchema,\n EndSessionResponse as EndSessionSchema,\n ForgetResponse as ForgetSchema,\n IngestJobResponse as IngestJobSchema,\n IngestJobStatusResponse as IngestJobStatusSchema,\n MemoryHistoryResponse as MemoryHistorySchema,\n MemoryResponse as MemorySchema,\n RecallResponse as RecallSchema,\n RefineJobResponse as RefineJobSchema,\n RefineJobStatusResponse as RefineJobStatusSchema,\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 // --- Forge: ingest / distill / refine -------------------------------\n //\n // Wrap the server's POST /v1/ingest, /v1/distill, /v1/refine plus the\n // matching GET status endpoints. The server gates each verb behind an\n // operator flag (INGEST_ENABLED / DISTILL_ENABLED / REFINE_ENABLED);\n // when off, these methods throw NotFoundError.\n\n async ingestText(params: {\n agentId: string;\n text: string;\n datasetId?: string;\n }): Promise<IngestJobResponse> {\n const body: Record<string, unknown> = {\n kind: \"text\",\n agent_id: params.agentId,\n text: params.text,\n };\n if (params.datasetId) body.dataset_id = params.datasetId;\n const resp = await this.request(\"POST\", \"/v1/ingest\", body);\n return IngestJobSchema.parse(resp);\n }\n\n async ingestUrl(params: {\n agentId: string;\n url: string;\n datasetId?: string;\n }): Promise<IngestJobResponse> {\n const body: Record<string, unknown> = {\n kind: \"url\",\n agent_id: params.agentId,\n url: params.url,\n };\n if (params.datasetId) body.dataset_id = params.datasetId;\n const resp = await this.request(\"POST\", \"/v1/ingest\", body);\n return IngestJobSchema.parse(resp);\n }\n\n async getIngestStatus(jobId: string): Promise<IngestJobStatusResponse> {\n const resp = await this.request(\"GET\", `/v1/ingest/${jobId}`);\n return IngestJobStatusSchema.parse(resp);\n }\n\n async distill(params: {\n agentId: string;\n memoryIds: string[];\n chunkSize?: number;\n chunkOverlap?: number;\n maxConcurrency?: number;\n summaryStyle?: string;\n includeSummary?: boolean;\n }): Promise<DistillJobResponse> {\n const body: Record<string, unknown> = {\n agent_id: params.agentId,\n memory_ids: params.memoryIds,\n include_summary: params.includeSummary ?? true,\n };\n if (params.chunkSize !== undefined) body.chunk_size = params.chunkSize;\n if (params.chunkOverlap !== undefined)\n body.chunk_overlap = params.chunkOverlap;\n if (params.maxConcurrency !== undefined)\n body.max_concurrency = params.maxConcurrency;\n if (params.summaryStyle !== undefined)\n body.summary_style = params.summaryStyle;\n const resp = await this.request(\"POST\", \"/v1/distill\", body);\n return DistillJobSchema.parse(resp);\n }\n\n async getDistillStatus(jobId: string): Promise<DistillJobStatusResponse> {\n const resp = await this.request(\"GET\", `/v1/distill/${jobId}`);\n return DistillJobStatusSchema.parse(resp);\n }\n\n async refine(params?: { datasetId?: string }): Promise<RefineJobResponse> {\n const body: Record<string, unknown> = {};\n if (params?.datasetId) body.dataset_id = params.datasetId;\n const resp = await this.request(\"POST\", \"/v1/refine\", body);\n return RefineJobSchema.parse(resp);\n }\n\n async getRefineStatus(jobId: string): Promise<RefineJobStatusResponse> {\n const resp = await this.request(\"GET\", `/v1/refine/${jobId}`);\n return RefineJobStatusSchema.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"]}
|