nenavi 0.0.0 → 0.1.0-alpha.2

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.
@@ -0,0 +1,896 @@
1
+ // The client, `Nenavi`, and its resource groups (sdks/CONTRACT.md, Operations).
2
+ //
3
+ // Each method describes one call: its HTTP method and path, where its fields go, and
4
+ // whether the SDK may retry it by itself. Core in core.ts sends it.
5
+ import { NenaviError, WaitTimeoutError } from './errors.js';
6
+ import { Core, helperDeadline, helperWait, ownProperties, pathParam, withCause, } from './core.js';
7
+ class Resource {
8
+ _core;
9
+ _raw;
10
+ constructor(core, raw) {
11
+ this._core = core;
12
+ this._raw = raw;
13
+ }
14
+ /** Build the call and send it; an error while building it rejects the promise too. */
15
+ _request(build) {
16
+ let call;
17
+ try {
18
+ call = build();
19
+ }
20
+ catch (error) {
21
+ return Promise.reject(error);
22
+ }
23
+ return this._core.request(call, this._raw);
24
+ }
25
+ }
26
+ /**
27
+ * The states a helper keeps polling through. Any other state, one the service adds later
28
+ * included, is final and returned.
29
+ */
30
+ const WORKING = new Set(['pending', 'running']);
31
+ /** `GET /v1/events/{event_id}/extraction-status`, for the method and its helper. */
32
+ function extractionStatusCall(eventId, options) {
33
+ return {
34
+ method: 'GET',
35
+ path: `/v1/events/${pathParam(eventId)}/extraction-status`,
36
+ retrySafe: true,
37
+ options,
38
+ };
39
+ }
40
+ /** `GET /v1/reingest/{run_id}`, for the method and its helper. */
41
+ function reingestGetCall(runId, options) {
42
+ return { method: 'GET', path: `/v1/reingest/${pathParam(runId)}`, retrySafe: true, options };
43
+ }
44
+ /** A caller's `Idempotency-Key`, or null; an empty value counts as not given. */
45
+ function callerKey(options) {
46
+ const key = ownProperties(options).idempotencyKey;
47
+ return key ? String(key) : null;
48
+ }
49
+ /** The `/v1/events` routes. */
50
+ export class Events extends Resource {
51
+ /** `GET /v1/events/{event_id}`: the stored event, as the JSON object it is. */
52
+ get(eventId, options) {
53
+ return this._request(() => ({
54
+ method: 'GET',
55
+ path: `/v1/events/${pathParam(eventId)}`,
56
+ retrySafe: true,
57
+ options,
58
+ }));
59
+ }
60
+ /** `GET /v1/events/{event_id}/nodes`: the nodes derived from the event. */
61
+ nodes(eventId, options) {
62
+ return this._request(() => ({
63
+ method: 'GET',
64
+ path: `/v1/events/${pathParam(eventId)}/nodes`,
65
+ retrySafe: true,
66
+ options,
67
+ }));
68
+ }
69
+ /** `GET /v1/events/{event_id}/processing-status`. */
70
+ processingStatus(eventId, options) {
71
+ return this._request(() => ({
72
+ method: 'GET',
73
+ path: `/v1/events/${pathParam(eventId)}/processing-status`,
74
+ retrySafe: true,
75
+ options,
76
+ }));
77
+ }
78
+ /** `GET /v1/events/{event_id}/extraction`: the record, or its protected view. */
79
+ extraction(eventId, options) {
80
+ return this._request(() => ({
81
+ method: 'GET',
82
+ path: `/v1/events/${pathParam(eventId)}/extraction`,
83
+ retrySafe: true,
84
+ options,
85
+ }));
86
+ }
87
+ /** `GET /v1/events/{event_id}/extraction-status`. */
88
+ extractionStatus(eventId, options) {
89
+ return this._request(() => extractionStatusCall(eventId, options));
90
+ }
91
+ /** `POST /v1/events/{event_id}/retry-extraction`. Not retried automatically. */
92
+ retryExtraction(eventId, params, options) {
93
+ return this._request(() => ({
94
+ method: 'POST',
95
+ path: `/v1/events/${pathParam(eventId)}/retry-extraction`,
96
+ retrySafe: false,
97
+ query: params,
98
+ options,
99
+ }));
100
+ }
101
+ }
102
+ /** The `/v1/nodes` routes. */
103
+ export class Nodes extends Resource {
104
+ /** `GET /v1/nodes/{node_id}`. */
105
+ get(nodeId, options) {
106
+ return this._request(() => ({
107
+ method: 'GET',
108
+ path: `/v1/nodes/${pathParam(nodeId)}`,
109
+ retrySafe: true,
110
+ options,
111
+ }));
112
+ }
113
+ /** `GET /v1/nodes`: list nodes. */
114
+ list(params, options) {
115
+ return this._request(() => ({
116
+ method: 'GET',
117
+ path: '/v1/nodes',
118
+ retrySafe: true,
119
+ query: params,
120
+ options,
121
+ }));
122
+ }
123
+ /**
124
+ * `GET /v1/nodes/scan`: one page of nodes, in id order.
125
+ *
126
+ * While the page's `has_more` is true, pass its `next_cursor` as `after_id` to read the
127
+ * next page.
128
+ */
129
+ scan(params, options) {
130
+ return this._request(() => ({
131
+ method: 'GET',
132
+ path: '/v1/nodes/scan',
133
+ retrySafe: true,
134
+ query: params,
135
+ options,
136
+ }));
137
+ }
138
+ /** `GET /v1/nodes/{node_id}/provenance`: the provenance, or its protected view. */
139
+ provenance(nodeId, params, options) {
140
+ return this._request(() => ({
141
+ method: 'GET',
142
+ path: `/v1/nodes/${pathParam(nodeId)}/provenance`,
143
+ retrySafe: true,
144
+ query: params,
145
+ options,
146
+ }));
147
+ }
148
+ /** `PUT /v1/nodes/{node_id}/promote`. Not retried automatically. */
149
+ promote(nodeId, options) {
150
+ return this._request(() => ({
151
+ method: 'PUT',
152
+ path: `/v1/nodes/${pathParam(nodeId)}/promote`,
153
+ retrySafe: false,
154
+ idempotencyKey: callerKey(options),
155
+ options,
156
+ }));
157
+ }
158
+ /** `PUT /v1/nodes/{node_id}/archive`. Not retried automatically. */
159
+ archive(nodeId, options) {
160
+ return this._request(() => ({
161
+ method: 'PUT',
162
+ path: `/v1/nodes/${pathParam(nodeId)}/archive`,
163
+ retrySafe: false,
164
+ idempotencyKey: callerKey(options),
165
+ options,
166
+ }));
167
+ }
168
+ /**
169
+ * `PUT /v1/nodes/{node_id}/reinforce`. Not retried automatically.
170
+ *
171
+ * Sends a body only when `params` has a field.
172
+ */
173
+ reinforce(nodeId, params, options) {
174
+ const given = Object.values(params ?? {}).some((value) => value !== undefined);
175
+ return this._request(() => ({
176
+ method: 'PUT',
177
+ path: `/v1/nodes/${pathParam(nodeId)}/reinforce`,
178
+ retrySafe: false,
179
+ body: given ? params : undefined,
180
+ idempotencyKey: callerKey(options),
181
+ options,
182
+ }));
183
+ }
184
+ /** `PUT /v1/nodes/{node_id}/condition`: record a conditional claim's state. Not retried automatically. */
185
+ evaluateCondition(nodeId, params, options) {
186
+ return this._request(() => ({
187
+ method: 'PUT',
188
+ path: `/v1/nodes/${pathParam(nodeId)}/condition`,
189
+ retrySafe: false,
190
+ body: params ?? {},
191
+ idempotencyKey: callerKey(options),
192
+ options,
193
+ }));
194
+ }
195
+ /** `GET /v1/nodes/{node_id}/neighborhood`: the nodes within `max_hops` edges. */
196
+ neighborhood(nodeId, params, options) {
197
+ return this._request(() => ({
198
+ method: 'GET',
199
+ path: `/v1/nodes/${pathParam(nodeId)}/neighborhood`,
200
+ retrySafe: true,
201
+ query: params,
202
+ options,
203
+ }));
204
+ }
205
+ /** `GET /v1/nodes/{node_id}/chain`: the node's supersedence chain. */
206
+ chain(nodeId, params, options) {
207
+ return this._request(() => ({
208
+ method: 'GET',
209
+ path: `/v1/nodes/${pathParam(nodeId)}/chain`,
210
+ retrySafe: true,
211
+ query: params,
212
+ options,
213
+ }));
214
+ }
215
+ }
216
+ /** The `/v1/reingest` routes: re-derive one end user's stored memories. */
217
+ export class Reingest extends Resource {
218
+ /**
219
+ * `POST /v1/reingest` with `dry_run: true`: count and estimate a run.
220
+ *
221
+ * Always sends `dry_run: true`, so a preview never starts a run. Not retried
222
+ * automatically.
223
+ */
224
+ preview(params, options) {
225
+ return this._request(() => ({
226
+ method: 'POST',
227
+ path: '/v1/reingest',
228
+ retrySafe: false,
229
+ body: { ...ownProperties(params), dry_run: true },
230
+ options,
231
+ }));
232
+ }
233
+ /**
234
+ * `POST /v1/reingest` with `dry_run: false`: start a background run.
235
+ *
236
+ * The service answers `202` with the run's `run_id`, or `200` with `run_id: null` when
237
+ * nothing needs re-deriving. Each memory the run takes counts as one ingest call. A run
238
+ * takes at most `limit` memories, so a `complete` run can leave some for later
239
+ * (`remaining` above 0): sending the same request again continues it. Not retried
240
+ * automatically; a `409` `reingest_running` throws `ConflictError`.
241
+ */
242
+ start(params, options) {
243
+ return this._request(() => ({
244
+ method: 'POST',
245
+ path: '/v1/reingest',
246
+ retrySafe: false,
247
+ body: { ...ownProperties(params), dry_run: false },
248
+ options,
249
+ }));
250
+ }
251
+ /** `GET /v1/reingest/{run_id}`: the run's state, counts and usage. */
252
+ get(runId, options) {
253
+ return this._request(() => reingestGetCall(runId, options));
254
+ }
255
+ }
256
+ /** The claim routes: supersedences and contradictions. Not retried automatically. */
257
+ export class Claims extends Resource {
258
+ /** `POST /v1/supersedences`: record that one claim replaces another. */
259
+ supersede(params, options) {
260
+ return this._request(() => ({
261
+ method: 'POST',
262
+ path: '/v1/supersedences',
263
+ retrySafe: false,
264
+ body: params ?? {},
265
+ options,
266
+ }));
267
+ }
268
+ /** `POST /v1/contradictions`: mark two claims as contradicting each other. */
269
+ markContradiction(params, options) {
270
+ return this._request(() => ({
271
+ method: 'POST',
272
+ path: '/v1/contradictions',
273
+ retrySafe: false,
274
+ body: params ?? {},
275
+ options,
276
+ }));
277
+ }
278
+ /** `POST /v1/contradictions/resolve`: resolve a contradiction in favor of one claim. */
279
+ resolveContradiction(params, options) {
280
+ return this._request(() => ({
281
+ method: 'POST',
282
+ path: '/v1/contradictions/resolve',
283
+ retrySafe: false,
284
+ body: params ?? {},
285
+ options,
286
+ }));
287
+ }
288
+ }
289
+ /** The `/v1/alias-proposals` routes: identity review. */
290
+ export class AliasProposals extends Resource {
291
+ /** `GET /v1/alias-proposals`: the alias proposals waiting for review. */
292
+ list(params, options) {
293
+ return this._request(() => ({
294
+ method: 'GET',
295
+ path: '/v1/alias-proposals',
296
+ retrySafe: true,
297
+ query: params,
298
+ answer: 'array',
299
+ options,
300
+ }));
301
+ }
302
+ /** `POST /v1/alias-proposals/{proposal_operation_id}/review`. Not retried automatically. */
303
+ review(proposalOperationId, params, options) {
304
+ return this._request(() => ({
305
+ method: 'POST',
306
+ path: `/v1/alias-proposals/${pathParam(proposalOperationId)}/review`,
307
+ retrySafe: false,
308
+ body: params ?? {},
309
+ options,
310
+ }));
311
+ }
312
+ }
313
+ /** The `/v1/materializations` routes. */
314
+ export class Materializations extends Resource {
315
+ /** `POST /v1/materializations/process`: run the due materializations. Not retried automatically. */
316
+ process(params, options) {
317
+ return this._request(() => ({
318
+ method: 'POST',
319
+ path: '/v1/materializations/process',
320
+ retrySafe: false,
321
+ body: params ?? {},
322
+ options,
323
+ }));
324
+ }
325
+ }
326
+ /** The `/v1/extractions` routes. */
327
+ export class Extractions extends Resource {
328
+ /** `POST /v1/extractions/process`: run the due extraction jobs. Not retried automatically. */
329
+ process(params, options) {
330
+ return this._request(() => ({
331
+ method: 'POST',
332
+ path: '/v1/extractions/process',
333
+ retrySafe: false,
334
+ body: params ?? {},
335
+ options,
336
+ }));
337
+ }
338
+ }
339
+ /** The `/v1/assertions` routes: exact queries over assertions. Not retried automatically. */
340
+ export class Assertions extends Resource {
341
+ /** `POST /v1/assertions/aggregate`. */
342
+ aggregate(params, options) {
343
+ return this._request(() => ({
344
+ method: 'POST',
345
+ path: '/v1/assertions/aggregate',
346
+ retrySafe: false,
347
+ body: params ?? {},
348
+ options,
349
+ }));
350
+ }
351
+ /** `POST /v1/assertions/state`. */
352
+ state(params, options) {
353
+ return this._request(() => ({
354
+ method: 'POST',
355
+ path: '/v1/assertions/state',
356
+ retrySafe: false,
357
+ body: params ?? {},
358
+ options,
359
+ }));
360
+ }
361
+ }
362
+ /** The `/v1/quantities` routes: exact queries over quantities. Not retried automatically. */
363
+ export class Quantities extends Resource {
364
+ /** `POST /v1/quantities/aggregate`. */
365
+ aggregate(params, options) {
366
+ return this._request(() => ({
367
+ method: 'POST',
368
+ path: '/v1/quantities/aggregate',
369
+ retrySafe: false,
370
+ body: params ?? {},
371
+ options,
372
+ }));
373
+ }
374
+ /** `POST /v1/quantities/aggregate-text`: plan and run an aggregation from a question. */
375
+ aggregateText(params, options) {
376
+ return this._request(() => ({
377
+ method: 'POST',
378
+ path: '/v1/quantities/aggregate-text',
379
+ retrySafe: false,
380
+ body: params ?? {},
381
+ options,
382
+ }));
383
+ }
384
+ }
385
+ /** The `/v1/retrievals` routes: retrieval receipts. */
386
+ export class Retrievals extends Resource {
387
+ /** `GET /v1/retrievals/{request_id}`: the receipt, or one of its protected views. */
388
+ get(requestId, params, options) {
389
+ return this._request(() => ({
390
+ method: 'GET',
391
+ path: `/v1/retrievals/${pathParam(requestId)}`,
392
+ retrySafe: true,
393
+ query: params,
394
+ options,
395
+ }));
396
+ }
397
+ }
398
+ /** The `/v1/relevance` routes: relevance feedback. */
399
+ export class Relevance extends Resource {
400
+ /** `POST /v1/relevance`: record feedback on a retrieved memory. Not retried automatically. */
401
+ record(params, options) {
402
+ return this._request(() => ({
403
+ method: 'POST',
404
+ path: '/v1/relevance',
405
+ retrySafe: false,
406
+ body: params ?? {},
407
+ options,
408
+ }));
409
+ }
410
+ /** `GET /v1/relevance`: the recorded feedback. */
411
+ list(params, options) {
412
+ return this._request(() => ({
413
+ method: 'GET',
414
+ path: '/v1/relevance',
415
+ retrySafe: true,
416
+ query: params,
417
+ answer: 'array',
418
+ options,
419
+ }));
420
+ }
421
+ /** `GET /v1/relevance/{feedback_id}`. */
422
+ get(feedbackId, params, options) {
423
+ return this._request(() => ({
424
+ method: 'GET',
425
+ path: `/v1/relevance/${pathParam(feedbackId)}`,
426
+ retrySafe: true,
427
+ query: params,
428
+ options,
429
+ }));
430
+ }
431
+ }
432
+ /** The `/v1/answer-citations` routes: which memories an answer cited. */
433
+ export class AnswerCitations extends Resource {
434
+ /** `POST /v1/answer-citations`: record an answer's citations. Not retried automatically. */
435
+ record(params, options) {
436
+ return this._request(() => ({
437
+ method: 'POST',
438
+ path: '/v1/answer-citations',
439
+ retrySafe: false,
440
+ body: params ?? {},
441
+ options,
442
+ }));
443
+ }
444
+ /** `GET /v1/answer-citations`: the recorded citations, each a record or its protected view. */
445
+ list(params, options) {
446
+ return this._request(() => ({
447
+ method: 'GET',
448
+ path: '/v1/answer-citations',
449
+ retrySafe: true,
450
+ query: params,
451
+ answer: 'array',
452
+ options,
453
+ }));
454
+ }
455
+ /** `GET /v1/answer-citations/{citation_id}`: the record, or its protected view. */
456
+ get(citationId, params, options) {
457
+ return this._request(() => ({
458
+ method: 'GET',
459
+ path: `/v1/answer-citations/${pathParam(citationId)}`,
460
+ retrySafe: true,
461
+ query: params,
462
+ options,
463
+ }));
464
+ }
465
+ }
466
+ /** The `/v1/learning/profiles` routes: ranking profiles. */
467
+ export class LearningProfiles extends Resource {
468
+ /** `GET /v1/learning/profiles`. */
469
+ list(params, options) {
470
+ return this._request(() => ({
471
+ method: 'GET',
472
+ path: '/v1/learning/profiles',
473
+ retrySafe: true,
474
+ query: params,
475
+ answer: 'array',
476
+ options,
477
+ }));
478
+ }
479
+ /** `POST /v1/learning/profiles`: create a profile. Not retried automatically. */
480
+ create(params, options) {
481
+ return this._request(() => ({
482
+ method: 'POST',
483
+ path: '/v1/learning/profiles',
484
+ retrySafe: false,
485
+ body: params ?? {},
486
+ options,
487
+ }));
488
+ }
489
+ /** `GET /v1/learning/profiles/{profile_id}`: the profile and its status. */
490
+ get(profileId, params, options) {
491
+ return this._request(() => ({
492
+ method: 'GET',
493
+ path: `/v1/learning/profiles/${pathParam(profileId)}`,
494
+ retrySafe: true,
495
+ query: params,
496
+ options,
497
+ }));
498
+ }
499
+ /** `GET /v1/learning/profiles/active`: the active profile, or null when none is. */
500
+ active(params, options) {
501
+ return this._request(() => ({
502
+ method: 'GET',
503
+ path: '/v1/learning/profiles/active',
504
+ retrySafe: true,
505
+ query: params,
506
+ answer: 'nullable',
507
+ options,
508
+ }));
509
+ }
510
+ /** `GET /v1/learning/profiles/history`: the activation history. */
511
+ history(params, options) {
512
+ return this._request(() => ({
513
+ method: 'GET',
514
+ path: '/v1/learning/profiles/history',
515
+ retrySafe: true,
516
+ query: params,
517
+ answer: 'array',
518
+ options,
519
+ }));
520
+ }
521
+ /** `POST /v1/learning/profiles/{profile_id}/activate`. Not retried automatically. */
522
+ activate(profileId, params, options) {
523
+ return this._request(() => ({
524
+ method: 'POST',
525
+ path: `/v1/learning/profiles/${pathParam(profileId)}/activate`,
526
+ retrySafe: false,
527
+ body: params ?? {},
528
+ options,
529
+ }));
530
+ }
531
+ /** `POST /v1/learning/profiles/deactivate`: null when no profile was active. Not retried automatically. */
532
+ deactivate(params, options) {
533
+ return this._request(() => ({
534
+ method: 'POST',
535
+ path: '/v1/learning/profiles/deactivate',
536
+ retrySafe: false,
537
+ body: params ?? {},
538
+ answer: 'nullable',
539
+ options,
540
+ }));
541
+ }
542
+ /** `POST /v1/learning/profiles/rollback`. Not retried automatically. */
543
+ rollback(params, options) {
544
+ return this._request(() => ({
545
+ method: 'POST',
546
+ path: '/v1/learning/profiles/rollback',
547
+ retrySafe: false,
548
+ body: params ?? {},
549
+ options,
550
+ }));
551
+ }
552
+ }
553
+ /** The `/v1/learning` routes: offline evaluation and ranking profiles. */
554
+ export class Learning extends Resource {
555
+ profiles;
556
+ constructor(core, raw) {
557
+ super(core, raw);
558
+ this.profiles = new LearningProfiles(core, raw);
559
+ }
560
+ /** `POST /v1/learning/evaluate`. Not retried automatically. */
561
+ evaluate(params, options) {
562
+ return this._request(() => ({
563
+ method: 'POST',
564
+ path: '/v1/learning/evaluate',
565
+ retrySafe: false,
566
+ body: params ?? {},
567
+ options,
568
+ }));
569
+ }
570
+ /** `POST /v1/learning/evaluate-full-retrieval`. Not retried automatically. */
571
+ evaluateFullRetrieval(params, options) {
572
+ return this._request(() => ({
573
+ method: 'POST',
574
+ path: '/v1/learning/evaluate-full-retrieval',
575
+ retrySafe: false,
576
+ body: params ?? {},
577
+ options,
578
+ }));
579
+ }
580
+ }
581
+ // The helpers (sdks/CONTRACT.md, Helpers) live on the parsed form only: the raw view has
582
+ // every operation and no helpers. Each poll is an ordinary call, with its retries and errors.
583
+ /** `client.events`: the event routes and `waitForExtraction()`. */
584
+ export class EventsWithHelpers extends Events {
585
+ /**
586
+ * Poll the event's extraction status until it is no longer `pending` or `running`.
587
+ *
588
+ * Polls `GET /v1/events/{event_id}/extraction-status` at once and then every
589
+ * `interval` milliseconds (2 000), and returns the first status that is not `pending`
590
+ * or `running`: `complete`, `failed` (returned, not thrown), or a status this SDK does
591
+ * not know yet. When `timeout` milliseconds (300 000) run out first, throws
592
+ * `WaitTimeoutError` with the last status as `lastStatus`; `timeout` is a deadline that
593
+ * also bounds each poll and its retries (see `HelperOptions`). Aborting `signal` stops
594
+ * the helper and any pending poll or retry. Each poll is an ordinary call, with the
595
+ * client's retries and errors, and counts against the key's request rate limit like any
596
+ * other call, so many waits at once can slow the key's other calls. A job can stay
597
+ * `pending` until the next batch flush; `extractions.process()` runs the due jobs.
598
+ */
599
+ async waitForExtraction(eventId, options) {
600
+ const { timeout = 300_000, interval = 2_000, signal = null } = ownProperties(options);
601
+ const core = this._core;
602
+ const deadline = helperDeadline(core.now(), timeout, interval);
603
+ let lastStatus = null;
604
+ for (;;) {
605
+ let status;
606
+ try {
607
+ status = await this._request(() => ({
608
+ ...extractionStatusCall(eventId, { signal }),
609
+ deadline,
610
+ }));
611
+ }
612
+ catch (error) {
613
+ // Only a poll the deadline stopped throws WaitTimeoutError; its own error is the cause.
614
+ if (!(error instanceof WaitTimeoutError))
615
+ throw error;
616
+ const last = lastStatus === null ? 'none' : JSON.stringify(lastStatus.status);
617
+ throw withCause(new WaitTimeoutError(`The extraction did not finish within ${timeout} ms: ${error.message}. The last ` +
618
+ `status read was ${last}.`, { lastStatus }), error.cause);
619
+ }
620
+ if (!WORKING.has(status.status))
621
+ return status;
622
+ lastStatus = status;
623
+ const wait = helperWait(core.now(), deadline, interval);
624
+ if (wait === null) {
625
+ throw new WaitTimeoutError(`The extraction did not finish within ${timeout} ms; its last status was ` +
626
+ `${JSON.stringify(status.status)}.`, { lastStatus: status });
627
+ }
628
+ await core.sleep(wait, signal);
629
+ }
630
+ }
631
+ }
632
+ /** `client.nodes`: the node routes and `scanAll()`. */
633
+ export class NodesWithHelpers extends Nodes {
634
+ /**
635
+ * Yield every node `scan()` reaches, one page after another.
636
+ *
637
+ * While a page's `has_more` is true, sends its `next_cursor` as the next `after_id`,
638
+ * with the other parameters unchanged; `limit` is the page size. Each page is an
639
+ * ordinary `scan()` call with `options`, sent as soon as the previous page is read, and
640
+ * counts against the key's request rate limit: a large `limit` (up to 1 000) needs fewer
641
+ * pages. A page whose `has_more` is true without a new `next_cursor` throws
642
+ * `NenaviError`, so a scan never ends early without saying so.
643
+ *
644
+ * @example
645
+ * for await (const node of client.nodes.scanAll({ user_id: 'user-1', limit: 1000 })) {
646
+ * console.log(node.id);
647
+ * }
648
+ */
649
+ async *scanAll(params, options) {
650
+ const given = ownProperties(params);
651
+ let cursor = given.after_id;
652
+ for (;;) {
653
+ const page = await this.scan({ ...given, after_id: cursor }, options);
654
+ for (const node of page.nodes ?? [])
655
+ yield node;
656
+ if (!page.has_more)
657
+ return;
658
+ if (page.next_cursor === undefined ||
659
+ page.next_cursor === null ||
660
+ String(page.next_cursor) === String(cursor)) {
661
+ // Following it would read the same page forever; stopping quietly would hide the
662
+ // nodes the scan did not reach.
663
+ throw new NenaviError('The scan page says there are more nodes but gives no new next_cursor, so the ' +
664
+ 'scan cannot continue.');
665
+ }
666
+ cursor = page.next_cursor;
667
+ }
668
+ }
669
+ }
670
+ /** `client.reingest`: the re-ingest routes and `run()`. */
671
+ export class ReingestWithHelpers extends Reingest {
672
+ /**
673
+ * Start a re-ingest run and poll it until its `state` is final.
674
+ *
675
+ * Sends `start()` (`dry_run: false`), then polls `get()` every `interval` milliseconds
676
+ * (5 000) and returns the first status whose `state` is not `pending` or `running`:
677
+ * `complete`, `failed` (returned, not thrown), or a state this SDK does not know yet.
678
+ * When nothing needs re-deriving, the service's `200` answer is returned as it is. A
679
+ * `409` `reingest_running` throws `ConflictError`. When `timeout` milliseconds
680
+ * (3 600 000) run out first, throws `WaitTimeoutError` with the last status as
681
+ * `lastStatus`; the run itself goes on. `timeout` is a deadline that also bounds each
682
+ * poll and its retries (see `HelperOptions`); it never prevents or cuts short the start,
683
+ * which has the client's own timeout. Aborting `signal` stops the helper and any pending
684
+ * poll, not the run. A poll that fails throws that call's error while the run goes on,
685
+ * with the last status read before it as `lastStatus`: its `run_id` lets the caller go
686
+ * on polling with `get()` instead of calling `run()` again, which throws `ConflictError`
687
+ * (`reingest_running`) until the run ends.
688
+ *
689
+ * A run takes at most `limit` memories, so a `complete` run can leave some for later
690
+ * (`remaining` above 0): calling `run()` again with the same parameters continues it.
691
+ */
692
+ async run(params, options) {
693
+ const { timeout = 3_600_000, interval = 5_000, signal = null } = ownProperties(options);
694
+ const core = this._core;
695
+ const deadline = helperDeadline(core.now(), timeout, interval);
696
+ let status = await this.start(params, { signal });
697
+ while (status.run_id !== null && status.run_id !== undefined && WORKING.has(status.state)) {
698
+ const wait = helperWait(core.now(), deadline, interval);
699
+ if (wait === null) {
700
+ throw new WaitTimeoutError(`The re-ingest run ${status.run_id} did not finish within ${timeout} ms; its ` +
701
+ `last state was ${JSON.stringify(status.state)}.`, { lastStatus: status });
702
+ }
703
+ await core.sleep(wait, signal);
704
+ const runId = status.run_id;
705
+ try {
706
+ status = await this._request(() => ({
707
+ ...reingestGetCall(runId, { signal }),
708
+ deadline,
709
+ }));
710
+ }
711
+ catch (error) {
712
+ // A poll the deadline stopped throws WaitTimeoutError; its own error is the cause.
713
+ if (error instanceof WaitTimeoutError) {
714
+ throw withCause(new WaitTimeoutError(`The re-ingest run ${runId} did not finish within ${timeout} ms: ` +
715
+ `${error.message}. Its last state was ${JSON.stringify(status.state)}.`, { lastStatus: status }), error.cause);
716
+ }
717
+ // The run goes on; without its id the caller could only call run() again, which
718
+ // the service refuses with 409 until the run ends. An abort keeps its own reason.
719
+ if (error instanceof NenaviError && !signal?.aborted)
720
+ error.lastStatus = status;
721
+ throw error;
722
+ }
723
+ }
724
+ return status;
725
+ }
726
+ }
727
+ /** The operations, in the parsed form (`Nenavi`) or the raw form (`withRawResponse`). */
728
+ export class NenaviMethods extends Resource {
729
+ events;
730
+ nodes;
731
+ reingest;
732
+ claims;
733
+ aliasProposals;
734
+ materializations;
735
+ extractions;
736
+ assertions;
737
+ quantities;
738
+ retrievals;
739
+ relevance;
740
+ answerCitations;
741
+ learning;
742
+ constructor(core, raw) {
743
+ super(core, raw);
744
+ this.events = new Events(core, raw);
745
+ this.nodes = new Nodes(core, raw);
746
+ this.reingest = new Reingest(core, raw);
747
+ this.claims = new Claims(core, raw);
748
+ this.aliasProposals = new AliasProposals(core, raw);
749
+ this.materializations = new Materializations(core, raw);
750
+ this.extractions = new Extractions(core, raw);
751
+ this.assertions = new Assertions(core, raw);
752
+ this.quantities = new Quantities(core, raw);
753
+ this.retrievals = new Retrievals(core, raw);
754
+ this.relevance = new Relevance(core, raw);
755
+ this.answerCitations = new AnswerCitations(core, raw);
756
+ this.learning = new Learning(core, raw);
757
+ }
758
+ /** `GET /v1/health`. Sends no key, and works on a client built without one. */
759
+ health(options) {
760
+ return this._request(() => ({
761
+ method: 'GET',
762
+ path: '/v1/health',
763
+ retrySafe: true,
764
+ auth: false,
765
+ options,
766
+ }));
767
+ }
768
+ /** `GET /v1/usage`: this month's usage and the project's quota. */
769
+ usage(options) {
770
+ return this._request(() => ({ method: 'GET', path: '/v1/usage', retrySafe: true, options }));
771
+ }
772
+ /** `GET /v1/stats`: event and node counts. */
773
+ stats(params, options) {
774
+ return this._request(() => ({
775
+ method: 'GET',
776
+ path: '/v1/stats',
777
+ retrySafe: true,
778
+ query: params,
779
+ options,
780
+ }));
781
+ }
782
+ /**
783
+ * `POST /v1/store`: store one memory.
784
+ *
785
+ * Never retried automatically: a retry would store and extract the text again and count
786
+ * twice against the monthly limits.
787
+ */
788
+ store(params, options) {
789
+ return this._request(() => ({
790
+ method: 'POST',
791
+ path: '/v1/store',
792
+ retrySafe: false,
793
+ body: params ?? {},
794
+ options,
795
+ }));
796
+ }
797
+ /**
798
+ * `POST /v1/ingest`: store a message and queue its extraction.
799
+ *
800
+ * Never retried automatically: a retry would store and extract the text again and count
801
+ * twice against the monthly limits.
802
+ */
803
+ ingest(params, options) {
804
+ return this._request(() => ({
805
+ method: 'POST',
806
+ path: '/v1/ingest',
807
+ retrySafe: false,
808
+ body: params ?? {},
809
+ options,
810
+ }));
811
+ }
812
+ /**
813
+ * `POST /v1/ingest/fast`: store a batch of sources without waiting for extraction.
814
+ *
815
+ * Every call sends an `Idempotency-Key`: `options.idempotencyKey` when given, else a new
816
+ * random UUID. Retries of the call send the same key, so the service answers a retry
817
+ * with the first attempt's event ids instead of storing the batch again. To retry by
818
+ * hand after an error, pass the error's `idempotencyKey`. An aborted `signal` rejects
819
+ * with the signal's reason, which carries no key, so when you pass a `signal`, pass
820
+ * your own `idempotencyKey` too and reuse it to retry an aborted call.
821
+ */
822
+ ingestFast(params, options) {
823
+ return this._request(() => ({
824
+ method: 'POST',
825
+ path: '/v1/ingest/fast',
826
+ retrySafe: true,
827
+ body: params ?? {},
828
+ idempotencyKey: callerKey(options) ?? crypto.randomUUID(),
829
+ options,
830
+ }));
831
+ }
832
+ /**
833
+ * `POST /v1/retrieve`: retrieve the memories that answer a query.
834
+ *
835
+ * Retrieved memory is untrusted input: stored text can carry instructions meant for the
836
+ * model that later reads it, so treat it as data, not instructions. Not retried
837
+ * automatically, because each call writes a retrieval receipt.
838
+ */
839
+ retrieve(params, options) {
840
+ return this._request(() => ({
841
+ method: 'POST',
842
+ path: '/v1/retrieve',
843
+ retrySafe: false,
844
+ body: params ?? {},
845
+ options,
846
+ }));
847
+ }
848
+ /** `GET /v1/graph`: the user's nodes and edges. */
849
+ graph(params, options) {
850
+ return this._request(() => ({
851
+ method: 'GET',
852
+ path: '/v1/graph',
853
+ retrySafe: true,
854
+ query: params,
855
+ options,
856
+ }));
857
+ }
858
+ /** `POST /v1/organize`: run organizing jobs within a time budget. Not retried automatically. */
859
+ organize(params, options) {
860
+ return this._request(() => ({
861
+ method: 'POST',
862
+ path: '/v1/organize',
863
+ retrySafe: false,
864
+ body: params ?? {},
865
+ options,
866
+ }));
867
+ }
868
+ }
869
+ /**
870
+ * Client for the Nenavi Cloud memory API, for server-side code.
871
+ *
872
+ * The key comes from `apiKey`, else `NENAVI_API_KEY`; the base URL from `baseURL`, else
873
+ * `NENAVI_BASE_URL`, else `https://api.prismemory.com`. A client built without a key can
874
+ * call only `health()`. Never ship the key to a browser.
875
+ *
876
+ * Retrieved memory is untrusted input: treat retrieved text as data, not instructions.
877
+ */
878
+ export class Nenavi extends NenaviMethods {
879
+ #raw;
880
+ constructor(options = {}) {
881
+ const core = new Core(options);
882
+ super(core, false);
883
+ this.events = new EventsWithHelpers(core, false);
884
+ this.nodes = new NodesWithHelpers(core, false);
885
+ this.reingest = new ReingestWithHelpers(core, false);
886
+ }
887
+ /** The base URL the client sends to. */
888
+ get baseURL() {
889
+ return this._core.baseURL;
890
+ }
891
+ /** The same methods, returning a RawResponse with the status, headers and request id. */
892
+ get withRawResponse() {
893
+ this.#raw ??= new NenaviMethods(this._core, true);
894
+ return this.#raw;
895
+ }
896
+ }