@polycode-projects/the-mechanical-code-talker 5.0.46 → 6.0.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.
Files changed (34) hide show
  1. package/README.md +27 -0
  2. package/bin/tmct.mjs +61 -0
  3. package/package.json +14 -2
  4. package/src/adapters/memory/backends-exports.mjs +8 -0
  5. package/src/adapters/memory/core.mjs +812 -175
  6. package/src/adapters/memory/corpus-bands.mjs +155 -0
  7. package/src/adapters/memory/dynamo-circuit-breaker.mjs +266 -0
  8. package/src/adapters/memory/row-backend-dynamo.mjs +315 -0
  9. package/src/adapters/memory/row-backend-memory.mjs +85 -0
  10. package/src/adapters/memory/row-backend.mjs +162 -0
  11. package/src/adapters/memory/rows.mjs +328 -0
  12. package/src/adapters/memory/shacl.mjs +24 -0
  13. package/src/adapters/memory/systemic-failure.mjs +28 -0
  14. package/src/adapters/research-queue-store.mjs +215 -32
  15. package/src/domain/ask.mjs +341 -75
  16. package/src/domain/cli-verbs.mjs +17 -0
  17. package/src/domain/fact-phrase.mjs +40 -0
  18. package/src/domain/news-feed.mjs +42 -4
  19. package/src/domain/phrase-exports.mjs +4 -0
  20. package/src/domain/retrieval-marker.mjs +120 -0
  21. package/src/domain/retrieval-modes.mjs +13 -0
  22. package/src/domain/retrieval-plan.mjs +224 -0
  23. package/src/services/chat-session.mjs +36 -9
  24. package/src/services/chat.mjs +73 -16
  25. package/src/services/corpus-loader.mjs +222 -0
  26. package/src/services/extract-facts.mjs +244 -33
  27. package/src/services/init.mjs +15 -5
  28. package/src/services/news.mjs +4 -2
  29. package/src/services/subgraph-retrieval.mjs +332 -0
  30. package/src/surfaces/web/http-row-backend.mjs +150 -0
  31. package/src/surfaces/web/memory-ask-browser.bundle.js +134 -131
  32. package/src/surfaces/web/news-browser-entry.mjs +6 -2
  33. package/src/tools/handlers/tmct-ingest.mjs +3 -1
  34. package/src/tools/memory-backend-conformance.mjs +238 -0
