xmemory 3.0.0 → 3.2.1

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
@@ -1,6 +1,6 @@
1
1
  # xmemory
2
2
 
3
- TypeScript/JavaScript client library for the [Xmemory](https://xmemory.ai) API.
3
+ TypeScript/JavaScript client library for the [xmemory](https://xmemory.ai) API.
4
4
 
5
5
  ## Installation
6
6
 
@@ -30,7 +30,7 @@ console.log(result.reader_result);
30
30
 
31
31
  | Parameter | Env var | Default | Description |
32
32
  |-------------|------------------|---------------------------|-----------------------------------------|
33
- | `url` | `XMEM_API_URL` | `https://api.xmemory.ai` | Base URL of the Xmemory API |
33
+ | `url` | `XMEM_API_URL` | `https://api.xmemory.ai` | Base URL of the xmemory API |
34
34
  | `apiKey` | `XMEM_API_KEY` | `undefined` | Bearer API key for authentication |
35
35
  | `timeoutMs` | — | `60000` | Default request timeout in milliseconds |
36
36
 
@@ -155,6 +155,24 @@ console.log(result.reader_result);
155
155
 
156
156
  Options: `{ readMode?, scope?, traceId?, timeoutMs? }` — `readMode` defaults to `"single-answer"`.
157
157
 
158
+ #### Composite queries
159
+
160
+ When a query bundles several independent questions, the server may decompose it
161
+ into sub-queries and answer each one. `reader_result` is still the combined
162
+ answer (for `"single-answer"` mode, a labelled multi-part string); `reader_results`
163
+ holds one `TaggedReaderResult` (`{ sub_query, reader_result, error }`) per
164
+ sub-query so you can read each answer unambiguously — a single-intent query
165
+ decomposes to one entry. `reader_results` is always an array: a server without
166
+ question decomposition omits the field on the wire and the client normalizes it
167
+ to `[]`, so it is empty regardless of how many questions the query held.
168
+
169
+ ```typescript
170
+ const result = await inst.read("Who leads sales, and where is HQ?");
171
+ for (const part of result.reader_results) {
172
+ console.log(part.sub_query, "→", part.error ?? part.reader_result);
173
+ }
174
+ ```
175
+
158
176
  #### Scoped reads
159
177
 
160
178
  By default a read may draw on the whole instance. Pass a `scope` to restrict it
@@ -339,9 +357,48 @@ try {
339
357
  ```
340
358
 
341
359
  `XmemoryAPIError` carries `status` (HTTP status), `code` (structured error code,
342
- when the server returned one), and `details`. The schema-evolution endpoints
343
- return codes you can pattern match on via `.code` — for example
344
- `stale_proposal_version`, `dependency_closure_failed`,
360
+ when the server returned one), `details` (an optional structured payload), and
361
+ `retryAfter` (the `Retry-After` header in seconds, when the server sent one).
362
+
363
+ **Branch on `code`, not on the bare HTTP status** — the same status can mean
364
+ different things:
365
+
366
+ | HTTP | `code` | Meaning | Retryable? |
367
+ | ---- | ----------------- | ---------------------------------------------------- | ---------------------------------- |
368
+ | 402 | `QUOTA_EXCEEDED` | Tenant exhausted its plan/usage allowance (a daily or monthly token quota). | **No.** Wait for the window to reset. |
369
+ | 429 | `RATE_LIMITED` | Genuine velocity / rate limit. | **Yes**, with backoff. |
370
+
371
+ For `QUOTA_EXCEEDED`, `details` carries `kind`
372
+ (`"daily_quota_exceeded"` | `"monthly_quota_exceeded"`) and
373
+ `retry_after_seconds` (`number | null`); when the window is resettable the
374
+ server also sends a `Retry-After` header, surfaced as `retryAfter` (seconds).
375
+ `RATE_LIMITED` is retryable — honour `retryAfter` (or `Retry-After`) for backoff.
376
+ The client never retries on its own; it only surfaces the value.
377
+
378
+ ```typescript
379
+ try {
380
+ await inst.write("...");
381
+ } catch (e) {
382
+ if (!(e instanceof XmemoryAPIError)) throw e;
383
+ switch (e.code) {
384
+ case "QUOTA_EXCEEDED": {
385
+ // Non-retryable: plan/usage allowance exhausted.
386
+ const kind = (e.details as { kind?: string } | null)?.kind; // daily_ | monthly_quota_exceeded
387
+ console.error(`Quota exhausted (${kind}); resets in ${e.retryAfter ?? "?"}s`);
388
+ break;
389
+ }
390
+ case "RATE_LIMITED":
391
+ // Retryable: back off and retry, honouring Retry-After.
392
+ console.error(`Rate limited; retry after ${e.retryAfter ?? "a short delay"}s`);
393
+ break;
394
+ default:
395
+ console.error(`API error (HTTP ${e.status}, code ${e.code}): ${e.message}`);
396
+ }
397
+ }
398
+ ```
399
+
400
+ The schema-evolution endpoints return codes you can pattern match on via `.code`
401
+ the same way — for example `stale_proposal_version`, `dependency_closure_failed`,
345
402
  `destructive_confirmation_required`, `non_additive_change_requires_plan`,
346
403
  `stale_schema_version`, `migration_not_found`, `instance_not_initialised`:
347
404
 
package/dist/client.js CHANGED
@@ -33,10 +33,31 @@ function extractStructuredError(payload) {
33
33
  return {
34
34
  code: typeof first.code === "string" ? first.code : undefined,
35
35
  message: typeof first.message === "string" ? first.message : undefined,
36
+ details: (first.details ?? null),
36
37
  };
37
38
  }
38
39
  return {};
39
40
  }
41
+ /**
42
+ * Parse the HTTP `Retry-After` response header into a number of seconds, or
43
+ * `undefined` when the header is absent or unparseable. Supports both the
44
+ * delta-seconds form (`Retry-After: 30`) and the HTTP-date form; HTTP-dates
45
+ * are converted to a non-negative second offset from now.
46
+ */
47
+ function parseRetryAfter(res) {
48
+ const raw = res.headers.get("Retry-After");
49
+ if (raw == null)
50
+ return undefined;
51
+ const trimmed = raw.trim();
52
+ if (trimmed === "")
53
+ return undefined;
54
+ if (/^\d+$/.test(trimmed))
55
+ return Number(trimmed);
56
+ const dateMs = Date.parse(trimmed);
57
+ if (Number.isNaN(dateMs))
58
+ return undefined;
59
+ return Math.max(0, Math.round((dateMs - Date.now()) / 1000));
60
+ }
40
61
  // ---------------------------------------------------------------------------
41
62
  // Client
42
63
  // ---------------------------------------------------------------------------
@@ -154,7 +175,7 @@ export class XmemoryClient {
154
175
  (typeof payload === "object" && payload !== null && "message" in payload
155
176
  ? String(payload.message)
156
177
  : raw.slice(0, 200));
157
- throw new XmemoryAPIError(`HTTP ${res.status}: ${msg}`, res.status, structured.code, structured.details);
178
+ throw new XmemoryAPIError(`HTTP ${res.status}: ${msg}`, res.status, structured.code, structured.details, parseRetryAfter(res));
158
179
  }
159
180
  const response = payload;
160
181
  if (response.errors?.length) {
package/dist/index.d.ts CHANGED
@@ -9,6 +9,6 @@ export { SchemaType } from "./types.js";
9
9
  export type { SchemaTypeValue, ExtractionLogic, ReadMode, WriteQueueStatus, FieldType, OnDelete, CastStrategy, DecisionKind, MigrationSource, } from "./types.js";
10
10
  export type { ScopeObject, ReadScope, RelationsScope } from "./types.js";
11
11
  export type { XmemoryClientOptions, RequestOptions, ReadOptions, WriteOptions, ExtractOptions, CreateInstanceOptions, GenerateSchemaOptions, UpdateInstanceSchemaOptions, DryRunMigrationOptions, ListMigrationsOptions, GetMigrationOptions, SuggestionRequestOptions, } from "./types.js";
12
- export type { ClusterInfo, InstanceInfo, InstanceSchemaInfo, ReadResult, WriteResult, AsyncWriteResult, WriteStatusResult, ExtractResult, GenerateSchemaResult, ToolDescription, ToolParameterDescription, RawDescribeResult, } from "./types.js";
12
+ export type { ClusterInfo, InstanceInfo, InstanceSchemaInfo, ReadResult, TaggedReaderResult, WriteResult, AsyncWriteResult, WriteStatusResult, ExtractResult, GenerateSchemaResult, ToolDescription, ToolParameterDescription, RawDescribeResult, } from "./types.js";
13
13
  export type { MigrationPlan, MigrationOp, FieldSpec, AddObject, RemoveObject, RenameObject, ChangeObject, AddField, RemoveField, RenameField, ChangeField, AddRelation, RemoveRelation, RenameRelation, ChangeRelation, DefaultValue, EnumValues, } from "./types.js";
14
14
  export type { EnhanceSchemaResult, PlanSummary, DryRunResult, MigrationRecord, ListMigrationsResult, GetMigrationResult, ConsolidatedProposal, ProposalItem, ReviewSuggestionsResult, DecisionInput, RecordedDecision, DependencyWarning, DecideSuggestionsResult, ApplyPendingDecisionsResult, } from "./types.js";
package/dist/instance.js CHANGED
@@ -127,10 +127,14 @@ export class InstanceHandle {
127
127
  }
128
128
  if (options?.traceId != null)
129
129
  body.trace_id = options.traceId;
130
- return this._requestOne("POST", `/instances/${this.id}/read`, {
130
+ // The wire shape omits `reader_results` on a server without question
131
+ // decomposition, so type it as optional here and normalize to an always-array
132
+ // for the public `ReadResult` below.
133
+ const result = await this._requestOne("POST", `/instances/${this.id}/read`, {
131
134
  body,
132
135
  timeoutMs: options?.timeoutMs,
133
136
  });
137
+ return { ...result, reader_results: result.reader_results ?? [] };
134
138
  }
135
139
  async write(text, options) {
136
140
  const body = {
package/dist/types.d.ts CHANGED
@@ -32,24 +32,58 @@ export type WriteQueueStatus = "queued" | "processing" | "extracting" | "extract
32
32
  export declare class XmemoryAPIError extends Error {
33
33
  readonly status?: number | undefined;
34
34
  /**
35
- * Structured error code when the server returned one. For the
35
+ * Structured error code when the server returned one. **Branch on this,
36
+ * not on the bare HTTP `status`** — the same status can mean different
37
+ * things. HTTP 402 carries `"QUOTA_EXCEEDED"` (plan/usage allowance
38
+ * exhausted — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
39
+ * velocity limit — retryable with backoff, honour `retryAfter`). For the
36
40
  * schema-evolution endpoints this is the `error_type` discriminator
37
41
  * (e.g. `"stale_proposal_version"`, `"destructive_confirmation_required"`).
38
42
  * Pattern match on this instead of parsing the message.
39
43
  */
40
44
  readonly code?: string | undefined;
41
- /** Optional structured `details` payload attached to some errors. */
45
+ /**
46
+ * Optional structured `details` payload attached to some errors. For
47
+ * `"QUOTA_EXCEEDED"` this carries `kind`
48
+ * (`"daily_quota_exceeded"` | `"monthly_quota_exceeded"`) and
49
+ * `retry_after_seconds` (`number | null`).
50
+ */
42
51
  readonly details?: (Record<string, unknown> | null) | undefined;
52
+ /**
53
+ * The HTTP `Retry-After` response header, in seconds, when the server sent
54
+ * one — e.g. on `429 RATE_LIMITED`, or a resettable `402 QUOTA_EXCEEDED`.
55
+ * This is the transport-level header value; for quota errors the same hint
56
+ * may also appear as `details.retry_after_seconds`. Surfaced for callers
57
+ * that implement their own backoff — the client does not retry on its own.
58
+ */
59
+ readonly retryAfter?: number | undefined;
43
60
  constructor(message: string, status?: number | undefined,
44
61
  /**
45
- * Structured error code when the server returned one. For the
62
+ * Structured error code when the server returned one. **Branch on this,
63
+ * not on the bare HTTP `status`** — the same status can mean different
64
+ * things. HTTP 402 carries `"QUOTA_EXCEEDED"` (plan/usage allowance
65
+ * exhausted — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
66
+ * velocity limit — retryable with backoff, honour `retryAfter`). For the
46
67
  * schema-evolution endpoints this is the `error_type` discriminator
47
68
  * (e.g. `"stale_proposal_version"`, `"destructive_confirmation_required"`).
48
69
  * Pattern match on this instead of parsing the message.
49
70
  */
50
71
  code?: string | undefined,
51
- /** Optional structured `details` payload attached to some errors. */
52
- details?: (Record<string, unknown> | null) | undefined);
72
+ /**
73
+ * Optional structured `details` payload attached to some errors. For
74
+ * `"QUOTA_EXCEEDED"` this carries `kind`
75
+ * (`"daily_quota_exceeded"` | `"monthly_quota_exceeded"`) and
76
+ * `retry_after_seconds` (`number | null`).
77
+ */
78
+ details?: (Record<string, unknown> | null) | undefined,
79
+ /**
80
+ * The HTTP `Retry-After` response header, in seconds, when the server sent
81
+ * one — e.g. on `429 RATE_LIMITED`, or a resettable `402 QUOTA_EXCEEDED`.
82
+ * This is the transport-level header value; for quota errors the same hint
83
+ * may also appear as `details.retry_after_seconds`. Surfaced for callers
84
+ * that implement their own backoff — the client does not retry on its own.
85
+ */
86
+ retryAfter?: number | undefined);
53
87
  }
54
88
  export declare class XmemoryHealthCheckError extends XmemoryAPIError {
55
89
  constructor(message: string, status?: number);
@@ -74,9 +108,32 @@ export interface InstanceInfo {
74
108
  export interface InstanceSchemaInfo {
75
109
  readonly data_schema: Record<string, unknown>;
76
110
  }
111
+ /**
112
+ * One sub-query and its own answer, in the requested read mode. Appears in
113
+ * {@link ReadResult.reader_results} when the server decomposed a composite query
114
+ * into independent sub-queries.
115
+ */
116
+ export interface TaggedReaderResult {
117
+ readonly sub_query: string;
118
+ readonly reader_result: unknown;
119
+ /**
120
+ * A user-safe message set when this sub-query could not be answered while the
121
+ * others still were (partial tolerance); `null` otherwise.
122
+ */
123
+ readonly error: string | null;
124
+ }
77
125
  export interface ReadResult {
78
126
  readonly trace_id: string | null;
79
127
  readonly reader_result: unknown;
128
+ /**
129
+ * Per-sub-query answers when the server decomposed the query into independent
130
+ * sub-queries — one entry per sub-query, so a single-intent query decomposes
131
+ * to exactly one. `reader_result` above stays the combined back-compat value.
132
+ * Always an array: a server without question decomposition (or with it
133
+ * disabled) omits the field on the wire and the client normalizes it to `[]`,
134
+ * so the array is empty regardless of how many questions the query held.
135
+ */
136
+ readonly reader_results: readonly TaggedReaderResult[];
80
137
  }
81
138
  export interface WriteResult {
82
139
  readonly write_id: string;
package/dist/types.js CHANGED
@@ -12,20 +12,39 @@ export class XmemoryAPIError extends Error {
12
12
  status;
13
13
  code;
14
14
  details;
15
+ retryAfter;
15
16
  constructor(message, status,
16
17
  /**
17
- * Structured error code when the server returned one. For the
18
+ * Structured error code when the server returned one. **Branch on this,
19
+ * not on the bare HTTP `status`** — the same status can mean different
20
+ * things. HTTP 402 carries `"QUOTA_EXCEEDED"` (plan/usage allowance
21
+ * exhausted — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
22
+ * velocity limit — retryable with backoff, honour `retryAfter`). For the
18
23
  * schema-evolution endpoints this is the `error_type` discriminator
19
24
  * (e.g. `"stale_proposal_version"`, `"destructive_confirmation_required"`).
20
25
  * Pattern match on this instead of parsing the message.
21
26
  */
22
27
  code,
23
- /** Optional structured `details` payload attached to some errors. */
24
- details) {
28
+ /**
29
+ * Optional structured `details` payload attached to some errors. For
30
+ * `"QUOTA_EXCEEDED"` this carries `kind`
31
+ * (`"daily_quota_exceeded"` | `"monthly_quota_exceeded"`) and
32
+ * `retry_after_seconds` (`number | null`).
33
+ */
34
+ details,
35
+ /**
36
+ * The HTTP `Retry-After` response header, in seconds, when the server sent
37
+ * one — e.g. on `429 RATE_LIMITED`, or a resettable `402 QUOTA_EXCEEDED`.
38
+ * This is the transport-level header value; for quota errors the same hint
39
+ * may also appear as `details.retry_after_seconds`. Surfaced for callers
40
+ * that implement their own backoff — the client does not retry on its own.
41
+ */
42
+ retryAfter) {
25
43
  super(message);
26
44
  this.status = status;
27
45
  this.code = code;
28
46
  this.details = details;
47
+ this.retryAfter = retryAfter;
29
48
  this.name = "XmemoryAPIError";
30
49
  }
31
50
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xmemory",
3
- "version": "3.0.0",
3
+ "version": "3.2.1",
4
4
  "description": "xmemory",
5
5
  "keywords": [
6
6
  "xmemory"