okengine 0.21.0 → 0.21.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 (45) hide show
  1. package/package.json +2 -7
  2. package/src/cli/dev.test.ts +105 -2
  3. package/src/cli/dev.ts +37 -2
  4. package/src/client/create.ts +13 -26
  5. package/src/client/live.ts +44 -101
  6. package/src/client/sse.ts +20 -66
  7. package/src/client/stream.ts +25 -67
  8. package/src/client/transport.ts +28 -73
  9. package/src/client/wire.ts +119 -0
  10. package/src/compiler/aot.ts +3 -32
  11. package/src/compiler/dynamic.ts +13 -11
  12. package/src/compiler/interpret.ts +45 -0
  13. package/src/console/ui-next/dist/assets/{access-page-tIbsiphz.js → access-page-Bgt9bq2r.js} +1 -1
  14. package/src/console/ui-next/dist/assets/{agent-disclosure-CSKumwS2.js → agent-disclosure-B43CXZZR.js} +1 -1
  15. package/src/console/ui-next/dist/assets/{cache-glyph-BCC-DxKT.js → cache-glyph-92uM5MO7.js} +1 -1
  16. package/src/console/ui-next/dist/assets/{call-pii-button-jOmYISdc.js → call-pii-button-DtGVPtcs.js} +1 -1
  17. package/src/console/ui-next/dist/assets/{collapsible-DC2xNaAb.js → collapsible-DN7l6zmC.js} +1 -1
  18. package/src/console/ui-next/dist/assets/{duration-tone-CwoV56jn.js → duration-tone-BmIR9FV8.js} +1 -1
  19. package/src/console/ui-next/dist/assets/{flows-page-gT1lsWQK.js → flows-page-BMHs-IzK.js} +1 -1
  20. package/src/console/ui-next/dist/assets/{highlighted-json-C2GZEJNI.js → highlighted-json-BlAEVgNW.js} +1 -1
  21. package/src/console/ui-next/dist/assets/{http-method-BdYjcIrD.js → http-method-BDf7OAHv.js} +1 -1
  22. package/src/console/ui-next/dist/assets/{index-Cul17AcV.js → index-BKpaes3n.js} +3 -3
  23. package/src/console/ui-next/dist/assets/{observability-page-oY9vdYBk.js → observability-page-WnVLI-0j.js} +1 -1
  24. package/src/console/ui-next/dist/assets/{replica-lag-C4QdAF7J.js → replica-lag-B3GLNVfF.js} +1 -1
  25. package/src/console/ui-next/dist/assets/{request-meta-C43DHyld.js → request-meta-DMbnAe3f.js} +1 -1
  26. package/src/console/ui-next/dist/assets/{store-page-CL0D9dOq.js → store-page-KvFDingJ.js} +1 -1
  27. package/src/console/ui-next/dist/assets/{trace-detail-sheet-Dcpo4Us_.js → trace-detail-sheet-Htk8Cm9t.js} +1 -1
  28. package/src/console/ui-next/dist/assets/{tree-expand-toggle-CKJTuv43.js → tree-expand-toggle-CFMPWX4f.js} +1 -1
  29. package/src/console/ui-next/dist/assets/{units-page-1PlT19ft.js → units-page-C4NdNuxP.js} +1 -1
  30. package/src/console/ui-next/dist/assets/{vault-page-BwZ9YjTW.js → vault-page-CBYl0LW_.js} +1 -1
  31. package/src/console/ui-next/dist/index.html +1 -1
  32. package/src/elements/store/sql-session.ts +20 -4
  33. package/src/kernel/app.ts +9 -2
  34. package/src/kernel/client-descriptor.test.ts +78 -0
  35. package/src/kernel/client-descriptor.ts +23 -0
  36. package/src/kernel/errors-text.ts +99 -0
  37. package/src/kernel/errors.ts +90 -138
  38. package/src/kernel/fx-sql-handle.ts +305 -0
  39. package/src/kernel/fx.ts +37 -329
  40. package/src/kernel/json-result.ts +59 -0
  41. package/src/kernel/project-out.ts +6 -1
  42. package/src/okid-extended.ts +175 -0
  43. package/src/okid-shared.ts +103 -0
  44. package/src/okid.ts +30 -213
  45. package/src/release/build-lib.ts +9 -0
