xmemory 3.7.0 → 3.8.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/README.md CHANGED
@@ -8,6 +8,9 @@ TypeScript/JavaScript client library for the [xmemory](https://xmemory.ai) API.
8
8
  npm install xmemory
9
9
  ```
10
10
 
11
+ The package ships both ESM and CommonJS builds. `import` and `require` both
12
+ work, and TypeScript resolves the matching declarations either way.
13
+
11
14
  ## Quick start
12
15
 
13
16
  ```typescript
@@ -0,0 +1,369 @@
1
+ "use strict";
2
+ /**
3
+ * XmemoryClient — main entry point for the xmemory API.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.XmemoryClient = void 0;
7
+ exports.xmemoryInstance = xmemoryInstance;
8
+ const instance_js_1 = require("./instance.js");
9
+ const types_js_1 = require("./types.js");
10
+ const DEFAULT_BASE_URL = "https://api.xmemory.ai";
11
+ const DEFAULT_TIMEOUT_MS = 60_000;
12
+ const ORANGE = "\x1b[38;5;208m";
13
+ const RESET = "\x1b[0m";
14
+ function deprecationWarning(message) {
15
+ console.warn(`${ORANGE}[xmemory] DEPRECATION: ${message}${RESET}`);
16
+ }
17
+ /**
18
+ * Pull a structured error out of an error body. Handles the schema-evolution
19
+ * shape (`{status: "error", error_type, error_message, details}`, where
20
+ * `error_type` is the code) and the standard `{errors: [{code, message}]}`
21
+ * envelope.
22
+ */
23
+ function extractStructuredError(payload) {
24
+ if (typeof payload !== "object" || payload === null)
25
+ return {};
26
+ const p = payload;
27
+ if (p.status === "error" && typeof p.error_type === "string") {
28
+ return {
29
+ code: p.error_type,
30
+ message: typeof p.error_message === "string" ? p.error_message : undefined,
31
+ details: (p.details ?? null),
32
+ };
33
+ }
34
+ const errors = p.errors;
35
+ if (Array.isArray(errors) && errors.length > 0 && typeof errors[0] === "object" && errors[0] !== null) {
36
+ const first = errors[0];
37
+ return {
38
+ code: typeof first.code === "string" ? first.code : undefined,
39
+ message: typeof first.message === "string" ? first.message : undefined,
40
+ details: (first.details ?? null),
41
+ };
42
+ }
43
+ return {};
44
+ }
45
+ /**
46
+ * Parse the HTTP `Retry-After` response header into a number of seconds, or
47
+ * `undefined` when the header is absent or unparseable. Supports both the
48
+ * delta-seconds form (`Retry-After: 30`) and the HTTP-date form; HTTP-dates
49
+ * are converted to a non-negative second offset from now.
50
+ */
51
+ function parseRetryAfter(res) {
52
+ const raw = res.headers.get("Retry-After");
53
+ if (raw == null)
54
+ return undefined;
55
+ const trimmed = raw.trim();
56
+ if (trimmed === "")
57
+ return undefined;
58
+ if (/^\d+$/.test(trimmed))
59
+ return Number(trimmed);
60
+ const dateMs = Date.parse(trimmed);
61
+ if (Number.isNaN(dateMs))
62
+ return undefined;
63
+ return Math.max(0, Math.round((dateMs - Date.now()) / 1000));
64
+ }
65
+ // ---------------------------------------------------------------------------
66
+ // Client
67
+ // ---------------------------------------------------------------------------
68
+ class XmemoryClient {
69
+ _baseUrl;
70
+ _timeoutMs;
71
+ _apiKey;
72
+ admin;
73
+ constructor(options = {}) {
74
+ const env = typeof process !== "undefined" ? process.env : undefined;
75
+ this._baseUrl = (options.url ?? env?.XMEM_API_URL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
76
+ this._apiKey = XmemoryClient._resolveApiKey(options, env);
77
+ this._timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
78
+ this.admin = this._buildAdmin();
79
+ }
80
+ static _resolveApiKey(options, env) {
81
+ if (options.apiKey != null)
82
+ return options.apiKey;
83
+ if (options.token != null) {
84
+ deprecationWarning("The `token` constructor option is deprecated and will be removed soon. Use `apiKey` instead.");
85
+ return options.token;
86
+ }
87
+ if (env?.XMEM_API_KEY)
88
+ return env.XMEM_API_KEY;
89
+ if (env?.XMEM_AUTH_TOKEN) {
90
+ deprecationWarning("The `XMEM_AUTH_TOKEN` environment variable is deprecated and will be removed soon. Use `XMEM_API_KEY` instead.");
91
+ return env.XMEM_AUTH_TOKEN;
92
+ }
93
+ return undefined;
94
+ }
95
+ /** Factory that performs a health check before returning the client. */
96
+ static async create(options = {}) {
97
+ const client = new XmemoryClient(options);
98
+ await client.checkHealth();
99
+ return client;
100
+ }
101
+ /** Return an InstanceHandle scoped to the given instance ID. */
102
+ instance(instanceId) {
103
+ return new instance_js_1.InstanceHandle(instanceId, this._requestOne.bind(this));
104
+ }
105
+ /** GET /healthz — throws XmemoryHealthCheckError on failure. */
106
+ async checkHealth() {
107
+ const url = `${this._baseUrl}/healthz`;
108
+ try {
109
+ const res = await this._fetch(url, { method: "GET" }, this._timeoutMs);
110
+ if (!res.ok) {
111
+ throw new types_js_1.XmemoryHealthCheckError(`Health check failed: HTTP ${res.status} at ${url}`, res.status);
112
+ }
113
+ }
114
+ catch (err) {
115
+ if (err instanceof types_js_1.XmemoryHealthCheckError)
116
+ throw err;
117
+ throw new types_js_1.XmemoryHealthCheckError(`Health check failed: ${err instanceof Error ? err.message : String(err)}`);
118
+ }
119
+ }
120
+ // -----------------------------------------------------------------------
121
+ // Private: HTTP layer
122
+ // -----------------------------------------------------------------------
123
+ async _fetch(url, init, timeoutMs) {
124
+ const controller = new AbortController();
125
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
126
+ try {
127
+ return await fetch(url, { ...init, signal: controller.signal });
128
+ }
129
+ finally {
130
+ clearTimeout(timer);
131
+ }
132
+ }
133
+ _headers(hasBody = false) {
134
+ const h = {
135
+ Accept: "application/json",
136
+ };
137
+ if (hasBody)
138
+ h["Content-Type"] = "application/json";
139
+ if (this._apiKey)
140
+ h["Authorization"] = `Bearer ${this._apiKey}`;
141
+ return h;
142
+ }
143
+ /** Core request — returns the raw API wrapper `{ids, items, errors}`. */
144
+ async _request(method, path, options) {
145
+ let url = `${this._baseUrl}${path}`;
146
+ if (options?.params) {
147
+ const sp = new URLSearchParams();
148
+ for (const [key, val] of Object.entries(options.params)) {
149
+ if (Array.isArray(val)) {
150
+ for (const v of val)
151
+ sp.append(key, v);
152
+ }
153
+ else {
154
+ sp.append(key, val);
155
+ }
156
+ }
157
+ const qs = sp.toString();
158
+ if (qs)
159
+ url += `?${qs}`;
160
+ }
161
+ const timeoutMs = options?.timeoutMs ?? this._timeoutMs;
162
+ const hasBody = !!(options?.body && method !== "GET");
163
+ const init = { method, headers: this._headers(hasBody) };
164
+ if (hasBody) {
165
+ init.body = JSON.stringify(options.body);
166
+ }
167
+ const res = await this._fetch(url, init, timeoutMs);
168
+ const raw = await res.text();
169
+ let payload;
170
+ try {
171
+ payload = raw ? JSON.parse(raw) : {};
172
+ }
173
+ catch {
174
+ throw new types_js_1.XmemoryAPIError(`Invalid JSON from server (${res.status}): ${raw.slice(0, 200)}`, res.status);
175
+ }
176
+ if (!res.ok) {
177
+ const structured = extractStructuredError(payload);
178
+ const msg = structured.message ??
179
+ (typeof payload === "object" && payload !== null && "message" in payload
180
+ ? String(payload.message)
181
+ : raw.slice(0, 200));
182
+ throw new types_js_1.XmemoryAPIError(`HTTP ${res.status}: ${msg}`, res.status, structured.code, structured.details, parseRetryAfter(res));
183
+ }
184
+ const response = payload;
185
+ if (response.errors?.length) {
186
+ const first = response.errors[0];
187
+ throw new types_js_1.XmemoryAPIError(`API error: ${first.message} (${first.code})`, res.status, first.code);
188
+ }
189
+ return response;
190
+ }
191
+ async _requestOne(method, path, options) {
192
+ const response = await this._request(method, path, options);
193
+ const items = response.items ?? [];
194
+ if (items.length === 0) {
195
+ throw new types_js_1.XmemoryAPIError(`Expected one item from ${method} ${path}, got none`);
196
+ }
197
+ if (items.length > 1) {
198
+ throw new types_js_1.XmemoryAPIError(`Expected one item from ${method} ${path}, got ${items.length}`);
199
+ }
200
+ return items[0];
201
+ }
202
+ async _requestList(method, path, options) {
203
+ const response = await this._request(method, path, options);
204
+ return (response.items ?? []);
205
+ }
206
+ async _requestIds(method, path, options) {
207
+ const response = await this._request(method, path, options);
208
+ return response.ids ?? [];
209
+ }
210
+ // -----------------------------------------------------------------------
211
+ // Private: build admin namespace
212
+ // -----------------------------------------------------------------------
213
+ _buildAdmin() {
214
+ return {
215
+ listClusters: async (options) => {
216
+ const params = options?.ids ? { ids: options.ids } : undefined;
217
+ return this._requestList("GET", "/clusters", { params, timeoutMs: options?.timeoutMs });
218
+ },
219
+ getCluster: async (clusterId, options) => {
220
+ return this._requestOne("GET", `/clusters/${clusterId}`, {
221
+ timeoutMs: options?.timeoutMs,
222
+ });
223
+ },
224
+ createInstance: async (clusterId, name, schemaText, schemaType, options) => {
225
+ const body = {
226
+ name,
227
+ instance_schema: (0, types_js_1.buildInstanceSchema)(schemaText, schemaType),
228
+ };
229
+ if (options?.description != null)
230
+ body.description = options.description;
231
+ if (options?.schemaDescription != null)
232
+ body.schema_description = options.schemaDescription;
233
+ const info = await this._requestOne("POST", `/clusters/${clusterId}/instances`, {
234
+ body,
235
+ timeoutMs: options?.timeoutMs,
236
+ });
237
+ return this.instance(info.id);
238
+ },
239
+ listInstances: async (options) => {
240
+ const params = options?.ids ? { ids: options.ids } : undefined;
241
+ return this._requestList("GET", "/instances", { params, timeoutMs: options?.timeoutMs });
242
+ },
243
+ getInstance: async (instanceId, options) => {
244
+ return this._requestOne("GET", `/instances/${instanceId}`, {
245
+ timeoutMs: options?.timeoutMs,
246
+ });
247
+ },
248
+ getSetupInstructions: async (instanceId, options) => {
249
+ return this._requestOne("GET", `/instances/${instanceId}/agent_setup`, {
250
+ params: { format: options?.format ?? types_js_1.SetupFormat.AGENT },
251
+ timeoutMs: options?.timeoutMs,
252
+ });
253
+ },
254
+ deleteInstance: async (instanceId, options) => {
255
+ return this._requestIds("DELETE", `/instances/${instanceId}`, {
256
+ timeoutMs: options?.timeoutMs,
257
+ });
258
+ },
259
+ getInstanceSchema: async (instanceId, options) => {
260
+ return this._requestOne("GET", `/instances/${instanceId}/schema`, {
261
+ timeoutMs: options?.timeoutMs,
262
+ });
263
+ },
264
+ updateInstanceSchema: async (instanceId, schemaText, schemaType, options) => {
265
+ const body = {
266
+ instance_schema: (0, types_js_1.buildInstanceSchema)(schemaText, schemaType),
267
+ };
268
+ if (options?.migrationPlan != null)
269
+ body.migration_plan = options.migrationPlan;
270
+ if (options?.confirmDestructive != null)
271
+ body.confirm_destructive = options.confirmDestructive;
272
+ return this._requestOne("PUT", `/instances/${instanceId}/schema`, {
273
+ body,
274
+ timeoutMs: options?.timeoutMs,
275
+ });
276
+ },
277
+ updateInstanceMetadata: async (instanceId, name, description, options) => {
278
+ // Only the fields the caller named are sent. The endpoint treats a field
279
+ // present in the body as a field to set, so serializing
280
+ // `agent_owner_instructions` unasked would wipe an owner's standing rule
281
+ // as a side effect of a rename.
282
+ const body = { name, description };
283
+ if (options?.agentOwnerInstructions !== undefined) {
284
+ body.agent_owner_instructions = options.agentOwnerInstructions;
285
+ }
286
+ if (options?.expectedOwnerInstructionsEpoch !== undefined) {
287
+ body.expected_owner_instructions_epoch = options.expectedOwnerInstructionsEpoch;
288
+ }
289
+ return this._requestOne("PUT", `/instances/${instanceId}`, {
290
+ body,
291
+ timeoutMs: options?.timeoutMs,
292
+ });
293
+ },
294
+ patchInstanceMetadata: async (instanceId, options) => {
295
+ // Same rule as above, applied to every field: absent means "leave it as
296
+ // it is", an explicit null means "clear it".
297
+ const body = {};
298
+ if (options?.name !== undefined)
299
+ body.name = options.name;
300
+ if (options?.description !== undefined)
301
+ body.description = options.description;
302
+ if (options?.agentSurfaces !== undefined) {
303
+ // Copied so a caller mutating their array afterwards cannot change what
304
+ // a retry sends.
305
+ body.agent_surfaces = options.agentSurfaces && [...options.agentSurfaces];
306
+ }
307
+ if (options?.agentDefaultBindingTier !== undefined) {
308
+ body.agent_default_binding_tier = options.agentDefaultBindingTier;
309
+ }
310
+ if (options?.agentEngagementHints !== undefined) {
311
+ body.agent_engagement_hints = options.agentEngagementHints && [...options.agentEngagementHints];
312
+ }
313
+ if (options?.agentOwnerInstructions !== undefined) {
314
+ body.agent_owner_instructions = options.agentOwnerInstructions;
315
+ }
316
+ return this._requestOne("PATCH", `/instances/${instanceId}`, {
317
+ body,
318
+ timeoutMs: options?.timeoutMs,
319
+ });
320
+ },
321
+ generateSchema: async (clusterId, schemaDescription, options) => {
322
+ const body = { schema_description: schemaDescription };
323
+ if (options?.currentYmlSchema != null)
324
+ body.current_yml_schema = options.currentYmlSchema;
325
+ return this._requestOne("POST", `/clusters/${clusterId}/instances/generate_schema`, { body, timeoutMs: options?.timeoutMs });
326
+ },
327
+ enhanceSchema: async (clusterId, schemaDescription, currentYmlSchema, options) => {
328
+ return this._requestOne("POST", `/clusters/${clusterId}/instances/generate_schema`, {
329
+ body: { schema_description: schemaDescription, current_yml_schema: currentYmlSchema },
330
+ timeoutMs: options?.timeoutMs,
331
+ });
332
+ },
333
+ dryRunMigration: async (instanceId, schemaText, schemaType, options) => {
334
+ const body = {
335
+ instance_schema: (0, types_js_1.buildInstanceSchema)(schemaText, schemaType),
336
+ };
337
+ if (options?.migrationPlan != null)
338
+ body.migration_plan = options.migrationPlan;
339
+ if (options?.confirmDestructive != null)
340
+ body.confirm_destructive = options.confirmDestructive;
341
+ return this._requestOne("POST", `/instances/${instanceId}/migrations/dry_run`, {
342
+ body,
343
+ timeoutMs: options?.timeoutMs,
344
+ });
345
+ },
346
+ listMigrations: async (instanceId, options) => {
347
+ const params = {
348
+ limit: String(options?.limit ?? 50),
349
+ include_yaml: String(options?.includeYaml ?? false),
350
+ };
351
+ if (options?.beforeId != null)
352
+ params.before_id = options.beforeId;
353
+ return this._requestOne("GET", `/instances/${instanceId}/migrations`, {
354
+ params,
355
+ timeoutMs: options?.timeoutMs,
356
+ });
357
+ },
358
+ getMigration: async (instanceId, migrationId, options) => {
359
+ const result = await this._requestOne("GET", `/instances/${instanceId}/migrations/${migrationId}`, { params: { include_yaml: String(options?.includeYaml ?? false) }, timeoutMs: options?.timeoutMs });
360
+ return result.record;
361
+ },
362
+ };
363
+ }
364
+ }
365
+ exports.XmemoryClient = XmemoryClient;
366
+ /** Convenience factory — creates a client with a health check. */
367
+ async function xmemoryInstance(options = {}) {
368
+ return XmemoryClient.create(options);
369
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ /**
3
+ * xmemory — TypeScript client for the xmemory API.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.StepKind = exports.SetupFormat = exports.FragmentMerge = exports.BindingTier = exports.AgentSurface = exports.SchemaType = exports.XmemoryHealthCheckError = exports.XmemoryAPIError = exports.InstanceHandle = exports.DescribeResult = exports.xmemoryInstance = exports.XmemoryClient = void 0;
7
+ // Client
8
+ var client_js_1 = require("./client.js");
9
+ Object.defineProperty(exports, "XmemoryClient", { enumerable: true, get: function () { return client_js_1.XmemoryClient; } });
10
+ Object.defineProperty(exports, "xmemoryInstance", { enumerable: true, get: function () { return client_js_1.xmemoryInstance; } });
11
+ // Instance handle
12
+ var instance_js_1 = require("./instance.js");
13
+ Object.defineProperty(exports, "DescribeResult", { enumerable: true, get: function () { return instance_js_1.DescribeResult; } });
14
+ Object.defineProperty(exports, "InstanceHandle", { enumerable: true, get: function () { return instance_js_1.InstanceHandle; } });
15
+ // Error classes
16
+ var types_js_1 = require("./types.js");
17
+ Object.defineProperty(exports, "XmemoryAPIError", { enumerable: true, get: function () { return types_js_1.XmemoryAPIError; } });
18
+ Object.defineProperty(exports, "XmemoryHealthCheckError", { enumerable: true, get: function () { return types_js_1.XmemoryHealthCheckError; } });
19
+ // Enums
20
+ var types_js_2 = require("./types.js");
21
+ Object.defineProperty(exports, "SchemaType", { enumerable: true, get: function () { return types_js_2.SchemaType; } });
22
+ var types_js_3 = require("./types.js");
23
+ Object.defineProperty(exports, "AgentSurface", { enumerable: true, get: function () { return types_js_3.AgentSurface; } });
24
+ Object.defineProperty(exports, "BindingTier", { enumerable: true, get: function () { return types_js_3.BindingTier; } });
25
+ Object.defineProperty(exports, "FragmentMerge", { enumerable: true, get: function () { return types_js_3.FragmentMerge; } });
26
+ Object.defineProperty(exports, "SetupFormat", { enumerable: true, get: function () { return types_js_3.SetupFormat; } });
27
+ Object.defineProperty(exports, "StepKind", { enumerable: true, get: function () { return types_js_3.StepKind; } });