xmemory 3.1.1 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -115,9 +115,9 @@ Get a handle to an instance and use it for reads, writes, and extractions.
115
115
  const inst = xm.instance("<instance-id>");
116
116
  ```
117
117
 
118
- ### `inst.write(text, options?)` → `WriteResult`
118
+ ### `inst.write(text | mutations, options?)` → `WriteResult`
119
119
 
120
- Extract and store structured objects from text.
120
+ Extract and store structured objects from text:
121
121
 
122
122
  ```typescript
123
123
  const result = await inst.write("Bob is a designer based in Berlin.");
@@ -127,9 +127,34 @@ console.log(result.changes); // what the write created / updated / deleted
127
127
 
128
128
  Options: `{ extractionLogic?, diffEngine?, timeoutMs? }` — `extractionLogic` defaults to `"fast"`.
129
129
 
130
- ### `inst.writeAsync(text, options?)` → `AsyncWriteResult`
130
+ Or pass a `WriteMutation[]` for **structured writes** — deterministic, LLM-free
131
+ create/update/delete mutations applied in array order (later mutations may
132
+ reference objects created earlier in the batch; a `null` value in `values`
133
+ clears that field):
131
134
 
132
- Start an asynchronous write. Returns a `write_id` for tracking.
135
+ ```typescript
136
+ const result = await inst.write([
137
+ {
138
+ object_mutation: {
139
+ object_type: "person",
140
+ create: { key: { name: "Bob" }, values: { role: "designer" } },
141
+ },
142
+ },
143
+ {
144
+ object_mutation: {
145
+ object_type: "person",
146
+ update: { key: { name: "Bob" }, values: { role: null } }, // null clears
147
+ },
148
+ },
149
+ ]);
150
+ ```
151
+
152
+ Options for the mutations form: `{ timeoutMs? }` (extraction options don't apply).
153
+
154
+ ### `inst.writeAsync(text | mutations, options?)` → `AsyncWriteResult`
155
+
156
+ Start an asynchronous write (same text / `WriteMutation[]` dual input as
157
+ `inst.write`). Returns a `write_id` for tracking.
133
158
 
134
159
  ```typescript
135
160
  const { write_id } = await inst.writeAsync("Carol manages the London office.");
@@ -155,6 +180,24 @@ console.log(result.reader_result);
155
180
 
156
181
  Options: `{ readMode?, scope?, traceId?, timeoutMs? }` — `readMode` defaults to `"single-answer"`.
157
182
 
183
+ #### Composite queries
184
+
185
+ When a query bundles several independent questions, the server may decompose it
186
+ into sub-queries and answer each one. `reader_result` is still the combined
187
+ answer (for `"single-answer"` mode, a labelled multi-part string); `reader_results`
188
+ holds one `TaggedReaderResult` (`{ sub_query, reader_result, error }`) per
189
+ sub-query so you can read each answer unambiguously — a single-intent query
190
+ decomposes to one entry. `reader_results` is always an array: a server without
191
+ question decomposition omits the field on the wire and the client normalizes it
192
+ to `[]`, so it is empty regardless of how many questions the query held.
193
+
194
+ ```typescript
195
+ const result = await inst.read("Who leads sales, and where is HQ?");
196
+ for (const part of result.reader_results) {
197
+ console.log(part.sub_query, "→", part.error ?? part.reader_result);
198
+ }
199
+ ```
200
+
158
201
  #### Scoped reads
159
202
 
160
203
  By default a read may draw on the whole instance. Pass a `scope` to restrict it
@@ -343,19 +386,17 @@ when the server returned one), `details` (an optional structured payload), and
343
386
  `retryAfter` (the `Retry-After` header in seconds, when the server sent one).
344
387
 
345
388
  **Branch on `code`, not on the bare HTTP status** — the same status can mean
346
- different things. In particular HTTP `402 Payment Required` is now overloaded:
389
+ different things:
347
390
 
348
391
  | HTTP | `code` | Meaning | Retryable? |
349
392
  | ---- | ----------------- | ---------------------------------------------------- | ---------------------------------- |
350
393
  | 402 | `QUOTA_EXCEEDED` | Tenant exhausted its plan/usage allowance (a daily or monthly token quota). | **No.** Wait for the window to reset. |
351
- | 402 | `TRIAL_ENDED` | Trial over / subscription lapsed. | **No.** Needs a plan change. |
352
394
  | 429 | `RATE_LIMITED` | Genuine velocity / rate limit. | **Yes**, with backoff. |
353
395
 
354
396
  For `QUOTA_EXCEEDED`, `details` carries `kind`
355
397
  (`"daily_quota_exceeded"` | `"monthly_quota_exceeded"`) and
356
398
  `retry_after_seconds` (`number | null`); when the window is resettable the
357
399
  server also sends a `Retry-After` header, surfaced as `retryAfter` (seconds).
358
- `TRIAL_ENDED` may carry `details.kind === "trial_exceeded"` or no details.
359
400
  `RATE_LIMITED` is retryable — honour `retryAfter` (or `Retry-After`) for backoff.
360
401
  The client never retries on its own; it only surfaces the value.
361
402
 
@@ -371,10 +412,6 @@ try {
371
412
  console.error(`Quota exhausted (${kind}); resets in ${e.retryAfter ?? "?"}s`);
372
413
  break;
373
414
  }
374
- case "TRIAL_ENDED":
375
- // Non-retryable: trial over / subscription lapsed — upgrade required.
376
- console.error("Trial ended — upgrade the plan.");
377
- break;
378
415
  case "RATE_LIMITED":
379
416
  // Retryable: back off and retry, honouring Retry-After.
380
417
  console.error(`Rate limited; retry after ${e.retryAfter ?? "a short delay"}s`);
package/dist/index.d.ts CHANGED
@@ -9,6 +9,7 @@ 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
+ export type { WriteMutation, ObjectMutationBody, ObjectCreatePayload, ObjectUpdatePayload, ObjectDeletePayload, RelationMutationBody, RelationCreatePayload, RelationUpdatePayload, RelationDeletePayload, RelationEndpoint, } from "./types.js";
13
14
  export type { MigrationPlan, MigrationOp, FieldSpec, AddObject, RemoveObject, RenameObject, ChangeObject, AddField, RemoveField, RenameField, ChangeField, AddRelation, RemoveRelation, RenameRelation, ChangeRelation, DefaultValue, EnumValues, } from "./types.js";
14
15
  export type { EnhanceSchemaResult, PlanSummary, DryRunResult, MigrationRecord, ListMigrationsResult, GetMigrationResult, ConsolidatedProposal, ProposalItem, ReviewSuggestionsResult, DecisionInput, RecordedDecision, DependencyWarning, DecideSuggestionsResult, ApplyPendingDecisionsResult, } from "./types.js";
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * InstanceHandle — scoped data operations on a single xmemory instance.
3
3
  */
4
- import type { ApplyPendingDecisionsResult, AsyncWriteResult, DecideSuggestionsResult, DecisionInput, ExtractOptions, ExtractResult, InstanceSchemaInfo, RawDescribeResult, ReadOptions, ReadResult, RequestOneFn, RequestOptions, ReviewSuggestionsResult, SuggestionRequestOptions, ToolDescription, WriteOptions, WriteResult, WriteStatusResult } from "./types.js";
4
+ import type { ApplyPendingDecisionsResult, AsyncWriteResult, DecideSuggestionsResult, DecisionInput, ExtractOptions, ExtractResult, InstanceSchemaInfo, RawDescribeResult, ReadOptions, ReadResult, RequestOneFn, RequestOptions, ReviewSuggestionsResult, SuggestionRequestOptions, ToolDescription, WriteMutation, WriteOptions, WriteResult, WriteStatusResult } from "./types.js";
5
5
  export declare class DescribeResult {
6
6
  readonly instanceId: string;
7
7
  readonly instanceName: string;
@@ -32,8 +32,23 @@ export declare class InstanceHandle {
32
32
  private _describeTtlMs;
33
33
  constructor(id: string, requestOne: RequestOneFn);
34
34
  read(query: string, options?: ReadOptions): Promise<ReadResult>;
35
+ /**
36
+ * Write to this instance: extract from free text, or apply structured
37
+ * mutations. Pass a string to extract structured data from free-form text,
38
+ * or a `WriteMutation[]` to apply deterministic, LLM-free create / update /
39
+ * delete edits (applied in array order; later mutations may reference
40
+ * objects created earlier in the batch, and a `null` value in a mutation's
41
+ * `values` clears that field). `extractionLogic` / `diffEngine` only apply
42
+ * to the text form.
43
+ */
35
44
  write(text: string, options?: WriteOptions): Promise<WriteResult>;
45
+ write(mutations: readonly WriteMutation[], options?: RequestOptions): Promise<WriteResult>;
46
+ /**
47
+ * Submit a write job and return immediately with a `write_id` for polling.
48
+ * Accepts the same text / `WriteMutation[]` dual input as {@link write}.
49
+ */
36
50
  writeAsync(text: string, options?: WriteOptions): Promise<AsyncWriteResult>;
51
+ writeAsync(mutations: readonly WriteMutation[], options?: RequestOptions): Promise<AsyncWriteResult>;
37
52
  writeStatus(writeId: string, options?: RequestOptions): Promise<WriteStatusResult>;
38
53
  extract(text: string, options?: ExtractOptions): Promise<ExtractResult>;
39
54
  getSchema(options?: RequestOptions): Promise<InstanceSchemaInfo>;
package/dist/instance.js CHANGED
@@ -1,6 +1,24 @@
1
1
  /**
2
2
  * InstanceHandle — scoped data operations on a single xmemory instance.
3
3
  */
4
+ /** Build the shared `/write` + `/write_async` request body for either input mode. */
5
+ function buildWriteBody(input, options) {
6
+ if (typeof input !== "string") {
7
+ if (input.length === 0) {
8
+ throw new Error("structured write requires at least one mutation");
9
+ }
10
+ // Structured path: no text, no extraction options — mutations go straight
11
+ // to the wire.
12
+ return { structured_mutations: input };
13
+ }
14
+ const body = {
15
+ text: input,
16
+ extraction_logic: options?.extractionLogic ?? "fast",
17
+ };
18
+ if (options?.diffEngine != null)
19
+ body.use_diff_engine = options.diffEngine;
20
+ return body;
21
+ }
4
22
  const DEFAULT_DESCRIBE_TTL_MS = 300_000; // 5 minutes
5
23
  export class DescribeResult {
6
24
  instanceId;
@@ -127,32 +145,24 @@ export class InstanceHandle {
127
145
  }
128
146
  if (options?.traceId != null)
129
147
  body.trace_id = options.traceId;
130
- return this._requestOne("POST", `/instances/${this.id}/read`, {
148
+ // The wire shape omits `reader_results` on a server without question
149
+ // decomposition, so type it as optional here and normalize to an always-array
150
+ // for the public `ReadResult` below.
151
+ const result = await this._requestOne("POST", `/instances/${this.id}/read`, {
131
152
  body,
132
153
  timeoutMs: options?.timeoutMs,
133
154
  });
155
+ return { ...result, reader_results: result.reader_results ?? [] };
134
156
  }
135
- async write(text, options) {
136
- const body = {
137
- text,
138
- extraction_logic: options?.extractionLogic ?? "fast",
139
- };
140
- if (options?.diffEngine != null)
141
- body.diff_engine = options.diffEngine;
157
+ async write(input, options) {
142
158
  return this._requestOne("POST", `/instances/${this.id}/write`, {
143
- body,
159
+ body: buildWriteBody(input, options),
144
160
  timeoutMs: options?.timeoutMs,
145
161
  });
146
162
  }
147
- async writeAsync(text, options) {
148
- const body = {
149
- text,
150
- extraction_logic: options?.extractionLogic ?? "fast",
151
- };
152
- if (options?.diffEngine != null)
153
- body.diff_engine = options.diffEngine;
163
+ async writeAsync(input, options) {
154
164
  return this._requestOne("POST", `/instances/${this.id}/write_async`, {
155
- body,
165
+ body: buildWriteBody(input, options),
156
166
  timeoutMs: options?.timeoutMs,
157
167
  });
158
168
  }
package/dist/types.d.ts CHANGED
@@ -34,9 +34,8 @@ export declare class XmemoryAPIError extends Error {
34
34
  /**
35
35
  * Structured error code when the server returned one. **Branch on this,
36
36
  * not on the bare HTTP `status`** — the same status can mean different
37
- * things. HTTP 402 carries either `"QUOTA_EXCEEDED"` (plan/usage allowance
38
- * exhausted — non-retryable) or `"TRIAL_ENDED"` (trial over / subscription
39
- * lapsed — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
37
+ * things. HTTP 402 carries `"QUOTA_EXCEEDED"` (plan/usage allowance
38
+ * exhausted — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
40
39
  * velocity limit — retryable with backoff, honour `retryAfter`). For the
41
40
  * schema-evolution endpoints this is the `error_type` discriminator
42
41
  * (e.g. `"stale_proposal_version"`, `"destructive_confirmation_required"`).
@@ -47,8 +46,7 @@ export declare class XmemoryAPIError extends Error {
47
46
  * Optional structured `details` payload attached to some errors. For
48
47
  * `"QUOTA_EXCEEDED"` this carries `kind`
49
48
  * (`"daily_quota_exceeded"` | `"monthly_quota_exceeded"`) and
50
- * `retry_after_seconds` (`number | null`); `"TRIAL_ENDED"` may carry
51
- * `kind: "trial_exceeded"` or no details at all.
49
+ * `retry_after_seconds` (`number | null`).
52
50
  */
53
51
  readonly details?: (Record<string, unknown> | null) | undefined;
54
52
  /**
@@ -63,9 +61,8 @@ export declare class XmemoryAPIError extends Error {
63
61
  /**
64
62
  * Structured error code when the server returned one. **Branch on this,
65
63
  * not on the bare HTTP `status`** — the same status can mean different
66
- * things. HTTP 402 carries either `"QUOTA_EXCEEDED"` (plan/usage allowance
67
- * exhausted — non-retryable) or `"TRIAL_ENDED"` (trial over / subscription
68
- * lapsed — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
64
+ * things. HTTP 402 carries `"QUOTA_EXCEEDED"` (plan/usage allowance
65
+ * exhausted — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
69
66
  * velocity limit — retryable with backoff, honour `retryAfter`). For the
70
67
  * schema-evolution endpoints this is the `error_type` discriminator
71
68
  * (e.g. `"stale_proposal_version"`, `"destructive_confirmation_required"`).
@@ -76,8 +73,7 @@ export declare class XmemoryAPIError extends Error {
76
73
  * Optional structured `details` payload attached to some errors. For
77
74
  * `"QUOTA_EXCEEDED"` this carries `kind`
78
75
  * (`"daily_quota_exceeded"` | `"monthly_quota_exceeded"`) and
79
- * `retry_after_seconds` (`number | null`); `"TRIAL_ENDED"` may carry
80
- * `kind: "trial_exceeded"` or no details at all.
76
+ * `retry_after_seconds` (`number | null`).
81
77
  */
82
78
  details?: (Record<string, unknown> | null) | undefined,
83
79
  /**
@@ -112,9 +108,32 @@ export interface InstanceInfo {
112
108
  export interface InstanceSchemaInfo {
113
109
  readonly data_schema: Record<string, unknown>;
114
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
+ }
115
125
  export interface ReadResult {
116
126
  readonly trace_id: string | null;
117
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[];
118
137
  }
119
138
  export interface WriteResult {
120
139
  readonly write_id: string;
@@ -138,6 +157,86 @@ export interface ExtractResult {
138
157
  export interface GenerateSchemaResult {
139
158
  readonly data_schema: Record<string, unknown>;
140
159
  }
160
+ export interface RelationEndpoint {
161
+ /** Relation role name from the instance schema. */
162
+ object_name: string;
163
+ /** Endpoint identity: user primary-key fields (field -> value), or `{ xuid: ... }`. */
164
+ key?: Record<string, unknown>;
165
+ }
166
+ /** Create an object: `key` holds the user primary-key fields (no `xuid` — it is
167
+ * generated server-side), `values` the remaining field values. */
168
+ export interface ObjectCreatePayload {
169
+ key?: Record<string, unknown>;
170
+ values?: Record<string, unknown>;
171
+ }
172
+ /** Update an object identified by `key` (primary-key fields or `{ xuid: ... }`).
173
+ * A `null` value in `values` clears that field. */
174
+ export interface ObjectUpdatePayload {
175
+ key: Record<string, unknown>;
176
+ values: Record<string, unknown>;
177
+ }
178
+ /** Delete the object identified by `key` (primary-key fields or `{ xuid: ... }`). */
179
+ export interface ObjectDeletePayload {
180
+ key: Record<string, unknown>;
181
+ }
182
+ /** Create a relation between the `endpoints`, with optional own-field `values`. */
183
+ export interface RelationCreatePayload {
184
+ endpoints: RelationEndpoint[];
185
+ values?: Record<string, unknown>;
186
+ }
187
+ /** Update a relation's own fields. Address it by `endpoints`, or by
188
+ * `key: { xuid: ... }` when endpoints are ambiguous. A `null` value in `values`
189
+ * clears that field. */
190
+ export interface RelationUpdatePayload {
191
+ key?: Record<string, unknown>;
192
+ endpoints?: RelationEndpoint[];
193
+ values: Record<string, unknown>;
194
+ }
195
+ /** Delete relation(s) matched by `endpoints` (a subset is allowed) or by
196
+ * `key: { xuid: ... }`. Deleting more than one matched row requires
197
+ * `allow_bulk_delete: true`. */
198
+ export interface RelationDeletePayload {
199
+ key?: Record<string, unknown>;
200
+ endpoints?: RelationEndpoint[];
201
+ allow_bulk_delete?: boolean;
202
+ }
203
+ export type ObjectMutationBody = {
204
+ object_type: string;
205
+ } & ({
206
+ create: ObjectCreatePayload;
207
+ update?: never;
208
+ delete?: never;
209
+ } | {
210
+ update: ObjectUpdatePayload;
211
+ create?: never;
212
+ delete?: never;
213
+ } | {
214
+ delete: ObjectDeletePayload;
215
+ create?: never;
216
+ update?: never;
217
+ });
218
+ export type RelationMutationBody = {
219
+ relation_type: string;
220
+ } & ({
221
+ create: RelationCreatePayload;
222
+ update?: never;
223
+ delete?: never;
224
+ } | {
225
+ update: RelationUpdatePayload;
226
+ create?: never;
227
+ delete?: never;
228
+ } | {
229
+ delete: RelationDeletePayload;
230
+ create?: never;
231
+ update?: never;
232
+ });
233
+ export type WriteMutation = {
234
+ object_mutation: ObjectMutationBody;
235
+ relation_mutation?: never;
236
+ } | {
237
+ relation_mutation: RelationMutationBody;
238
+ object_mutation?: never;
239
+ };
141
240
  export type FieldType = "str" | "string" | "int" | "integer" | "float" | "bool" | "boolean";
142
241
  export type OnDelete = "nullify" | "cascade";
143
242
  export type CastStrategy = "safe_implicit" | "explicit_using" | "lossy";
package/dist/types.js CHANGED
@@ -17,9 +17,8 @@ export class XmemoryAPIError extends Error {
17
17
  /**
18
18
  * Structured error code when the server returned one. **Branch on this,
19
19
  * not on the bare HTTP `status`** — the same status can mean different
20
- * things. HTTP 402 carries either `"QUOTA_EXCEEDED"` (plan/usage allowance
21
- * exhausted — non-retryable) or `"TRIAL_ENDED"` (trial over / subscription
22
- * lapsed — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
20
+ * things. HTTP 402 carries `"QUOTA_EXCEEDED"` (plan/usage allowance
21
+ * exhausted — non-retryable); HTTP 429 carries `"RATE_LIMITED"` (genuine
23
22
  * velocity limit — retryable with backoff, honour `retryAfter`). For the
24
23
  * schema-evolution endpoints this is the `error_type` discriminator
25
24
  * (e.g. `"stale_proposal_version"`, `"destructive_confirmation_required"`).
@@ -30,8 +29,7 @@ export class XmemoryAPIError extends Error {
30
29
  * Optional structured `details` payload attached to some errors. For
31
30
  * `"QUOTA_EXCEEDED"` this carries `kind`
32
31
  * (`"daily_quota_exceeded"` | `"monthly_quota_exceeded"`) and
33
- * `retry_after_seconds` (`number | null`); `"TRIAL_ENDED"` may carry
34
- * `kind: "trial_exceeded"` or no details at all.
32
+ * `retry_after_seconds` (`number | null`).
35
33
  */
36
34
  details,
37
35
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xmemory",
3
- "version": "3.1.1",
3
+ "version": "3.3.0",
4
4
  "description": "xmemory",
5
5
  "keywords": [
6
6
  "xmemory"