@@ -236,6 +236,9 @@ export const fail: FailFn = failImpl as FailFn;
236
236
  * Permanent error registry. Codes are stable within their domain range after
237
237
  * the domain-range renumber; each entry declares `domain` for range guards.
238
238
  *
239
+ * Cause/fix templates load from {@link OKE_ERROR_TEXT} on first read so the
240
+ * edge profile does not carry the English strings.
241
+ *
239
242
  * Ranges:
240
243
  * - `1000–1099` — Kernel (Flow / Trigger / Gate-posture)
241
244
  * - `1100–1199` — Store
@@ -248,168 +251,117 @@ export const fail: FailFn = failImpl as FailFn;
248
251
  * - `1800–1899` — MCP + Tenancy
249
252
  * - `1900–1999` — Compiler / Manifest
250
253
  */
251
- export const OKE_ERRORS = {
254
+ const OKE_ERROR_ROWS = {
252
255
  /** Flow reads a store resource not listed in `effects.reads`. */
253
- UNDECLARED_READ: {
254
- code: 1001,
255
- domain: "kernel",
256
- cause: 'Flow "{flow}" reads "{resource}" without declaring it.',
257
- fix: 'Add "{resource}" to this flow\'s effects.reads.',
258
- },
256
+ UNDECLARED_READ: { code: 1001, domain: "kernel" },
259
257
  /** Flow writes a store resource not listed in `effects.writes`. */
260
- UNDECLARED_WRITE: {
261
- code: 1002,
262
- domain: "kernel",
263
- cause: 'Flow "{flow}" writes "{resource}" without declaring it.',
264
- fix: 'Add "{resource}" to this flow\'s effects.writes.',
265
- },
258
+ UNDECLARED_WRITE: { code: 1002, domain: "kernel" },
266
259
  /** Flow emits a signal not listed in `effects.emits`. */
267
- UNDECLARED_EMIT: {
268
- code: 1003,
269
- domain: "kernel",
270
- cause: 'Flow "{flow}" emits "{resource}" without declaring it.',
271
- fix: 'Add "{resource}" to this flow\'s effects.emits.',
272
- },
260
+ UNDECLARED_EMIT: { code: 1003, domain: "kernel" },
273
261
  /** Flow sends a channel template not listed in `effects.sends`. */
274
- UNDECLARED_SEND: {
275
- code: 1004,
276
- domain: "kernel",
277
- cause: 'Flow "{flow}" sends "{resource}" without declaring it.',
278
- fix: 'Add "{resource}" to this flow\'s effects.sends.',
279
- },
262
+ UNDECLARED_SEND: { code: 1004, domain: "kernel" },
280
263
  /** Flow asks a prompt not listed in `effects.asks`. */
281
- UNDECLARED_ASK: {
282
- code: 1005,
283
- domain: "kernel",
284
- cause: 'Flow "{flow}" asks "{resource}" without declaring it.',
285
- fix: 'Add "{resource}" to this flow\'s effects.asks.',
286
- },
264
+ UNDECLARED_ASK: { code: 1005, domain: "kernel" },
287
265
  /** Flow reads a secret not listed in `effects.secrets`. */
288
- UNDECLARED_SECRET: {
289
- code: 1006,
290
- domain: "kernel",
291
- cause: 'Flow "{flow}" reads secret "{resource}" without declaring it.',
292
- fix: 'Add "{resource}" to this flow\'s effects.secrets.',
293
- },
266
+ UNDECLARED_SECRET: { code: 1006, domain: "kernel" },
294
267
  /** Flow calls another flow not listed in `effects.calls`. */
295
- UNDECLARED_CALL: {
296
- code: 1007,
297
- domain: "kernel",
298
- cause: 'Flow "{flow}" calls "{resource}" without declaring it.',
299
- fix: 'Add "{resource}" to this flow\'s effects.calls.',
300
- },
268
+ UNDECLARED_CALL: { code: 1007, domain: "kernel" },
301
269
  /** Flow fetches a host not listed in `effects.fetches`. */
302
- UNDECLARED_FETCH: {
303
- code: 1008,
304
- domain: "kernel",
305
- cause: 'Flow "{flow}" fetches "{resource}" without declaring it.',
306
- fix: 'Add "{resource}" to this flow\'s effects.fetches.',
307
- },
270
+ UNDECLARED_FETCH: { code: 1008, domain: "kernel" },
308
271
  /** Flow embeds via a model not listed in `effects.embeds`. */
309
- UNDECLARED_EMBED: {
310
- code: 1009,
311
- domain: "kernel",
312
- cause: 'Flow "{flow}" embeds with "{resource}" without declaring it.',
313
- fix: 'Add "{resource}" to this flow\'s effects.embeds.',
314
- },
272
+ UNDECLARED_EMBED: { code: 1009, domain: "kernel" },
315
273
  /**
316
274
  * Flow has no declared `effects` and no Manifest-derived effects were
317
275
  * available to stamp at boot (dev+compose / prod — never a silent open token).
318
276
  */
319
- NO_EFFECTS_DECLARED: {
320
- code: 1020,
321
- domain: "kernel",
322
- cause: 'Flow "{flow}" has no declared effects and no Manifest to derive them from.{extract}',
323
- fix:
324
- "Add explicit `effects` to this flow, or boot with a Manifest (`oke build`) / " +
325
- "`rootDir` so effects can be derived. If extract failed, ensure `oxc-parser` is " +
326
- "installed (okengine dependency). dev+compose/prod refuse an open capability token.",
327
- },
277
+ NO_EFFECTS_DECLARED: { code: 1020, domain: "kernel" },
328
278
  /**
329
279
  * A `src/flows/<unit>` folder exists on disk but no adopted flow carries
330
280
  * that unit — the generated `.adopt()` barrel (`src/flows/index.ts`)
331
281
  * is stale or was hand-edited. dev+compose / prod — never a silently-incomplete
332
282
  * route table in a deploy-shaped environment.
333
283
  */
334
- ADOPT_BARREL_STALE: {
335
- code: 1030,
336
- domain: "kernel",
337
- cause: "src/flows/{unit} exists on disk but adopted no flows — the .adopt() barrel is stale.",
338
- fix: "Run `oke dev` or `oke build` to regenerate `src/flows/index.ts`.",
339
- },
340
- /**
341
- * `http.get()` was never stamped from the file tree — refuse a silent `/`.
342
- */
343
- HTTP_PATH_UNRESOLVED: {
344
- code: 1040,
345
- domain: "kernel",
346
- cause: 'Flow "{flow}" bound {method} with no path — the file-tree stamp never ran.',
347
- fix: 'Put the file under `src/flows/<unit>/` and import `@/flows`, or pass an explicit path to `http.{method}("/…")`.',
348
- },
349
- /**
350
- * Two HTTP bindings share method + path — last-add-wins is the opposite of this DX.
351
- */
352
- HTTP_ROUTE_DUPLICATE: {
353
- code: 1041,
354
- domain: "kernel",
355
- cause: '{method} {path} is bound twice (flow "{flow}").',
356
- fix: "Give each HTTP flow a unique method + path.",
357
- },
358
- /**
359
- * Adopted HTTP flow still has no name (`flow({ do })` outside a unit).
360
- */
361
- HTTP_FLOW_UNNAMED: {
362
- code: 1045,
363
- domain: "kernel",
364
- cause: "An HTTP flow on {method} {path} has no name.",
365
- fix: 'Use `flow("unit.export", {…})` or export it from a `src/flows/<unit>/` file so the tree can stamp `unit.export`.',
366
- },
367
- /**
368
- * Two live HTTP exposures of the same signal share gates + match shape.
369
- */
370
- LIVE_EXPOSURE_DUPLICATE: {
371
- code: 1050,
372
- domain: "kernel",
373
- cause:
374
- 'Live signal "{signal}" is exposed twice with the same gates ({gates}) and match ({match}).',
375
- fix: "Use a different gate or path-param filter, or drop the extra route.",
376
- },
377
- /**
378
- * Two MCP tool bindings share the same exposed tool name.
379
- */
380
- MCP_TOOL_DUPLICATE: {
381
- code: 1060,
382
- domain: "kernel",
383
- cause: 'MCP tool "{tool}" is bound twice (flow "{flow}").',
384
- fix: "Give each MCP tool exposure a unique tool name.",
385
- },
284
+ ADOPT_BARREL_STALE: { code: 1030, domain: "kernel" },
285
+ /** `http.get()` was never stamped from the file tree — refuse a silent `/`. */
286
+ HTTP_PATH_UNRESOLVED: { code: 1040, domain: "kernel" },
287
+ /** Two HTTP bindings share method + path. */
288
+ HTTP_ROUTE_DUPLICATE: { code: 1041, domain: "kernel" },
289
+ /** Adopted HTTP flow still has no name (`flow({ do })` outside a unit). */
290
+ HTTP_FLOW_UNNAMED: { code: 1045, domain: "kernel" },
291
+ /** Two live HTTP exposures of the same signal share gates + match shape. */
292
+ LIVE_EXPOSURE_DUPLICATE: { code: 1050, domain: "kernel" },
293
+ /** Two MCP tool bindings share the same exposed tool name. */
294
+ MCP_TOOL_DUPLICATE: { code: 1060, domain: "kernel" },
386
295
  /**
387
296
  * Emit target has no subscriber (unified-theory §21).
388
297
  * Thrown at emit when `optional` is false and nobody is subscribed.
389
298
  */
390
- ORPHAN_EMIT: {
391
- code: 1240,
392
- domain: "signal",
393
- cause: 'Flow "{flow}" emits signal "{resource}" with no subscriber.',
394
- fix: "Add `on({resource}, …)` or mark the signal `{ optional: true }`.",
395
- },
299
+ ORPHAN_EMIT: { code: 1240, domain: "signal" },
396
300
  /** Emit payload failed the signal's declared Standard Schema. */
397
- SIGNAL_SCHEMA: {
398
- code: 1250,
399
- domain: "signal",
400
- cause: '"{resource}": {detail}',
401
- fix: "Fix schema payload.",
402
- },
403
- /**
404
- * Domain table/column missing under docker/prod (migrations not applied).
405
- */
406
- DOMAIN_SCHEMA_MISSING: {
407
- code: 1110,
408
- domain: "store",
409
- cause: "domain table not found — migrations have not been applied.",
410
- fix: "run `oke db migrate` against this environment.",
411
- },
412
- } as const satisfies Record<string, OkeErrorDefinition>;
301
+ SIGNAL_SCHEMA: { code: 1250, domain: "signal" },
302
+ /** Domain table/column missing under docker/prod (migrations not applied). */
303
+ DOMAIN_SCHEMA_MISSING: { code: 1110, domain: "store" },
304
+ } as const satisfies Record<string, { readonly code: number; readonly domain: OkeErrorDomain }>;
305
+
306
+ type OkeErrorRowTable = typeof OKE_ERROR_ROWS;
307
+
308
+ /** Registry entries with literal codes and lazy cause/fix. */
309
+ type OkeErrorTable = {
310
+ readonly [K in keyof OkeErrorRowTable]: OkeErrorDefinition & {
311
+ readonly code: OkeErrorRowTable[K]["code"];
312
+ readonly domain: OkeErrorRowTable[K]["domain"];
313
+ };
314
+ };
315
+
316
+ /**
317
+ * Load English cause/fix templates. Computed stem so Bun.build cannot inline them.
318
+ */
319
+ function loadErrorText(): typeof import("./errors-text.ts") {
320
+ return lazyRequire(import.meta.dir, ["errors", "text"].join("-"));
321
+ }
322
+
323
+ /**
324
+ * Read one cause or fix template.
325
+ *
326
+ * @param key - {@link OKE_ERRORS} property name
327
+ * @param part - `cause` or `fix`
328
+ */
329
+ function errorPart(key: string, part: "cause" | "fix"): string {
330
+ const row = loadErrorText().OKE_ERROR_TEXT[key];
331
+ if (!row) throw new Error(`Missing OKE error text for ${key}.${part}`);
332
+ return row[part];
333
+ }
334
+
335
+ /**
336
+ * Attach lazy cause/fix getters. Strings stay in the text chunk until read.
337
+ *
338
+ * @param rows - Code and domain table
339
+ */
340
+ function attachErrorText(rows: OkeErrorRowTable): OkeErrorTable {
341
+ const out: Record<string, OkeErrorDefinition> = {};
342
+ for (const key of Object.keys(rows) as (keyof OkeErrorRowTable)[]) {
343
+ const row = rows[key];
344
+ out[key] = {
345
+ code: row.code,
346
+ domain: row.domain,
347
+ get cause() {
348
+ return errorPart(key, "cause");
349
+ },
350
+ get fix() {
351
+ return errorPart(key, "fix");
352
+ },
353
+ };
354
+ }
355
+ return out as OkeErrorTable;
356
+ }
357
+
358
+ /**
359
+ * Permanent error registry. Cause/fix load from the lazy text chunk.
360
+ *
361
+ * `@__PURE__` lets bundles that never read the registry drop the getter
362
+ * table. A plain call looks like a side effect and stays in every importer.
363
+ */
364
+ export const OKE_ERRORS: OkeErrorTable = /* @__PURE__ */ attachErrorText(OKE_ERROR_ROWS);
413
365
 