@@ -0,0 +1,332 @@
1
+ // subgraph-retrieval.mjs — runs a retrieval plan against corpus band
2
+ // partitions and hands back the rows a turn can reason over, plus the metrics
3
+ // that say how complete the answer is.
4
+ //
5
+ // The whole point is that a smaller budget returns a prefix of a bigger one's
6
+ // answer rather than a different answer. That holds because the traversal order
7
+ // is fixed before the first read: terms sorted, bands sorted, each page sorted
8
+ // by row key, and every response folded in the order it was issued rather than
9
+ // the order it came back. Concurrency changes the wall time and nothing else.
10
+ //
11
+ // Running out of budget degrades. It never throws: the caller gets the rows
12
+ // that arrived, `bounded: true`, and the name of the budget that stopped it. A
13
+ // timeout is a smaller subgraph, never a guess.
14
+
15
+ import {
16
+ buildRetrievalPlan, expandedTerms, ancestryTerms,
17
+ } from "../domain/retrieval-plan.mjs";
18
+ import { loadLexicon } from "../domain/grammar/lexicon.mjs";
19
+ import { isSystemicFailure } from "../adapters/memory/systemic-failure.mjs";
20
+ import { SUPPLEMENTED_MODE, SEED_SESSION_MODE } from "../domain/retrieval-modes.mjs";
21
+
22
+ export { isSystemicFailure, SUPPLEMENTED_MODE, SEED_SESSION_MODE };
23
+
24
+ /** The retrieval budgets, set from what scripts/corpus-bands/calibrate-retrieval.mjs
25
+ * measured over the committed WordNet and ConceptNet corpora. Changing one is
26
+ * a code change, deliberately: a request cannot widen its own read.
27
+ *
28
+ * Each budget degrades rather than failing. `fuzzyVariantsPerTerm` and
29
+ * `hopDepth` cut the plan before any read; `rowsPerQueryPage` paginates;
30
+ * `totalRows`, `totalQueries` and `wallTimeMs` stop the traversal and mark the
31
+ * subgraph bounded; `inFlightQueries` only queues.
32
+ *
33
+ * What each number came from:
34
+ *
35
+ * fuzzyVariantsPerTerm the widest measured tie was five candidates at the
36
+ * same distance; below that the cap cuts alphabetically
37
+ * and drops real candidates, so six clears every case
38
+ * hopDepth the engine's own alias chase is two hops
39
+ * rowsPerQueryPage the heaviest single term returned 92 rows, so 200
40
+ * reads every measured term in one round trip
41
+ * totalRows folding 1,000 rows into a payload costs about 12 ms
42
+ * and about 1 MB; 5,000 costs 44 ms and 5.3 MB, which
43
+ * is a third of the whole bundled seed for one question
44
+ * totalQueries eight rounds of eight in flight, about 80 ms against
45
+ * a store answering in the 10 ms class. A wide turn
46
+ * spends 20-30 of these on its own terms across three
47
+ * bands, and the rest goes to the subClassOf chain
48
+ * wallTimeMs the latency the turn surface can spend on reads
49
+ * inFlightQueries eight, so a turn cannot monopolize table throughput
50
+ * queryRetries two retries at 25 ms doubling spends at most 75 ms of
51
+ * backoffBaseMs the 300 ms on waiting, leaving 225 ms of reading
52
+ *
53
+ * The measurement's headline is worth knowing when reading a turn's metrics: a
54
+ * grounded question over a corpus this dense wants thousands of Queries if
55
+ * nothing stops it, because the subClassOf closure branches rather than
56
+ * chaining. Every grounded turn comes back bounded, and the marker says so.
57
+ * Reads are ordered so what a budget takes is always the least targeted part. */
58
+ export const RETRIEVAL_BUDGETS = Object.freeze({
59
+ fuzzyVariantsPerTerm: 6,
60
+ hopDepth: 2,
61
+ rowsPerQueryPage: 200,
62
+ totalRows: 1000,
63
+ totalQueries: 64,
64
+ wallTimeMs: 300,
65
+ inFlightQueries: 8,
66
+ queryRetries: 2,
67
+ backoffBaseMs: 25,
68
+ });
69
+
70
+ /** Is fuzzy variant expansion on for this turn? Most specific setting wins:
71
+ * the request, then the environment, then the config file, then the default,
72
+ * which is on. */
73
+ export function resolveFuzzyMode({ request, env = process.env, config } = {}) {
74
+ if (typeof request === "boolean") return request;
75
+ const fromEnv = env?.TMCT_RETRIEVAL_FUZZY;
76
+ if (fromEnv === "0" || fromEnv === "false") return false;
77
+ if (fromEnv === "1" || fromEnv === "true") return true;
78
+ if (typeof config === "boolean") return config;
79
+ return true;
80
+ }
81
+
82
+ const sleepFor = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
83
+
84
+ /** A term query over a DynamoDB document client, in the band partition layout:
85
+ * partition `corpus:<band>`, sort key `fact#<term>#<rowKey>`, so one term is
86
+ * one `begins_with` Query. Pass the result as `queryTerm`. */
87
+ export function termQueryOverDocumentClient({ client, tableName, pageSize }) {
88
+ return async function queryTerm({ band, term, exclusiveStartKey, limit }) {
89
+ const response = await client.query({
90
+ TableName: tableName,
91
+ KeyConditionExpression: "pk = :pk AND begins_with(sk, :sk)",
92
+ ExpressionAttributeValues: { ":pk": `corpus:${band}`, ":sk": `fact#${term}#` },
93
+ Limit: limit ?? pageSize,
94
+ ...(exclusiveStartKey ? { ExclusiveStartKey: exclusiveStartKey } : {}),
95
+ });
96
+ return { rows: response?.Items || [], lastEvaluatedKey: response?.LastEvaluatedKey ?? null };
97
+ };
98
+ }
99
+
100
+ const byRowKey = (a, b) => (a.rowKey < b.rowKey ? -1 : a.rowKey > b.rowKey ? 1 : 0);
101
+
102
+ /** One Query, with exponential backoff on a systemic failure and no retry on
103
+ * anything else. Backoff happens inside the wall budget: when the next sleep
104
+ * would spend more time than retrieval has left, the read is given up instead
105
+ * of waited on. */
106
+ async function queryWithBackoff(request, run) {
107
+ let delay = run.budgets.backoffBaseMs;
108
+ for (let attempt = 0; ; attempt += 1) {
109
+ run.queries += 1;
110
+ try {
111
+ const response = await run.queryTerm(request);
112
+ return { rows: [...(response?.rows || [])].sort(byRowKey), lastEvaluatedKey: response?.lastEvaluatedKey ?? null };
113
+ } catch (error) {
114
+ run.failedQueries += 1;
115
+ if (!isSystemicFailure(error)) return { rows: [], lastEvaluatedKey: null, failed: true };
116
+ run.systemicFailures += 1;
117
+ const spent = run.now() - run.startedAt;
118
+ if (attempt >= run.budgets.queryRetries || spent + delay >= run.budgets.wallTimeMs) {
119
+ return { rows: [], lastEvaluatedKey: null, failed: true };
120
+ }
121
+ run.throttles += 1;
122
+ await run.sleep(delay);
123
+ delay *= 2;
124
+ }
125
+ }
126
+ }
127
+
128
+ /** The budget that has already stopped this run, or null while it can carry
129
+ * on. Checked between chunks, so a chunk already in flight finishes and its
130
+ * rows are folded in issue order. */
131
+ function trippedBudget(run) {
132
+ if (run.rows.length >= run.budgets.totalRows) return "totalRows";
133
+ if (run.queries >= run.budgets.totalQueries) return "totalQueries";
134
+ if (run.now() - run.startedAt >= run.budgets.wallTimeMs) return "wallTimeMs";
135
+ return null;
136
+ }
137
+
138
+ /** Fold one response into the run. Rows land in issue order, deduped by key,
139
+ * and the row budget cuts inside the page rather than after it, so the same
140
+ * inputs under a smaller budget stop at exactly the same row. */
141
+ function foldResponse(response, run) {
142
+ const fresh = [];
143
+ for (const row of response.rows) {
144
+ if (!row?.rowKey || run.seenRowKeys.has(row.rowKey)) continue;
145
+ if (run.rows.length >= run.budgets.totalRows) {
146
+ run.tripped = run.tripped ?? "totalRows";
147
+ break;
148
+ }
149
+ run.seenRowKeys.add(row.rowKey);
150
+ run.rows.push(row);
151
+ fresh.push(row);
152
+ }
153
+ if (response.failed) run.degraded = true;
154
+ return fresh;
155
+ }
156
+
157
+ /** Run one wave of term reads to exhaustion or to a budget, and return the rows
158
+ * it brought back. Pagination re-queues the same term behind the rest of the
159
+ * wave, which keeps the issue order a pure function of the plan. */
160
+ async function runWave(requests, run) {
161
+ const fresh = [];
162
+ let pending = requests;
163
+ while (pending.length) {
164
+ const stoppedBy = trippedBudget(run);
165
+ if (stoppedBy) { run.tripped = run.tripped ?? stoppedBy; break; }
166
+ const chunk = pending.slice(0, run.budgets.inFlightQueries);
167
+ const rest = pending.slice(run.budgets.inFlightQueries);
168
+ for (const request of chunk) run.readTerms.add(request.term);
169
+ const responses = await Promise.all(chunk.map((request) => queryWithBackoff(request, run)));
170
+ const continuations = [];
171
+ for (let i = 0; i < chunk.length; i += 1) {
172
+ fresh.push(...foldResponse(responses[i], run));
173
+ if (responses[i].lastEvaluatedKey) {
174
+ continuations.push({ ...chunk[i], exclusiveStartKey: responses[i].lastEvaluatedKey });
175
+ }
176
+ }
177
+ pending = [...rest, ...continuations];
178
+ }
179
+ return fresh;
180
+ }
181
+
182
+ /** Every (band, term) read one wave issues, in a fixed order: term first so a
183
+ * cut lands on whole terms wherever possible, band second. */
184
+ function requestsFor(terms, run) {
185
+ const requests = [];
186
+ for (const term of terms) {
187
+ if (run.plannedTerms.has(term)) continue;
188
+ run.plannedTerms.add(term);
189
+ for (const band of run.bands) requests.push({ band, term, limit: run.budgets.rowsPerQueryPage });
190
+ }
191
+ return requests;
192
+ }
193
+
194
+ /** Read a wave and record what phase paid for it, so a run can say where its
195
+ * Queries went. */
196
+ async function runPhase(terms, run, phase) {
197
+ const queriesBefore = run.queries;
198
+ const rowsBefore = run.rows.length;
199
+ const fresh = await runWave(requestsFor(terms, run), run);
200
+ run.queriesByPhase[phase] += run.queries - queriesBefore;
201
+ run.rowsByPhase[phase] += run.rows.length - rowsBefore;
202
+ return fresh;
203
+ }
204
+
205
+ /** Walk the subClassOf chain above `rows` until it closes. This runs before
206
+ * each wider hop because the inheritance lanes read exactly these rows, so a
207
+ * budget that stops the traversal takes the widest reads and not the ones an
208
+ * answer is most likely to stand on. A term is asked for once per turn, so a
209
+ * cycle in the taxonomy cannot loop here. */
210
+ async function chaseAncestry(rows, run) {
211
+ const found = [];
212
+ let terms = ancestryTerms(rows, { seen: run.plannedTerms });
213
+ while (terms.length && !run.tripped) {
214
+ const fresh = await runPhase(terms, run, "ancestry");
215
+ found.push(...fresh);
216
+ terms = ancestryTerms(fresh, { seen: run.plannedTerms });
217
+ }
218
+ return found;
219
+ }
220
+
221
+ /** Retrieve the corpus subgraph one turn can reach.
222
+ *
223
+ * `queryTerm({band, term, exclusiveStartKey, limit})` resolves to
224
+ * `{rows, lastEvaluatedKey}`. The read is injected, so the caller decides
225
+ * whether it comes from a document client, an HTTP route or a fixture.
226
+ *
227
+ * Returns `{rows, metrics, plan}`. `metrics.mode` and `metrics.bounded` are
228
+ * what an answer's honesty marker reads: `bounded` is true when a budget
229
+ * stopped the traversal or a read failed, which are the two ways the subgraph
230
+ * can hold less than the corpus does. */
231
+ export async function retrieveSubgraph({
232
+ text,
233
+ bands = [],
234
+ queryTerm = null,
235
+ fuzzy = true,
236
+ skip = false,
237
+ lexicon = loadLexicon(),
238
+ vocabulary = null,
239
+ budgets: budgetOverrides = null,
240
+ now = () => Date.now(),
241
+ sleep = sleepFor,
242
+ }) {
243
+ // A partial override keeps every budget it did not name. A missing cap would
244
+ // otherwise read as no cap, which is the one thing this module must never do.
245
+ const budgets = budgetOverrides ? { ...RETRIEVAL_BUDGETS, ...budgetOverrides } : RETRIEVAL_BUDGETS;
246
+ const startedAt = now();
247
+ const plan = buildRetrievalPlan({
248
+ text, fuzzy, lexicon, vocabulary,
249
+ hopDepth: budgets.hopDepth,
250
+ fuzzyVariantsPerTerm: budgets.fuzzyVariantsPerTerm,
251
+ });
252
+ const sortedBands = [...bands].sort();
253
+
254
+ if (skip || !queryTerm || sortedBands.length === 0) {
255
+ return {
256
+ rows: [],
257
+ plan,
258
+ metrics: metricsOf({
259
+ plan, bands: sortedBands, mode: SEED_SESSION_MODE, elapsedMs: now() - startedAt,
260
+ }),
261
+ };
262
+ }
263
+
264
+ const run = {
265
+ budgets, queryTerm, now, sleep, startedAt,
266
+ bands: sortedBands,
267
+ rows: [],
268
+ seenRowKeys: new Set(),
269
+ plannedTerms: new Set(), readTerms: new Set(),
270
+ queries: 0,
271
+ failedQueries: 0,
272
+ systemicFailures: 0,
273
+ throttles: 0,
274
+ tripped: null,
275
+ degraded: false,
276
+ hops: 0,
277
+ queriesByPhase: { seed: 0, ancestry: 0, expansion: 0 },
278
+ rowsByPhase: { seed: 0, ancestry: 0, expansion: 0 },
279
+ };
280
+
281
+ // The words the turn actually contained are read before any variant of them.
282
+ // Under a tight query budget that ordering is the difference between a guess
283
+ // spending the read the real term needed and the real term getting it.
284
+ let wave = [
285
+ ...plan.terms.filter((entry) => entry.origin === "exact").map((entry) => entry.term),
286
+ ...plan.terms.filter((entry) => entry.origin === "fuzzy").map((entry) => entry.term),
287
+ ];
288
+ for (let hop = 0; hop <= budgets.hopDepth && wave.length; hop += 1) {
289
+ const fresh = await runPhase(wave, run, hop === 0 ? "seed" : "expansion");
290
+ run.hops = hop;
291
+ const inherited = await chaseAncestry(fresh, run);
292
+ if (run.tripped) break;
293
+ wave = expandedTerms([...fresh, ...inherited], { seen: run.plannedTerms });
294
+ }
295
+
296
+ return {
297
+ rows: run.rows,
298
+ plan,
299
+ metrics: metricsOf({
300
+ plan,
301
+ bands: sortedBands,
302
+ mode: SUPPLEMENTED_MODE,
303
+ elapsedMs: now() - startedAt,
304
+ run,
305
+ }),
306
+ };
307
+ }
308
+
309
+ function metricsOf({ plan, bands, mode, elapsedMs, run = null }) {
310
+ const exactTerms = plan.terms.filter((entry) => entry.origin === "exact").length;
311
+ return {
312
+ mode,
313
+ bounded: Boolean(run && (run.tripped || run.degraded)),
314
+ tripped: run?.tripped ?? null,
315
+ fuzzy: plan.fuzzy,
316
+ bands,
317
+ planTerms: plan.terms.length,
318
+ exactTerms,
319
+ fuzzyTerms: plan.terms.length - exactTerms,
320
+ termsPlanned: run ? run.plannedTerms.size : 0,
321
+ termsRead: run ? run.readTerms.size : 0,
322
+ queries: run?.queries ?? 0,
323
+ rows: run?.rows.length ?? 0,
324
+ hops: run?.hops ?? 0,
325
+ failedQueries: run?.failedQueries ?? 0,
326
+ systemicFailures: run?.systemicFailures ?? 0,
327
+ throttles: run?.throttles ?? 0,
328
+ queriesByPhase: run ? { ...run.queriesByPhase } : { seed: 0, ancestry: 0, expansion: 0 },
329
+ rowsByPhase: run ? { ...run.rowsByPhase } : { seed: 0, ancestry: 0, expansion: 0 },
330
+ elapsedMs,
331
+ };
332
+ }
@@ -0,0 +1,150 @@
1
+ // http-row-backend.mjs — the §3.1 row-backend contract over the row
2
+ // service's HTTP surface (server/row-service/handler.mjs's endpoint table).
3
+ // This is the client half of the seam the DynamoDB backend fills on the
4
+ // storage side. A page or a Node caller constructs one per session and gets
5
+ // the same contract every other backend gives. Only the network can fail.
6
+ //
7
+ // The module is fetch-only and imports nothing node-specific, so it runs
8
+ // unmodified in a browser bundle and in a node test. `fetchImpl` lets a test
9
+ // or an older runtime hand in its own implementation.
10
+
11
+ import {
12
+ ROW_BACKEND_KIND, ROW_BACKEND_CONTRACT_VERSION,
13
+ BackendRejected, BackendUnavailable,
14
+ } from "../../adapters/memory/row-backend.mjs";
15
+
16
+ const SESSION_HEADER = "x-tmct-session";
17
+
18
+ function trimTrailingSlash(value) {
19
+ return value.endsWith("/") ? value.slice(0, -1) : value;
20
+ }
21
+
22
+ /** Reads whatever text the response carries, for the error's own message
23
+ * only. The class decision uses the status code alone (the service's own
24
+ * §3.8 mapping), so a consumer never has to parse a body to know whether a
25
+ * failure is worth retrying. */
26
+ async function responseFailureMessage(response, fallback) {
27
+ try {
28
+ const text = await response.text();
29
+ if (!text) return fallback;
30
+ const parsed = JSON.parse(text);
31
+ return parsed?.error?.message || fallback;
32
+ } catch {
33
+ return fallback;
34
+ }
35
+ }
36
+
37
+ async function throwForStatus(response, fallbackMessage) {
38
+ const status = response.status;
39
+ const message = await responseFailureMessage(response, fallbackMessage);
40
+ if (status === 400 || status === 413) throw new BackendRejected(message, { status });
41
+ // 429 (mutation rate), 507 (table cap), and any 5xx (503 is the handler's
42
+ // own mapping for a backend-level BackendUnavailable; 500 is an
43
+ // unexpected handler fault) all mean the store refused or failed to
44
+ // serve. They share one retryable bucket, decided by status, never by
45
+ // matching on message text.
46
+ throw new BackendUnavailable(message, { status });
47
+ }
48
+
49
+ async function runFetch(fetchImpl, url, init, networkFailureMessage) {
50
+ try {
51
+ return await fetchImpl(url, init);
52
+ } catch (error) {
53
+ throw new BackendUnavailable(networkFailureMessage, { cause: error });
54
+ }
55
+ }
56
+
57
+ /** One retry, on a 5xx only, for the one call the spec singles out.
58
+ * `deleteAll`'s purge is query-then-mark and idempotent, so a retried
59
+ * DELETE just re-marks whatever the first attempt already reached; it
60
+ * never double-applies. Every other mutation gets one attempt only:
61
+ * retrying a PUT or a keyed DELETE past a 5xx is a caller decision, not
62
+ * this backend's. */
63
+ async function fetchWithOneRetryOn5xx(fetchImpl, url, init, networkFailureMessage) {
64
+ const first = await runFetch(fetchImpl, url, init, networkFailureMessage);
65
+ if (first.status < 500) return first;
66
+ return runFetch(fetchImpl, url, init, networkFailureMessage);
67
+ }
68
+
69
+ /** `createHttpRowBackend({ apiBase, sessionKey, fetchImpl })`: a §3.1 row
70
+ * backend over the row service at `apiBase` (same-origin, no trailing
71
+ * slash needed), scoped to `sessionKey` (a v4 UUID the caller minted).
72
+ * `fetchImpl` defaults to the ambient `fetch`, so a page never has to pass
73
+ * one. A test points it at a running `local.mjs` double instead. */
74
+ export function createHttpRowBackend({ apiBase, sessionKey, fetchImpl = fetch } = {}) {
75
+ if (typeof apiBase !== "string" || !apiBase) throw new TypeError("createHttpRowBackend needs an apiBase URL");
76
+ if (typeof sessionKey !== "string" || !sessionKey) throw new TypeError("createHttpRowBackend needs a sessionKey");
77
+ if (typeof fetchImpl !== "function") throw new TypeError("createHttpRowBackend needs a fetchImpl(url, init) function, or an ambient fetch");
78
+
79
+ const base = trimTrailingSlash(apiBase);
80
+ let closed = false;
81
+
82
+ const assertOpen = () => {
83
+ if (closed) throw new BackendUnavailable("this row backend was closed and can no longer be used");
84
+ };
85
+
86
+ const jsonHeaders = { "content-type": "application/json" };
87
+ const sessionReadHeaders = { [SESSION_HEADER]: sessionKey };
88
+
89
+ async function getJson(path, { headers = {} } = {}) {
90
+ const response = await runFetch(fetchImpl, `${base}${path}`, { headers }, "could not reach the row service");
91
+ if (response.status === 404) return { notFound: true };
92
+ if (!response.ok) await throwForStatus(response, `GET ${path} failed`);
93
+ return { value: await response.json() };
94
+ }
95
+
96
+ async function mutate(path, { method, body }, { retryOn5xx = false } = {}) {
97
+ const init = { method, headers: jsonHeaders, body: JSON.stringify(body) };
98
+ const response = retryOn5xx
99
+ ? await fetchWithOneRetryOn5xx(fetchImpl, `${base}${path}`, init, "could not reach the row service")
100
+ : await runFetch(fetchImpl, `${base}${path}`, init, "could not reach the row service");
101
+ if (!response.ok) await throwForStatus(response, `${method} ${path} failed`);
102
+ }
103
+
104
+ return {
105
+ kind: ROW_BACKEND_KIND,
106
+ contractVersion: ROW_BACKEND_CONTRACT_VERSION,
107
+
108
+ async readRows() {
109
+ assertOpen();
110
+ const result = await getJson("/api/rows", { headers: sessionReadHeaders });
111
+ return result.notFound ? [] : (result.value.rows || []);
112
+ },
113
+
114
+ async readRowsByTerm(term) {
115
+ assertOpen();
116
+ const result = await getJson(`/api/rows?term=${encodeURIComponent(term)}`, { headers: sessionReadHeaders });
117
+ return result.notFound ? [] : (result.value.rows || []);
118
+ },
119
+
120
+ async putRows(rows) {
121
+ assertOpen();
122
+ await mutate(`/api/sessions/${sessionKey}/rows`, { method: "PUT", body: { puts: rows } });
123
+ },
124
+
125
+ async deleteRows(rowKeys) {
126
+ assertOpen();
127
+ await mutate(`/api/sessions/${sessionKey}/rows`, { method: "DELETE", body: { rowKeys } });
128
+ },
129
+
130
+ async deleteAll() {
131
+ assertOpen();
132
+ await mutate(`/api/sessions/${sessionKey}/rows`, { method: "DELETE", body: { all: true } }, { retryOn5xx: true });
133
+ },
134
+
135
+ async readMeta(key) {
136
+ assertOpen();
137
+ const result = await getJson(`/api/meta/${encodeURIComponent(key)}`, { headers: sessionReadHeaders });
138
+ return result.notFound ? null : result.value.value;
139
+ },
140
+
141
+ async putMeta(key, value) {
142
+ assertOpen();
143
+ await mutate(`/api/sessions/${sessionKey}/meta/${encodeURIComponent(key)}`, { method: "PUT", body: { value } });
144
+ },
145
+
146
+ async close() {
147
+ closed = true;
148
+ },
149
+ };
150
+ }