414
366
  /** Tenant error keys — definitions live in the lazy `errors-tenant` chunk. */
415
367
  export type TenantOkeErrorKey = "TENANT_REQUIRED" | "TENANT_NOT_MEMBER" | "TENANT_UNKNOWN_SCOPE";
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Driver-backed `fx.store` SQL handle — lazy chunk.
3
+ *
4
+ * The in-memory stub stays on the edge profile. This query builder loads
5
+ * the first time a SQL facet is opened.
6
+ */
7
+
8
+ import type { SqlRow } from "../drivers/types.ts";
9
+ import type {
10
+ SelectFromBuilder,
11
+ SelectOrderBuilder,
12
+ SqlStoreHandle,
13
+ StoreDecl,
14
+ } from "../elements/store.ts";
15
+ import { schemaTableName, sqlTableRef } from "../manifest/sql-resource.ts";
16
+ import type { CapabilityToken } from "./capability.ts";
17
+ import { DryRunWriteIsolationError, isDryRun } from "./dry-run.ts";
18
+ import type { EffectExternal } from "./effects.ts";
19
+
20
+ /** Capability-gated effect runner from {@link createFx}. */
21
+ type Gated = <T>(
22
+ kind: Parameters<CapabilityToken["assert"]>[0],
23
+ resource: string,
24
+ body: () => T | Promise<T>,
25
+ externalOf?:
26
+ | EffectExternal
27
+ | ((result: T | undefined, error: unknown) => EffectExternal | undefined),
28
+ ) => Promise<T>;
29
+
30
+ /** Inputs for {@link createGatedSqlHandle}. */
31
+ export interface GatedSqlHandleOptions {
32
+ /** Store declaration (`facet: "sql"`). */
33
+ readonly decl: StoreDecl;
34
+ /** Opens (and caches) the runtime handle. */
35
+ readonly open: () => Promise<SqlStoreHandle>;
36
+ /** Flow `gated` helper. */
37
+ readonly gated: Gated;
38
+ /** Capability token for per-table ref checks. */
39
+ readonly capability: CapabilityToken;
40
+ /** `fx.ask` — optional search rerank. */
41
+ readonly ask: (model: string, input: unknown) => Promise<unknown>;
42
+ }
43
+
44
+ /**
45
+ * Lazy, capability-gated proxy over a driver-backed {@link SqlStoreHandle}.
46
+ *
47
+ * @param options - Declaration, opener, gate, and rerank hook
48
+ */
49
+ export function createGatedSqlHandle(options: GatedSqlHandleOptions): SqlStoreHandle {
50
+ const { decl, open, gated, capability, ask } = options;
51
+ const ref = decl.ref as `sql:${string}`;
52
+ let cached: SqlStoreHandle | undefined;
53
+ const ensure = async (): Promise<SqlStoreHandle> => {
54
+ if (!cached) cached = await open();
55
+ return cached;
56
+ };
57
+ /** Driver-backed SQL has no dry-run transaction — refuse writes. */
58
+ const refuseDryRunWrite = (): void => {
59
+ if (isDryRun()) {
60
+ throw new DryRunWriteIsolationError(
61
+ `Driver-backed store "${ref}" cannot isolate writes during dry-run; dry-run refused rather than risk a double-write.`,
62
+ );
63
+ }
64
+ };
65
+ /**
66
+ * Gate a table-scoped SQL operation. Prefers the precise `sql:<table>`
67
+ * ref (matches what the compiler's AST inference derives from the same
68
+ * call site); falls back to the store-level ref when the table ref isn't
69
+ * declared — flows that hand-declared `effects: { writes: ["sql:<store>"] }`
70
+ * keep working. Ledger / journal record whichever ref the capability check
71
+ * actually matched.
72
+ *
73
+ * @param kind - Effect kind
74
+ * @param table - Table argument passed to a `SqlStoreHandle` method
75
+ * @param body - Work to run under the gate
76
+ */
77
+ const gatedTable = <T>(
78
+ kind: Parameters<CapabilityToken["assert"]>[0],
79
+ table: unknown,
80
+ body: () => T | Promise<T>,
81
+ ): Promise<T> => {
82
+ const externalOf = (): EffectExternal | undefined => cached?.external;
83
+ const name = schemaTableName(table);
84
+ if (name !== undefined) {
85
+ const perTable = sqlTableRef(name);
86
+ if (perTable !== ref && capability.allows(kind, perTable)) {
87
+ return gated(kind, perTable, body, externalOf);
88
+ }
89
+ }
90
+ return gated(kind, ref, body, externalOf);
91
+ };
92
+
93
+ return {
94
+ ref,
95
+ get routedRole() {
96
+ return cached?.routedRole ?? "primary";
97
+ },
98
+ get driverId() {
99
+ return cached?.driverId ?? "memory";
100
+ },
101
+ select: ((columns?: unknown) => {
102
+ return {
103
+ from(table: unknown) {
104
+ const run = (plan: {
105
+ where?: unknown;
106
+ orders?: readonly unknown[];
107
+ limit?: number;
108
+ offset?: number;
109
+ }): Promise<SqlRow[]> =>
110
+ gatedTable("read", table, async () => {
111
+ const h = await ensure();
112
+ const from = h.select(columns).from(table) as SelectFromBuilder;
113
+ const filtered = plan.where === undefined ? from : from.where(plan.where);
114
+ const ordered =
115
+ plan.orders === undefined ? filtered : filtered.orderBy(...plan.orders);
116
+ if (plan.offset !== undefined) return ordered.offset(plan.offset);
117
+ return plan.limit === undefined ? ordered : ordered.limit(plan.limit);
118
+ });
119
+
120
+ const tail = (plan: {
121
+ where?: unknown;
122
+ orders?: readonly unknown[];
123
+ }): SelectOrderBuilder => ({
124
+ limit(n) {
125
+ return run({ ...plan, limit: n });
126
+ },
127
+ offset(n) {
128
+ return run({ ...plan, offset: n });
129
+ },
130
+ then(onfulfilled, onrejected) {
131
+ return run(plan).then(onfulfilled, onrejected);
132
+ },
133
+ });
134
+
135
+ return {
136
+ where(where: unknown) {
137
+ return {
138
+ ...tail({ where }),
139
+ orderBy: (...orders: readonly unknown[]) => tail({ where, orders }),
140
+ };
141
+ },
142
+ orderBy: (...orders: readonly unknown[]) => tail({ orders }),
143
+ limit(n: number) {
144
+ return run({ limit: n });
145
+ },
146
+ offset(n: number) {
147
+ return run({ offset: n });
148
+ },
149
+ then(
150
+ onfulfilled: (value: SqlRow[]) => unknown,
151
+ onrejected?: (reason: unknown) => unknown,
152
+ ) {
153
+ return run({}).then(onfulfilled, onrejected);
154
+ },
155
+ };
156
+ },
157
+ };
158
+ }) as SqlStoreHandle["select"],
159
+ insert(table) {
160
+ return {
161
+ values(row) {
162
+ const runExecute = () =>
163
+ gatedTable("write", table, async () => {
164
+ refuseDryRunWrite();
165
+ const h = await ensure();
166
+ await h.insert(table).values(row).execute();
167
+ });
168
+ return {
169
+ returning() {
170
+ return gatedTable("write", table, async () => {
171
+ refuseDryRunWrite();
172
+ const h = await ensure();
173
+ return h.insert(table).values(row).returning();
174
+ });
175
+ },
176
+ execute: runExecute,
177
+ then(onfulfilled, onrejected) {
178
+ return runExecute().then(onfulfilled, onrejected);
179
+ },
180
+ };
181
+ },
182
+ };
183
+ },
184
+ update(table) {
185
+ return {
186
+ set(row) {
187
+ return {
188
+ where(where) {
189
+ return gatedTable("write", table, async () => {
190
+ refuseDryRunWrite();
191
+ const h = await ensure();
192
+ return h.update(table).set(row).where(where);
193
+ });
194
+ },
195
+ };
196
+ },
197
+ };
198
+ },
199
+ findById(table, id) {
200
+ return gatedTable("read", table, async () => {
201
+ const h = await ensure();
202
+ return h.findById(table, id);
203
+ });
204
+ },
205
+ delete(table: Parameters<SqlStoreHandle["delete"]>[0], id?: string) {
206
+ if (id !== undefined) {
207
+ return gatedTable("write", table, async () => {
208
+ refuseDryRunWrite();
209
+ const h = await ensure();
210
+ return h.delete(table, id);
211
+ });
212
+ }
213
+ return {
214
+ where(where: unknown) {
215
+ return gatedTable("write", table, async () => {
216
+ refuseDryRunWrite();
217
+ const h = await ensure();
218
+ return h.delete(table).where(where);
219
+ });
220
+ },
221
+ };
222
+ },
223
+ exists(table, idOrWhere) {
224
+ return gatedTable("read", table, async () => {
225
+ const h = await ensure();
226
+ return h.exists(table, idOrWhere);
227
+ });
228
+ },
229
+ upsert(table, matchOn, values, upsertOptions) {
230
+ return gatedTable("write", table, async () => {
231
+ refuseDryRunWrite();
232
+ const h = await ensure();
233
+ return h.upsert(table, matchOn, values, upsertOptions);
234
+ });
235
+ },
236
+ increment(table, id, column, by) {
237
+ return gatedTable("write", table, async () => {
238
+ refuseDryRunWrite();
239
+ const h = await ensure();
240
+ return h.increment(table, id, column, by);
241
+ });
242
+ },
243
+ raw(sql, params) {
244
+ return gated("read", ref, async () => {
245
+ const h = await ensure();
246
+ return h.raw(sql, params);
247
+ });
248
+ },
249
+ count(table, where) {
250
+ return gatedTable("read", table, async () => {
251
+ const h = await ensure();
252
+ return h.count(table, where);
253
+ });
254
+ },
255
+ page(table, pageOptions) {
256
+ return gatedTable("read", table, async () => {
257
+ const h = await ensure();
258
+ return h.page(table, pageOptions);
259
+ });
260
+ },
261
+ search(table, searchOptions) {
262
+ return gatedTable("read", table, async () => {
263
+ const h = await ensure();
264
+ const result = await h.search(table, searchOptions);
265
+ // Optional rerank via fx.ask — only when explicitly requested.
266
+ if (
267
+ searchOptions.rerank &&
268
+ typeof searchOptions.rerank === "object" &&
269
+ searchOptions.rerank.model
270
+ ) {
271
+ const model = searchOptions.rerank.model;
272
+ const pk = "id";
273
+ const docs = result.data.map((row) => ({
274
+ id: String(row[pk] ?? ""),
275
+ text: Object.values(row)
276
+ .filter((v) => typeof v === "string")
277
+ .join("\n"),
278
+ score: 0,
279
+ }));
280
+ const out = (await ask(model, {
281
+ query: searchOptions.query,
282
+ docs,
283
+ })) as { rankedIds?: string[] };
284
+ if (out.rankedIds && out.rankedIds.length > 0) {
285
+ const byId = new Map(result.data.map((r) => [String(r[pk] ?? ""), r]));
286
+ return {
287
+ ...result,
288
+ data: out.rankedIds
289
+ .map((id) => byId.get(id))
290
+ .filter((r): r is NonNullable<typeof r> => r !== undefined),
291
+ };
292
+ }
293
+ }
294
+ return result;
295
+ });
296
+ },
297
+ ensureTable(table) {
298
+ return gatedTable("write", table, async () => {
299
+ refuseDryRunWrite();
300
+ const h = await ensure();
301
+ return h.ensureTable(table);
302
+ });
303
+ },
304
+ } as SqlStoreHandle;
305
+ }