@mnmal-ai/substrate 1.0.0-alpha.1 → 1.0.0-alpha.10

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 (47) hide show
  1. package/README.md +48 -6
  2. package/dist/boot-store-BVqfFxh1.js +4060 -0
  3. package/dist/{runtime-metrics-DwpDJ8vz.d.ts → bridge-Cp4PaIYO.d.ts} +2 -87
  4. package/dist/cli-hSCBywhE.js +3126 -0
  5. package/dist/client.d.ts +130 -8
  6. package/dist/client.js +6 -5
  7. package/dist/{plugin-t2g2wX0b.d.ts → dataset-CejF-Fr_.d.ts} +1640 -1320
  8. package/dist/{agent-token-BIboWOU0.js → env-utils-CGNazUNt.js} +31 -2
  9. package/dist/{errors-D4vKuwz8.d.ts → errors-7mycvNGq.d.ts} +1 -1
  10. package/dist/{index-D7mSOFlM.d.ts → index-DgSfwx7M.d.ts} +1 -1
  11. package/dist/node-version-C5FSmwJX.js +26 -0
  12. package/dist/pack.d.ts +2 -2
  13. package/dist/pack.js +1 -1
  14. package/dist/pg-edges-store-Lxsl5ZnK.js +381 -0
  15. package/dist/{plugin-BuQQEzL-.js → plugin-CtwOINCM.js} +171 -18
  16. package/dist/proposals-bootstrap.js +6 -4
  17. package/dist/proposals.config.schema.json +5 -0
  18. package/dist/proposals.d.ts +15 -4
  19. package/dist/proposals.default-config.json +2 -1
  20. package/dist/proposals.js +2 -2
  21. package/dist/recall-bootstrap.js +13 -4
  22. package/dist/recall.config.schema.json +12 -0
  23. package/dist/recall.d.ts +54 -9
  24. package/dist/recall.js +2 -2
  25. package/dist/{repl-C52wyfMs.js → repl-DqfHelK7.js} +62 -29
  26. package/dist/{row-ByLFE2Wx.d.ts → row-BKKCXIG6.d.ts} +5 -3
  27. package/dist/run-B5dTbZ3g.js +1997 -0
  28. package/dist/{schema-g4FQLr0V.d.ts → schema-DoSc-4ig.d.ts} +44 -7
  29. package/dist/script-C6DSa_Na.js +134 -0
  30. package/dist/sdk.d.ts +90 -12
  31. package/dist/sdk.js +5 -110
  32. package/dist/{src-YXlv_RyL.js → src-5SJ5GEIM.js} +1555 -326
  33. package/dist/{src-DuopV8u7.js → src-7CUSMK66.js} +148 -19
  34. package/dist/{src-zcyUofMJ.js → src-Bi849yhn.js} +39 -15
  35. package/dist/{src-5hVbeiAu.js → src-CqT-QWZ_.js} +697 -57
  36. package/dist/src-CyvV7dCK.js +4333 -0
  37. package/dist/{row-DK7lPZVe.js → src-Da0t6si5.js} +11 -11
  38. package/dist/{src-C4DzaIQZ.js → src-hZb8wfvg.js} +12 -1
  39. package/dist/substrate-admin.js +17 -781
  40. package/dist/substrate.js +4 -5476
  41. package/dist/testing.d.ts +557 -8
  42. package/dist/testing.js +39 -3
  43. package/dist/{ws-C72iVS5T.d.ts → ws-ByZyHk7m.d.ts} +3 -3
  44. package/package.json +21 -20
  45. package/dist/dataset-DOXGRz50.js +0 -1535
  46. package/dist/env-utils-B7SGmoeJ.js +0 -21
  47. package/dist/src-CjEwiKXw.js +0 -2327
@@ -14,6 +14,21 @@ interface Row {
14
14
  _metadata?: RowMetadata;
15
15
  [field: string]: unknown;
16
16
  }
17
+ /**
18
+ * A row as passed to `Dataset.write`. `id` may be omitted: the dataset then
19
+ * assigns a version-7 UUID and returns it in `WriteResult.ids`.
20
+ */
21
+ interface WriteRow {
22
+ id?: Id;
23
+ _deletedAt?: Date | null;
24
+ _metadata?: RowMetadata;
25
+ [field: string]: unknown;
26
+ }
27
+ /**
28
+ * Refuse an upsert batch that names one id twice: the datasets would
29
+ * otherwise disagree (pg cannot update a row twice in one statement).
30
+ */
31
+ declare function assertNoRepeatedIds(type: string, rows: readonly WriteRow[]): void;
17
32
  type IdentityKind = 'agent' | 'user' | 'system';
18
33
  /**
19
34
  * Row-attribution actor — records who created or last updated a row.
@@ -28,6 +43,11 @@ interface RowMetadata {
28
43
  readonly updatedAt: string | null;
29
44
  readonly createdBy: ActorIdentity | null;
30
45
  readonly updatedBy: ActorIdentity | null;
46
+ /**
47
+ * The row's place in its type's commit order, on a type declared
48
+ * `ordering: 'visible'`; absent on every other type. Assigned on insert only.
49
+ */
50
+ readonly seq?: number;
31
51
  }
32
52
  declare const CLIENT_SUPPLIED_SERVER_FIELD: 'client_supplied_server_field';
33
53
  type ClientSuppliedServerFieldError = typeof CLIENT_SUPPLIED_SERVER_FIELD;
@@ -162,6 +182,13 @@ interface FieldDefScalar {
162
182
  * inner keys, use `field.struct` instead.
163
183
  */
164
184
  type: 'string' | 'number' | 'boolean' | 'date' | 'json';
185
+ /**
186
+ * Tri-state. `true` builds an index (a btree; a GIN for json). Unset means
187
+ * no index. `false` means no index AND not a search handle: long-form
188
+ * prose that NL and similar consumers leave out. The field filters either
189
+ * way. Physical consumers test `=== true`, so never normalise unset to
190
+ * `false`.
191
+ */
165
192
  indexed?: boolean;
166
193
  /** Metadata: when true, consumers SHOULD expect `null` as a legitimate value. */
167
194
  nullable?: boolean;
@@ -284,11 +311,10 @@ interface FieldDefList {
284
311
  kind: 'list';
285
312
  of: FieldDef;
286
313
  /**
287
- * When true, the field is server-side filterable via the `has` (element
288
- * membership) operator without `_allowTableScan`, and is backed by a GIN
314
+ * When true, the `has` (element membership) operator is backed by a GIN
289
315
  * index on `(body -> '<field>')`. List fields are stored as native JSONB
290
- * arrays. Default false — an unindexed list field rejects `has` unless the
291
- * caller opts into a table scan. The substrate binary derives the matching GIN
316
+ * arrays. Default false — `has` on an unindexed list still works, by
317
+ * scanning the type's rows. The substrate binary derives the matching GIN
292
318
  * as an idempotent migration at boot from this flag; no hand-authored
293
319
  * migration is needed per field.
294
320
  */
@@ -304,7 +330,18 @@ type FieldDef = FieldDefScalar | FieldDefCrossRef | FieldDefStruct | FieldDefLis
304
330
  */
305
331
  interface TypeSchema {
306
332
  fields: Record<string, FieldDef>;
333
+ /** The type's natural order; absent means {@link DEFAULT_ORDERED_BY}. */
334
+ orderedBy?: OrderedBy;
307
335
  }
336
+ /**
337
+ * A type's natural order: exactly one `{ field: direction }` key, the order a
338
+ * read with no `orderBy` returns. The datasets still append `id` as the tie-break.
339
+ */
340
+ type OrderedBy = Record<string, 'asc' | 'desc'>;
341
+ /** Natural order of a type that declares none: newest first. */
342
+ declare const DEFAULT_ORDERED_BY: OrderedBy;
343
+ /** The declared natural order, or {@link DEFAULT_ORDERED_BY}. */
344
+ declare function naturalOrderOf(schema: Pick<TypeSchema, 'orderedBy'>): OrderedBy;
308
345
  /**
309
346
  * Per-mutation schema entry. `params` describes the input shape a client
310
347
  * sends; `returns` describes the shape a client decodes on success. Both are
@@ -403,8 +440,8 @@ interface PackEnvelope {
403
440
  * The where-clause reached the substrate without being schema-validated,
404
441
  * because the type is registered but absent from its namespace's
405
442
  * published schema (e.g. runtime-created types). The result is still
406
- * correct — substrates refuse a predicate they cannot honour — but an
407
- * unindexed filter scans instead of rejecting.
443
+ * correct — substrates refuse a predicate they cannot honour — but the
444
+ * engine's operator and operand check did not run.
408
445
  */
409
446
  filterValidationSkipped?: string;
410
447
  }>;
@@ -430,4 +467,4 @@ type FieldInput = {
430
467
  [field: string]: true | FieldInput;
431
468
  };
432
469
  //#endregion
433
- export { Id as C, RowMetadata as D, Row as E, RowMetadataField as O, ClientSuppliedServerFieldError as S, ROW_METADATA_FIELDS as T, EdgesStore as _, FieldDefScalar as a, ActorIdentity as b, MutationSchema as c, TypeSchema as d, CanDeleteResult as f, EdgeWriteInput as g, EdgeRef as h, FieldDefList as i, PackEnvelope as l, EdgePatch as m, FieldDef as n, FieldDefStruct as o, Edge as p, FieldDefCrossRef as r, FieldInput as s, EnvelopeShape as t, Schema as u, OnDelete as v, IdentityKind as w, CLIENT_SUPPLIED_SERVER_FIELD as x, OnMissing as y };
470
+ export { RowMetadata as A, ActorIdentity as C, IdentityKind as D, Id as E, WriteRow as M, assertNoRepeatedIds as N, ROW_METADATA_FIELDS as O, OnMissing as S, ClientSuppliedServerFieldError as T, EdgePatch as _, FieldDefList as a, EdgesStore as b, FieldInput as c, PackEnvelope as d, Schema as f, Edge as g, CanDeleteResult as h, FieldDefCrossRef as i, RowMetadataField as j, Row as k, MutationSchema as l, naturalOrderOf as m, EnvelopeShape as n, FieldDefScalar as o, TypeSchema as p, FieldDef as r, FieldDefStruct as s, DEFAULT_ORDERED_BY as t, OrderedBy as u, EdgeRef as v, CLIENT_SUPPLIED_SERVER_FIELD as w, OnDelete as x, EdgeWriteInput as y };
@@ -0,0 +1,134 @@
1
+ import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
+ //#region ../../packages/substrate-client/src/script.ts
3
+ const DEFAULT_MAX_WRITES = 50;
4
+ const DEFAULT_MAX_PAGES = 200;
5
+ /** Counts the frames in a mutate payload: an array under an op-key is one frame per element. */
6
+ function frameCount(frame) {
7
+ return Object.values(frame).reduce((n, v) => n + (Array.isArray(v) ? v.length : 1), 0);
8
+ }
9
+ function assertKeys(frame, env, verb) {
10
+ const missing = Object.keys(frame).filter((k) => !(k in env.data));
11
+ if (missing.length > 0 || verb === "mutate" && (env.errors?.length ?? 0) > 0) {
12
+ const errs = (env.errors ?? []).map((e) => `${e.code ?? "error"}: ${e.message}`).join("; ");
13
+ throw new Error(`${verb} refused${missing.length > 0 ? ` for ${missing.join(", ")}` : ""}${errs !== "" ? ` (${errs})` : ""}`);
14
+ }
15
+ }
16
+ /**
17
+ * Runs `script` against a guarded context and reports everything it did,
18
+ * including the mutations applied before any failure.
19
+ */
20
+ async function runScript(script, opts) {
21
+ const { client, kid, mode = "read", args = {}, maxWrites = 50, maxPages = DEFAULT_MAX_PAGES } = opts;
22
+ const log = opts.log ?? ((line) => process.stderr.write(`${line}\n`));
23
+ const mutations = [];
24
+ const warnings = [];
25
+ const stats = {
26
+ queries: 0,
27
+ writes: 0,
28
+ ms: 0
29
+ };
30
+ const started = Date.now();
31
+ const query = async (frame) => {
32
+ stats.queries++;
33
+ const env = await client.query(frame);
34
+ assertKeys(frame, env, "query");
35
+ for (const [key, page] of Object.entries(env._pagination ?? {})) if (page.hasMore) warnings.push(`${key}: result truncated (hasMore); use queryAll for a complete read`);
36
+ return env;
37
+ };
38
+ const ctx = {
39
+ kid,
40
+ mode,
41
+ args: Object.freeze({ ...args }),
42
+ query,
43
+ async queryAll(key, frame) {
44
+ const rows = [];
45
+ let cursor;
46
+ for (let page = 0; page < maxPages; page++) {
47
+ const params = {
48
+ ...frame.params,
49
+ ...cursor !== void 0 ? { cursor } : {}
50
+ };
51
+ stats.queries++;
52
+ const env = await client.query({ [key]: {
53
+ ...frame,
54
+ params
55
+ } });
56
+ assertKeys({ [key]: frame }, env, "query");
57
+ const data = env.data[key];
58
+ rows.push(...Array.isArray(data) ? data : [data]);
59
+ const p = env._pagination?.[key];
60
+ if (p?.hasMore !== true) return rows;
61
+ if (p.nextCursor === void 0) throw new Error(`${key}: hasMore with no nextCursor`);
62
+ cursor = p.nextCursor;
63
+ }
64
+ throw new Error(`${key}: still hasMore after ${maxPages} pages`);
65
+ },
66
+ async recall({ query: to, row, ...params }) {
67
+ const fields = row === void 0 ? {} : { fields: {
68
+ id: true,
69
+ namespace: true,
70
+ type: true,
71
+ score: true,
72
+ kind: true,
73
+ expandedFrom: true,
74
+ row
75
+ } };
76
+ return (await query({ "recall/Hit": {
77
+ params: {
78
+ to,
79
+ ...params
80
+ },
81
+ ...fields
82
+ } })).data["recall/Hit"];
83
+ },
84
+ async mutate(frame) {
85
+ if (mode === "read") throw new Error("mutate refused: read mode (pass --dry-run or --write)");
86
+ if (mode === "dry-run") {
87
+ mutations.push({
88
+ frame,
89
+ applied: false
90
+ });
91
+ return null;
92
+ }
93
+ const n = frameCount(frame);
94
+ if (stats.writes + n > maxWrites) throw new Error(`mutate refused: ${stats.writes + n} frames would exceed --max-writes ${maxWrites}`);
95
+ const env = await client.mutate(frame);
96
+ const applied = Object.keys(frame).some((k) => k in env.data);
97
+ if (applied) stats.writes += n;
98
+ mutations.push({
99
+ frame,
100
+ applied,
101
+ ...env.errors !== void 0 ? { errors: env.errors } : {}
102
+ });
103
+ assertKeys(frame, env, "mutate");
104
+ return env;
105
+ },
106
+ log: (...args) => log(args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" "))
107
+ };
108
+ const report = (extra) => {
109
+ stats.ms = Date.now() - started;
110
+ return {
111
+ ...extra,
112
+ kid,
113
+ mode,
114
+ args,
115
+ mutations,
116
+ warnings,
117
+ stats
118
+ };
119
+ };
120
+ try {
121
+ return report({
122
+ ok: true,
123
+ result: await script(ctx)
124
+ });
125
+ } catch (err) {
126
+ return report({
127
+ ok: false,
128
+ error: err instanceof Error ? err.message : String(err)
129
+ });
130
+ }
131
+ }
132
+
133
+ //#endregion
134
+ export { runScript as n, DEFAULT_MAX_WRITES as t };
package/dist/sdk.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { C as Id, D as RowMetadata, E as Row, O as RowMetadataField, S as ClientSuppliedServerFieldError, T as ROW_METADATA_FIELDS, _ as EdgesStore, a as FieldDefScalar, b as ActorIdentity, c as MutationSchema, d as TypeSchema, f as CanDeleteResult, g as EdgeWriteInput, h as EdgeRef, i as FieldDefList, l as PackEnvelope, m as EdgePatch, n as FieldDef, o as FieldDefStruct, p as Edge, r as FieldDefCrossRef, s as FieldInput, t as EnvelopeShape, u as Schema, v as OnDelete, w as IdentityKind, x as CLIENT_SUPPLIED_SERVER_FIELD, y as OnMissing } from "./schema-g4FQLr0V.js";
2
- import { a as RuntimeErrors, c as BridgeClient, d as BridgeFrame, i as RuntimeErrorEntry, l as BridgeCredential, n as ResolveObservation, o as RuntimeMetrics, r as ResolverStat, s as SlowRequest, t as ProcessStat, u as BridgeCredentialStore } from "./runtime-metrics-DwpDJ8vz.js";
3
- import { $ as PolicyProbeContext, A as ScheduledTask, B as StartOpts, C as QualifiedFrame, D as RegistryEntryInput, E as RegistryEntry, F as HttpMethod, G as WsConnection, H as SubstrateResponse, I as PluginRouter, J as AutoCrudVerb, K as WsHandler, L as RequestObservation, M as VirtualMutationDef, N as VirtualTypeDef, O as RegistryEntryKind, P as HttpHandler, Q as PolicyDecision, R as RequestObserver, S as PostWriteHook, St as WriteResult, T as RegistryBase, U as SubstrateServer, V as SubstrateRequest, W as TlsConfig, X as Obligation, Y as Identity, Z as Policy, _ as NamespaceDefinition, _t as ReadResult, a as EngineHandle, at as TypedResolver, b as PluginLifecycleContext, bt as WhereClause, c as FrameEntry, ct as Dataset, d as KernelMigrationContext, dt as DropResult, et as RequestContext, f as KernelNamespaceContribution, ft as FieldKind, g as NamespaceConfig, gt as ReadParams, h as McpToolRegistration, ht as OrderByClause, i as EncodeContext, it as RowFilterObligation, j as ScheduledTaskContext, k as RegistryEntryResolver, l as KernelLifecycleContext, lt as DatasetRegistry, m as KernelRouteClaim, mt as FilterCapabilities, n as DropParticipant, nt as ResolverArgs, o as EngineInput, ot as WriteEvent, p as KernelPlugin, pt as FieldPredicate, q as AfterTxWork, r as EmbedSourceContext, rt as ResolverReturn, s as FilterOperatorDef, st as ConditionalUpdateResult, t as CoordinatorPlugin, tt as Resolver, u as KernelMigration, ut as DeleteResult, v as NamespaceInstallContext, vt as TxScopeHandles, w as Registry, x as PluginRouteContext, xt as WriteOptions, y as NamespaceTypeDef, yt as UpdateFieldRef, z as RuntimeOp } from "./plugin-t2g2wX0b.js";
4
- import { a as ResolverFrameError, c as isAuthCause, i as ReservedField, l as isResolverFrameError, n as MissingReferentError, o as RestrictViolation, r as NamespaceMismatch, s as UnsupportedFilterError, t as BridgeUnreachableError, u as isRestrictViolation } from "./errors-D4vKuwz8.js";
5
- import { a as WsResponseFrame, c as ResolveTarget, d as TargetState, f as IdempotencyStore, i as WsRequestFrame, l as SweepDeps, n as WS_REASON_SERVER_RESTART, o as WsResponseKind, r as WS_REASON_SUBSCRIPTION_OVERLOADED, s as BridgeRegistry, t as WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, u as SweepState } from "./ws-C72iVS5T.js";
6
- import { $ as NlJudgeStep, A as and, B as SYSTEM_NAMESPACE, C as flattenGrant, D as parseGrantEntries, E as intersectGrants, F as TokenProviderOpts, G as resolveAdminCredential, H as isActiveAdminKeyRow, I as adminClaimCapabilities, J as NlAskRequest, K as resolveDefaultKeyPath, L as isEncryptedKey, M as or, N as ADMIN_CAPABILITIES, O as decodeList, P as DEFAULT_CAPABILITIES, Q as NlJudgeChoice, R as makeAuthorizationProvider, S as expandFlat, T as grantIsUniform, U as AdminCredential, V as describeGrant, W as AdminEnv, X as NlEvidence, Y as NlAskResult, Z as NlJudgeAction, _ as newlyGrantedPairs, a as denyAll, at as NlPackType, b as capabilitiesFor, c as requireIdentity, ct as NlParsedData, d as KeyUpdateRefusal, dt as NlValueAlias, et as NlJudgedStatus, f as checkRevocable, ft as NlWireEvent, g as newlyGranted, gt as Query, h as grantEntriesConfer, ht as NLVocabularyHint, i as allowVerbs, it as NlPackField, j as not, k as encodeList, l as requireNamespace, lt as NlServedPack, m as grantCovers, mt as NLResult, n as row, nt as NlNamespaceRulings, o as denyVerbs, ot as NlPackValueRef, p as checkUpdatable, pt as NLBase, q as resolveDefaultKidPath, r as allowAll, rt as NlOutcome, s as requireCapability, st as NlParseStatus, t as applyRowFilters, tt as NlNamespacePack, u as KeyMutationRefusal, ut as NlTrailEvent, v as revokedAtIso, w as grantEntryError, x as encodeGrant, y as Grant, z as makeTokenProvider } from "./row-ByLFE2Wx.js";
1
+ import { A as RowMetadata, C as ActorIdentity, D as IdentityKind, E as Id, M as WriteRow, N as assertNoRepeatedIds, O as ROW_METADATA_FIELDS, S as OnMissing, T as ClientSuppliedServerFieldError, _ as EdgePatch, a as FieldDefList, b as EdgesStore, c as FieldInput, d as PackEnvelope, f as Schema, g as Edge, h as CanDeleteResult, i as FieldDefCrossRef, j as RowMetadataField, k as Row, l as MutationSchema, m as naturalOrderOf, n as EnvelopeShape, o as FieldDefScalar, p as TypeSchema, r as FieldDef, s as FieldDefStruct, t as DEFAULT_ORDERED_BY, u as OrderedBy, v as EdgeRef, w as CLIENT_SUPPLIED_SERVER_FIELD, x as OnDelete, y as EdgeWriteInput } from "./schema-DoSc-4ig.js";
2
+ import { i as BridgeFrame, n as BridgeCredential, r as BridgeCredentialStore, t as BridgeClient } from "./bridge-Cp4PaIYO.js";
3
+ import { $ as Registry, A as DropParticipant, At as Resolver, B as KernelMigrationContext, C as ResolverStat, Ct as AutoCrudVerb, D as SlowRequest, Dt as PolicyDecision, E as RuntimeMetrics, Et as Policy, F as FilterOperatorDef, Ft as WriteEvent, G as NamespaceConfig, H as KernelPlugin, I as FrameEntry, J as NamespaceTypeDef, K as NamespaceDefinition, L as IndexDecl, M as EncodeContext, Mt as ResolverReturn, N as EngineHandle, Nt as RowFilterObligation, O as TypeStats, Ot as PolicyProbeContext, P as EngineInput, Pt as TypedResolver, Q as QualifiedFrame, R as KernelLifecycleContext, S as ResolveObservation, St as AfterTxWork, T as RuntimeErrors, Tt as Obligation, U as KernelRouteClaim, V as KernelNamespaceContribution, W as McpToolRegistration, X as PluginRouteContext, Y as PluginLifecycleContext, Z as PostWriteHook, _ as UpdateFieldRef, _t as SubstrateResponse, a as DropResult, at as ScheduledTask, b as WriteResult, bt as WsConnection, c as FilterCapabilities, ct as VirtualTypeDef, d as ReadParams, dt as PluginRouter, et as RegistryBase, f as ReadResult, ft as RequestObservation, g as TypeStorageReport, gt as SubstrateRequest, h as TypeIndexState, ht as StartOpts, i as DeleteResult, it as RegistryEntryResolver, j as EmbedSourceContext, jt as ResolverArgs, k as CoordinatorPlugin, kt as RequestContext, l as IndexPlan, lt as HttpHandler, m as TxScopeHandles, mt as RuntimeOp, n as Dataset, nt as RegistryEntryInput, o as FieldKind, ot as ScheduledTaskContext, p as StorageReport, pt as RequestObserver, q as NamespaceInstallContext, r as DatasetRegistry, rt as RegistryEntryKind, s as FieldPredicate, st as VirtualMutationDef, t as ConditionalUpdateResult, tt as RegistryEntry, u as OrderByClause, ut as HttpMethod, v as WhereClause, vt as SubstrateServer, w as RuntimeErrorEntry, wt as Identity, x as ProcessStat, xt as WsHandler, y as WriteOptions, yt as TlsConfig, z as KernelMigration } from "./dataset-CejF-Fr_.js";
4
+ import { a as ResolverFrameError, c as isAuthCause, i as ReservedField, l as isResolverFrameError, n as MissingReferentError, o as RestrictViolation, r as NamespaceMismatch, s as UnsupportedFilterError, t as BridgeUnreachableError, u as isRestrictViolation } from "./errors-7mycvNGq.js";
5
+ import { a as WsResponseFrame, c as ResolveTarget, d as TargetState, f as IdempotencyStore, i as WsRequestFrame, l as SweepDeps, n as WS_REASON_SERVER_RESTART, o as WsResponseKind, r as WS_REASON_SUBSCRIPTION_OVERLOADED, s as BridgeRegistry, t as WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, u as SweepState } from "./ws-ByZyHk7m.js";
6
+ import { $ as NlJudgeStep, A as and, B as SYSTEM_NAMESPACE, C as flattenGrant, D as parseGrantEntries, E as intersectGrants, F as TokenProviderOpts, G as resolveAdminCredential, H as isActiveAdminKeyRow, I as adminClaimCapabilities, J as NlAskRequest, K as resolveDefaultKeyPath, L as isEncryptedKey, M as or, N as ADMIN_CAPABILITIES, O as decodeList, P as DEFAULT_CAPABILITIES, Q as NlJudgeChoice, R as makeAuthorizationProvider, S as expandFlat, T as grantIsUniform, U as AdminCredential, V as describeGrant, W as AdminEnv, X as NlEvidence, Y as NlAskResult, Z as NlJudgeAction, _ as newlyGrantedPairs, a as denyAll, at as NlPackType, b as capabilitiesFor, c as requireIdentity, ct as NlParsedData, d as KeyUpdateRefusal, dt as NlValueAlias, et as NlJudgedStatus, f as checkRevocable, ft as NlWireEvent, g as newlyGranted, gt as Query, h as grantEntriesConfer, ht as NLVocabularyHint, i as allowVerbs, it as NlPackField, j as not, k as encodeList, l as requireNamespace, lt as NlServedPack, m as grantCovers, mt as NLResult, n as row, nt as NlNamespaceRulings, o as denyVerbs, ot as NlPackValueRef, p as checkUpdatable, pt as NLBase, q as resolveDefaultKidPath, r as allowAll, rt as NlOutcome, s as requireCapability, st as NlParseStatus, t as applyRowFilters, tt as NlNamespacePack, u as KeyMutationRefusal, ut as NlTrailEvent, v as revokedAtIso, w as grantEntryError, x as encodeGrant, y as Grant, z as makeTokenProvider } from "./row-BKKCXIG6.js";
7
7
  //#region ../../packages/substrate-types/src/assert-never.d.ts
8
8
  /**
9
9
  * Exhaustiveness guard for the `default:` arm of a `switch` over a
@@ -32,6 +32,12 @@ export declare function canonicalize(value: unknown): unknown;
32
32
  * a config typo fails at boot.
33
33
  */
34
34
  export declare function parsePositiveInt(raw: string | undefined, envVar: string, fallback: number): number;
35
+ /**
36
+ * `url` with its trailing slashes removed, for joining a configured base URL
37
+ * to a path. A loop rather than `/\/+$/`, which backtracks quadratically on a
38
+ * long run of slashes that does not end the string.
39
+ */
40
+ export declare function trimTrailingSlashes(url: string): string;
35
41
  //#endregion
36
42
  //#region ../../packages/substrate-types/src/hard-delete-gate.d.ts
37
43
  /**
@@ -98,6 +104,18 @@ export declare function confersAnywhere(resolved: IdentityGrant | null, capabili
98
104
  /** Every capability conferred anywhere — the union, for error messages only. */
99
105
  export declare function allCapabilities(resolved: IdentityGrant | null): string[];
100
106
  //#endregion
107
+ //#region ../../packages/substrate-types/src/iso-timestamp.d.ts
108
+ /**
109
+ * `v` as `YYYY-MM-DDTHH:MM:SS[.ffffff](Z|±HH:MM)`, or `undefined` when it is
110
+ * outside the grammar or names a day that does not exist (Feb 30, year 0000).
111
+ * No offset is read as UTC, and a date alone as its midnight UTC.
112
+ */
113
+ export declare function normalizeIsoTimestamp(v: string): string | undefined;
114
+ /** Is `v` a timestamp every dataset reads to the same instant? */
115
+ export declare function isIsoTimestamp(v: string): boolean;
116
+ /** Does `v` have the grammar's shape but name a day that does not exist (Feb 30, month 13, year 0000)? */
117
+ export declare function isImpossibleIsoTimestamp(v: string): boolean;
118
+ //#endregion
101
119
  //#region ../../packages/substrate-types/src/keyed-mutex.d.ts
102
120
  /**
103
121
  * A process-local mutual-exclusion lock per string key.
@@ -331,6 +349,43 @@ interface TypeInput {
331
349
  lexical?: {
332
350
  source: (row: Row) => string | null | undefined | Promise<string | null | undefined>;
333
351
  };
352
+ /**
353
+ * Composite and unique indexes, built by the engine with the filter
354
+ * compiler's own expressions. Keys and predicate fields must be declared
355
+ * scalar (not json) or crossRef fields. See `IndexDecl`.
356
+ */
357
+ indexes?: IndexDecl[];
358
+ /**
359
+ * The type's natural order: what a read with no `orderBy` returns. Exactly
360
+ * one key, a declared date or number field or a metadata column
361
+ * (`createdAt`, `updatedAt`, or `seq` on a visible-order type). Absent
362
+ * means newest first by `createdAt`.
363
+ */
364
+ orderedBy?: OrderedBy;
365
+ /**
366
+ * `'visible'`: each inserted row gets `_metadata.seq`, strictly increasing
367
+ * per type in commit order, so a reader paging by `seq` never sees a higher
368
+ * seq before a lower one becomes visible. An upsert of an existing row keeps
369
+ * its seq. `seq` is filterable, sortable, and valid in `orderedBy`.
370
+ *
371
+ * Cost: writes to the type are serialised. Each insert holds a per-type
372
+ * transaction lock from seq assignment to commit, so one writer's open
373
+ * transaction blocks every other writer of the type until it ends. Other
374
+ * types are unaffected and pay nothing.
375
+ *
376
+ * Two transactions that write two visible-order types in opposite orders
377
+ * can deadlock; Postgres aborts one with 40P01. Write them in a consistent
378
+ * order.
379
+ *
380
+ * Making an existing type visible assigns no seq to its old rows: they keep
381
+ * a null seq and sort after every new row.
382
+ */
383
+ ordering?: 'visible';
384
+ /**
385
+ * Expected size. `large` lets the index advisor recommend for this type
386
+ * from its profile's lower `minRowsLargeHint` rather than `minRows`.
387
+ */
388
+ expectedSize?: 'small' | 'large';
334
389
  }
335
390
  interface DefineNamespaceOptions {
336
391
  /**
@@ -347,6 +402,13 @@ interface DefineNamespaceOptions {
347
402
  promotedColumns?: NamespaceDefinition['promotedColumns'];
348
403
  }
349
404
  export declare function defineNamespace(namespace: string, types: Record<string, TypeInput>, opts?: DefineNamespaceOptions): NamespaceDefinition;
405
+ /** Throws unless every key is a btree-indexable declared field or `createdAt`/`updatedAt`, and every predicate field a declared one. */
406
+ export declare function assertIndexDecl(typeName: string, fields: Record<string, FieldDef>, decl: IndexDecl): void;
407
+ /**
408
+ * Throws unless `orderedBy` is one key, on a date or number field or a metadata
409
+ * column; `seq` only on a type declared `ordering: 'visible'`.
410
+ */
411
+ export declare function assertOrderedBy(typeName: string, def: Pick<TypeInput, 'fields' | 'orderedBy' | 'ordering'>): void;
350
412
  //#endregion
351
413
  //#region ../../packages/substrate-sdk/src/autocrud/autocrud-create.d.ts
352
414
  interface CreateResolverOptions {
@@ -418,6 +480,9 @@ export interface AutoCrudRegistry {
418
480
  kind?: 'type' | 'mutation';
419
481
  params?: Record<string, FieldDef>;
420
482
  returns?: FieldDef;
483
+ orderedBy?: OrderedBy;
484
+ indexes?: IndexDecl[];
485
+ expectedSize?: 'small' | 'large';
421
486
  /** Semantic autoCRUD verb threaded to policies via ctx.verb. */
422
487
  verb?: AutoCrudVerb;
423
488
  }): void;
@@ -446,6 +511,12 @@ export interface InstallAutoCrudOptions {
446
511
  * Delete resolver does NOT invoke this hook.
447
512
  */
448
513
  postWrite?: PostWriteHook;
514
+ /** The type's natural order — published on the type entry's schema. */
515
+ orderedBy?: OrderedBy;
516
+ /** Declared indexes, kept on the type entry for storage to build (proposed types). */
517
+ indexes?: IndexDecl[];
518
+ /** Size hint, kept on the type entry for the index advisor (proposed types). */
519
+ expectedSize?: 'small' | 'large';
449
520
  }
450
521
  export interface CreateResolverWithEdgesOptions {
451
522
  /** Field definitions for the type — crossRef entries drive edge emission. */
@@ -478,6 +549,8 @@ export declare function installAutoCrud(registry: AutoCrudRegistry, typeName: st
478
549
  //#endregion
479
550
  //#region ../../packages/substrate-sdk/src/autocrud/reserved.d.ts
480
551
  export declare const RESERVED_AUTOCRUD_FIELDS: Record<string, FieldDef>;
552
+ /** Is `def` a descriptor autoCRUD injected, rather than a body field of the same name? */
553
+ export declare function isReservedAutoCrudField(def: FieldDef): boolean;
481
554
  /** Reserved field names — useful for validation loops. */
482
555
  export declare const RESERVED_AUTOCRUD_FIELD_NAMES: string[];
483
556
  //#endregion
@@ -569,6 +642,12 @@ export declare function queryOne<T>(engine: EngineHandle, namespace: string, typ
569
642
  //#endregion
570
643
  //#region ../../packages/substrate-sdk/src/field.d.ts
571
644
  interface ScalarFieldOptions {
645
+ /**
646
+ * `true` builds a btree for this field. Leave it unset for no index: the
647
+ * field still filters and sorts, by scanning. `false` also means no index,
648
+ * and marks the field as not a search handle (long-form prose), so NL
649
+ * leaves it out.
650
+ */
572
651
  indexed?: boolean;
573
652
  nullable?: boolean;
574
653
  /**
@@ -626,9 +705,9 @@ interface StructFieldOptions {
626
705
  }
627
706
  interface ListFieldOptions {
628
707
  /**
629
- * Opt the list field into server-side `has` (element-membership) filtering
630
- * without `_allowTableScan`. The substrate binary auto-derives the backing GIN as
631
- * a tracked migration at boot — no per-field migration to author.
708
+ * Back the list field's `has` (element-membership) filter with a GIN, which
709
+ * the substrate binary derives as a tracked migration at boot — no per-field
710
+ * migration to author. Without it `has` still works, by scanning.
632
711
  * Default false. See `FieldDefList.indexed`.
633
712
  */
634
713
  indexed?: boolean;
@@ -673,8 +752,7 @@ export declare const field: {
673
752
  * JSON body. Value round-trips unchanged. Filter a value INSIDE it with a
674
753
  * path predicate — `{ values: { path: ['year'], gt: 1990 } }` — which is
675
754
  * type-strict. `eq` / `in` / `has` are index-served only with
676
- * `{ indexed: true }`; everything else scans the type's rows and needs
677
- * `_allowTableScan`. No ordering. When inner keys are known at schema time,
755
+ * `{ indexed: true }`; everything else scans the type's rows. No ordering. When inner keys are known at schema time,
678
756
  * `field.struct` is still the better fit: declared, indexed, orderable.
679
757
  */
680
758
  json(opts?: JsonFieldOptions): FieldDefScalar;
@@ -691,4 +769,4 @@ export declare function resolveEntityId(dataset: Dataset, type: string, input: I
691
769
  */
692
770
  export declare function resolveEntityRow(dataset: Dataset, type: string, input: Id): Promise<Row | null>;
693
771
  //#endregion
694
- export { ADMIN_CAPABILITIES, ActorIdentity, type AdminCredential, type AdminEnv, AfterTxWork, AutoCrudVerb, BridgeClient, BridgeCredential, BridgeCredentialStore, BridgeFrame, BridgeRegistry, BridgeUnreachableError, CLIENT_SUPPLIED_SERVER_FIELD, CanDeleteResult, ClientSuppliedServerFieldError, ConditionalUpdateResult, CoordinatorPlugin, type CrossRefFieldOptions, DEFAULT_CAPABILITIES, Dataset, DatasetRegistry, type DateFieldOptions, type DefineNamespaceOptions, DeleteResult, type DeleteRowArgs, type DeleteRowResult, DropParticipant, DropResult, Edge, EdgePatch, EdgeRef, EdgeWriteInput, EdgesStore, EmbedSourceContext, EncodeContext, EngineHandle, EngineInput, EnvelopeShape, FieldDef, FieldDefCrossRef, FieldDefList, FieldDefScalar, FieldDefStruct, FieldInput, FieldKind, FieldPredicate, FilterCapabilities, FilterOperatorDef, FrameEntry, type Grant, HttpHandler, HttpMethod, Id, IdempotencyStore, Identity, IdentityKind, type JsonFieldOptions, KernelLifecycleContext, KernelMigration, KernelMigrationContext, KernelNamespaceContribution, KernelPlugin, KernelRouteClaim, type KeyMutationRefusal, type KeyUpdateRefusal, type ListFieldOptions, McpToolRegistration, MissingReferentError, MutationSchema, NLBase, NLResult, NLVocabularyHint, NamespaceConfig, NamespaceDefinition, NamespaceInstallContext, NamespaceMismatch, NamespaceTypeDef, NlAskRequest, NlAskResult, NlEvidence, NlJudgeAction, NlJudgeChoice, NlJudgeStep, NlJudgedStatus, NlNamespacePack, NlNamespaceRulings, NlOutcome, NlPackField, NlPackType, NlPackValueRef, NlParseStatus, NlParsedData, NlServedPack, NlTrailEvent, NlValueAlias, NlWireEvent, Obligation, OnDelete, OnMissing, OrderByClause, PackEnvelope, PluginLifecycleContext, PluginRouteContext, PluginRouter, Policy, PolicyDecision, PolicyProbeContext, PostWriteHook, ProcessStat, QualifiedFrame, Query, ROW_METADATA_FIELDS, ReadParams, ReadResult, Registry, RegistryBase, RegistryEntry, RegistryEntryInput, RegistryEntryKind, RegistryEntryResolver, RequestContext, RequestObservation, RequestObserver, ReservedField, ResolveObservation, ResolveTarget, Resolver, ResolverArgs, ResolverFrameError, ResolverReturn, ResolverStat, RestrictViolation, Row, RowFilterObligation, RowMetadata, RowMetadataField, RuntimeErrorEntry, RuntimeErrors, RuntimeMetrics, RuntimeOp, SYSTEM_NAMESPACE, type ScalarFieldOptions, ScheduledTask, ScheduledTaskContext, Schema, SlowRequest, StartOpts, type StructFieldOptions, SubstrateRequest, SubstrateResponse, SubstrateServer, SweepDeps, SweepState, TargetState, TlsConfig, type TokenProviderOpts, TxScopeHandles, type TypeInput, TypeSchema, TypedResolver, UnsupportedFilterError, UpdateFieldRef, type UpdateResolverOptions, VirtualMutationDef, VirtualTypeDef, WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, WS_REASON_SERVER_RESTART, WS_REASON_SUBSCRIPTION_OVERLOADED, WhereClause, WriteEvent, WriteOptions, WriteResult, WsConnection, WsHandler, WsRequestFrame, WsResponseFrame, WsResponseKind, adminClaimCapabilities, allowAll, allowVerbs, and, applyRowFilters, capabilitiesFor, checkRevocable, checkUpdatable, decodeList, denyAll, denyVerbs, describeGrant, encodeGrant, encodeList, expandFlat, flattenGrant, grantCovers, grantEntriesConfer, grantEntryError, grantIsUniform, intersectGrants, isActiveAdminKeyRow, isAuthCause, isEncryptedKey, isResolverFrameError, isRestrictViolation, makeAuthorizationProvider, makeTokenProvider, newlyGranted, newlyGrantedPairs, not, or, parseGrantEntries, requireCapability, requireIdentity, requireNamespace, resolveAdminCredential, resolveDefaultKeyPath, resolveDefaultKidPath, revokedAtIso, row };
772
+ export { ADMIN_CAPABILITIES, ActorIdentity, type AdminCredential, type AdminEnv, AfterTxWork, AutoCrudVerb, BridgeClient, BridgeCredential, BridgeCredentialStore, BridgeFrame, BridgeRegistry, BridgeUnreachableError, CLIENT_SUPPLIED_SERVER_FIELD, CanDeleteResult, ClientSuppliedServerFieldError, ConditionalUpdateResult, CoordinatorPlugin, type CrossRefFieldOptions, DEFAULT_CAPABILITIES, DEFAULT_ORDERED_BY, Dataset, DatasetRegistry, type DateFieldOptions, type DefineNamespaceOptions, DeleteResult, type DeleteRowArgs, type DeleteRowResult, DropParticipant, DropResult, Edge, EdgePatch, EdgeRef, EdgeWriteInput, EdgesStore, EmbedSourceContext, EncodeContext, EngineHandle, EngineInput, EnvelopeShape, FieldDef, FieldDefCrossRef, FieldDefList, FieldDefScalar, FieldDefStruct, FieldInput, FieldKind, FieldPredicate, FilterCapabilities, FilterOperatorDef, FrameEntry, type Grant, HttpHandler, HttpMethod, Id, IdempotencyStore, Identity, IdentityKind, IndexDecl, IndexPlan, type JsonFieldOptions, KernelLifecycleContext, KernelMigration, KernelMigrationContext, KernelNamespaceContribution, KernelPlugin, KernelRouteClaim, type KeyMutationRefusal, type KeyUpdateRefusal, type ListFieldOptions, McpToolRegistration, MissingReferentError, MutationSchema, NLBase, NLResult, NLVocabularyHint, NamespaceConfig, NamespaceDefinition, NamespaceInstallContext, NamespaceMismatch, NamespaceTypeDef, NlAskRequest, NlAskResult, NlEvidence, NlJudgeAction, NlJudgeChoice, NlJudgeStep, NlJudgedStatus, NlNamespacePack, NlNamespaceRulings, NlOutcome, NlPackField, NlPackType, NlPackValueRef, NlParseStatus, NlParsedData, NlServedPack, NlTrailEvent, NlValueAlias, NlWireEvent, Obligation, OnDelete, OnMissing, OrderByClause, OrderedBy, PackEnvelope, PluginLifecycleContext, PluginRouteContext, PluginRouter, Policy, PolicyDecision, PolicyProbeContext, PostWriteHook, ProcessStat, QualifiedFrame, Query, ROW_METADATA_FIELDS, ReadParams, ReadResult, Registry, RegistryBase, RegistryEntry, RegistryEntryInput, RegistryEntryKind, RegistryEntryResolver, RequestContext, RequestObservation, RequestObserver, ReservedField, ResolveObservation, ResolveTarget, Resolver, ResolverArgs, ResolverFrameError, ResolverReturn, ResolverStat, RestrictViolation, Row, RowFilterObligation, RowMetadata, RowMetadataField, RuntimeErrorEntry, RuntimeErrors, RuntimeMetrics, RuntimeOp, SYSTEM_NAMESPACE, type ScalarFieldOptions, ScheduledTask, ScheduledTaskContext, Schema, SlowRequest, StartOpts, StorageReport, type StructFieldOptions, SubstrateRequest, SubstrateResponse, SubstrateServer, SweepDeps, SweepState, TargetState, TlsConfig, type TokenProviderOpts, TxScopeHandles, TypeIndexState, type TypeInput, TypeSchema, TypeStats, TypeStorageReport, TypedResolver, UnsupportedFilterError, UpdateFieldRef, type UpdateResolverOptions, VirtualMutationDef, VirtualTypeDef, WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, WS_REASON_SERVER_RESTART, WS_REASON_SUBSCRIPTION_OVERLOADED, WhereClause, WriteEvent, WriteOptions, WriteResult, WriteRow, WsConnection, WsHandler, WsRequestFrame, WsResponseFrame, WsResponseKind, adminClaimCapabilities, allowAll, allowVerbs, and, applyRowFilters, assertNoRepeatedIds, capabilitiesFor, checkRevocable, checkUpdatable, decodeList, denyAll, denyVerbs, describeGrant, encodeGrant, encodeList, expandFlat, flattenGrant, grantCovers, grantEntriesConfer, grantEntryError, grantIsUniform, intersectGrants, isActiveAdminKeyRow, isAuthCause, isEncryptedKey, isResolverFrameError, isRestrictViolation, makeAuthorizationProvider, makeTokenProvider, naturalOrderOf, newlyGranted, newlyGrantedPairs, not, or, parseGrantEntries, requireCapability, requireIdentity, requireNamespace, resolveAdminCredential, resolveDefaultKeyPath, resolveDefaultKidPath, revokedAtIso, row };
package/dist/sdk.js CHANGED
@@ -1,112 +1,7 @@
1
1
  import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
- import { $ as error400, A as resolveIdentity, At as CLIENT_SUPPLIED_SERVER_FIELD, C as purgeResolver, Ct as ReservedField, D as deleteRow, Dt as isAuthCause, E as deleteResolver, Et as UnsupportedFilterError, M as resolveEntityRow, Mt as canonicalize, Nt as BootstrapConfigError, O as createResolver, Ot as isResolverFrameError, Pt as defineBootstrap, S as updateResolver, St as NamespaceMismatch, T as getResolver, Tt as RestrictViolation, Z as JSON_HEADERS, _ as field, _t as createKeyedMutex, at as WS_REASON_SERVER_RESTART, b as installAutoCrud, bt as BridgeUnreachableError, ct as normaliseVocabValues, dt as vocabImplication, et as jsonResponse, ft as RegistryBase, g as RESERVED_AUTOCRUD_FIELD_NAMES, gt as normaliseMetadataWhere, h as RESERVED_AUTOCRUD_FIELDS, ht as normaliseMetadataOrderBy, it as WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, j as resolveEntityId, jt as ROW_METADATA_FIELDS, k as UnattributedWriteError, kt as isRestrictViolation, lt as normaliseVocabWhere, m as defineNamespace, mt as METADATA_FILTER_FIELDS, ot as WS_REASON_SUBSCRIPTION_OVERLOADED, pt as METADATA_AUTHOR_FIELDS, st as canonicalVocabValue, tt as parseJsonBody, ut as storedVocabSpellings, v as autoCrudOptionsOf, vt as assertHardDeleteAllowed, w as listResolver, wt as ResolverFrameError, x as applyUpdatePatch, xt as MissingReferentError, y as createResolverWithEdges, yt as validateHardDeleteEnv } from "./src-YXlv_RyL.js";
3
- import { a as makeAuthorizationProvider, c as resolveDefaultKeyPath, i as isEncryptedKey, l as resolveDefaultKidPath, n as DEFAULT_CAPABILITIES, o as makeTokenProvider, r as adminClaimCapabilities, s as resolveAdminCredential, t as ADMIN_CAPABILITIES } from "./agent-token-BIboWOU0.js";
4
- import { A as expandFlat, C as not, D as isActiveAdminKeyRow, E as describeGrant, F as parseGrantEntries, I as decodeList, L as encodeList, M as grantEntryError, N as grantIsUniform, O as capabilitiesFor, P as intersectGrants, S as and, T as SYSTEM_NAMESPACE, _ as grantCovers, a as denyAll, b as newlyGrantedPairs, c as requireIdentity, d as confersAnywhere, f as coversNamespace, g as checkUpdatable, h as checkRevocable, i as allowVerbs, j as flattenGrant, k as encodeGrant, l as requireNamespace, m as grantedIn, n as row, o as denyVerbs, p as grantOf, r as allowAll, s as requireCapability, t as applyRowFilters, u as allCapabilities, v as grantEntriesConfer, w as or, x as revokedAtIso, y as newlyGranted } from "./row-DK7lPZVe.js";
5
- import { S as assertNever, b as formatQualifiedKey, x as parseQualifiedKey } from "./src-C4DzaIQZ.js";
6
- import { t as parsePositiveInt } from "./env-utils-B7SGmoeJ.js";
2
+ import { A as createResolverWithEdges, At as normaliseMetadataWhere, B as UnattributedWriteError, Bt as ReservedField, C as queryOne, Ct as normaliseVocabWhere, D as isReservedAutoCrudField, Dt as METADATA_AUTHOR_FIELDS, E as RESERVED_AUTOCRUD_FIELD_NAMES, Et as RegistryBase, F as listResolver, Ft as assertHardDeleteAllowed, Gt as isResolverFrameError, H as resolveEntityId, Ht as RestrictViolation, I as getResolver, It as validateHardDeleteEnv, Jt as ROW_METADATA_FIELDS, Kt as isRestrictViolation, L as deleteResolver, Lt as BridgeUnreachableError, M as applyUpdatePatch, Mt as isImpossibleIsoTimestamp, N as updateResolver, Nt as isIsoTimestamp, O as field, Ot as METADATA_FILTER_FIELDS, P as purgeResolver, Pt as normalizeIsoTimestamp, Qt as defineBootstrap, R as deleteRow, Rt as MissingReferentError, S as queryAll, St as normaliseVocabValues, T as RESERVED_AUTOCRUD_FIELDS, Tt as vocabImplication, U as resolveEntityRow, Ut as UnsupportedFilterError, V as resolveIdentity, Vt as ResolverFrameError, Wt as isAuthCause, Xt as canonicalize, Yt as assertNoRepeatedIds, Zt as BootstrapConfigError, _ as assertIndexDecl, b as EngineQueryError, bt as WS_REASON_SUBSCRIPTION_OVERLOADED, dt as JSON_HEADERS, ht as parseJsonBody, j as installAutoCrud, jt as createKeyedMutex, k as autoCrudOptionsOf, kt as normaliseMetadataOrderBy, mt as jsonResponse, pt as error400, qt as CLIENT_SUPPLIED_SERVER_FIELD, v as assertOrderedBy, vt as WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, w as selectAll, wt as storedVocabSpellings, x as makeCtx, xt as canonicalVocabValue, y as defineNamespace, yt as WS_REASON_SERVER_RESTART, z as createResolver, zt as NamespaceMismatch } from "./src-5SJ5GEIM.js";
3
+ import { a as adminClaimCapabilities, c as makeTokenProvider, d as resolveDefaultKidPath, i as DEFAULT_CAPABILITIES, l as resolveAdminCredential, n as trimTrailingSlashes, o as isEncryptedKey, r as ADMIN_CAPABILITIES, s as makeAuthorizationProvider, t as parsePositiveInt, u as resolveDefaultKeyPath } from "./env-utils-CGNazUNt.js";
4
+ import { A as expandFlat, C as not, D as isActiveAdminKeyRow, E as describeGrant, F as parseGrantEntries, I as decodeList, L as encodeList, M as grantEntryError, N as grantIsUniform, O as capabilitiesFor, P as intersectGrants, S as and, T as SYSTEM_NAMESPACE, _ as grantCovers, a as denyAll, b as newlyGrantedPairs, c as requireIdentity, d as confersAnywhere, f as coversNamespace, g as checkUpdatable, h as checkRevocable, i as allowVerbs, j as flattenGrant, k as encodeGrant, l as requireNamespace, m as grantedIn, n as row, o as denyVerbs, p as grantOf, r as allowAll, s as requireCapability, t as applyRowFilters, u as allCapabilities, v as grantEntriesConfer, w as or, x as revokedAtIso, y as newlyGranted } from "./src-Da0t6si5.js";
5
+ import { C as parseQualifiedKey, S as formatQualifiedKey, b as DEFAULT_ORDERED_BY, w as assertNever, x as naturalOrderOf } from "./src-hZb8wfvg.js";
7
6
 
8
- //#region ../../packages/substrate-sdk/src/engine-helpers.ts
9
- /**
10
- * Engine-call helpers for coordinator/plugin authors.
11
- *
12
- * Run an internal engine query or build a request context from inside a
13
- * plugin route or scheduled task, so coordinators share one implementation.
14
- *
15
- * Depends only on `@mnmal-ai/substrate-types`; this package must not take a
16
- * runtime dependency on `substrate-core`.
17
- */
18
- /**
19
- * Build a minimal `Partial<RequestContext>` for a plugin's engine call.
20
- *
21
- * PASS THE CALLER'S IDENTITY WHENEVER THERE IS ONE. Omitting it yields the
22
- * SYSTEM ACTOR (`identity: null`), which the engine's per-frame namespace gate
23
- * waves through unconditionally — correct for genuinely system-initiated work
24
- * (a scheduled sweep, a liveness probe), and a privilege escalation for
25
- * anything a caller asked for. A plugin route that omits it lets a caller reach
26
- * namespaces their grant does not cover, because the route gate checks a
27
- * capability without a namespace and the engine gate then checks a namespace
28
- * without an identity.
29
- *
30
- * The distinction is WHO ASKED, not which plugin.
31
- */
32
- function makeCtx(namespace, operation, identity = null) {
33
- return {
34
- identity,
35
- namespace,
36
- operation,
37
- now: /* @__PURE__ */ new Date(),
38
- headers: {},
39
- meta: {}
40
- };
41
- }
42
- /**
43
- * A frame the engine REFUSED, surfaced as a throw rather than as an empty result.
44
- *
45
- * Substrate returns a partial-success envelope: a rejected frame comes back with its
46
- * key ABSENT from `data` and the reason in `errors`. Without this, `queryOne` /
47
- * `queryAll` would render a refusal as `null` / `[]`, indistinguishable from a
48
- * query that matched nothing.
49
- */
50
- var EngineQueryError = class extends Error {
51
- name = "EngineQueryError";
52
- code;
53
- constructor(code, message) {
54
- super(message);
55
- this.code = code;
56
- }
57
- };
58
- /** Throw when the envelope carries an error, so a refusal cannot read as absence. */
59
- function assertNoFrameError(env, key) {
60
- const err = env.errors?.[0];
61
- if (err !== void 0) throw new EngineQueryError(err.code ?? "query_failed", err.message ?? `${key} was refused`);
62
- }
63
- /** Expand a list of field names into the `{ field: true }` selection map. */
64
- function selectAll(fields) {
65
- const out = {};
66
- for (const f of fields) out[f] = true;
67
- return out;
68
- }
69
- /** Accept either a field-name list or an already-built selection map. */
70
- function toSelection(fields) {
71
- return Array.isArray(fields) ? selectAll(fields) : fields;
72
- }
73
- /**
74
- * Run an internal engine query and return the row list (empty when the frame
75
- * resolves to nothing). `fields` may be a name list or a prebuilt selection map.
76
- */
77
- async function queryAll(engine, namespace, typeName, params, fields, identity = null) {
78
- const key = formatQualifiedKey(namespace, typeName);
79
- const env = await engine.query({
80
- frame: { [key]: {
81
- params,
82
- fields: toSelection(fields)
83
- } },
84
- ctx: makeCtx(namespace, "query", identity)
85
- });
86
- assertNoFrameError(env, key);
87
- const rows = env.data[key];
88
- if (rows === void 0 || rows === null) return [];
89
- return rows;
90
- }
91
- /**
92
- * Run an internal engine query expecting at most one row; returns the first
93
- * row or null. `fields` may be a name list or a prebuilt selection map.
94
- */
95
- async function queryOne(engine, namespace, typeName, params, fields, identity = null) {
96
- const key = formatQualifiedKey(namespace, typeName);
97
- const env = await engine.query({
98
- frame: { [key]: {
99
- params,
100
- fields: toSelection(fields)
101
- } },
102
- ctx: makeCtx(namespace, "query", identity)
103
- });
104
- assertNoFrameError(env, key);
105
- const rows = env.data[key];
106
- if (rows === void 0 || rows === null) return null;
107
- if (Array.isArray(rows)) return rows[0] ?? null;
108
- return rows;
109
- }
110
-
111
- //#endregion
112
- export { ADMIN_CAPABILITIES, BootstrapConfigError, BridgeUnreachableError, CLIENT_SUPPLIED_SERVER_FIELD, DEFAULT_CAPABILITIES, EngineQueryError, JSON_HEADERS, METADATA_AUTHOR_FIELDS, METADATA_FILTER_FIELDS, MissingReferentError, NamespaceMismatch, RESERVED_AUTOCRUD_FIELDS, RESERVED_AUTOCRUD_FIELD_NAMES, ROW_METADATA_FIELDS, RegistryBase, ReservedField, ResolverFrameError, RestrictViolation, SYSTEM_NAMESPACE, UnattributedWriteError, UnsupportedFilterError, WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, WS_REASON_SERVER_RESTART, WS_REASON_SUBSCRIPTION_OVERLOADED, adminClaimCapabilities, allCapabilities, allowAll, allowVerbs, and, applyRowFilters, applyUpdatePatch, assertHardDeleteAllowed, assertNever, autoCrudOptionsOf, canonicalVocabValue, canonicalize, capabilitiesFor, checkRevocable, checkUpdatable, confersAnywhere, coversNamespace, createKeyedMutex, createResolver, createResolverWithEdges, decodeList, defineBootstrap, defineNamespace, deleteResolver, deleteRow, denyAll, denyVerbs, describeGrant, encodeGrant, encodeList, error400, expandFlat, field, flattenGrant, formatQualifiedKey, getResolver, grantCovers, grantEntriesConfer, grantEntryError, grantIsUniform, grantOf, grantedIn, installAutoCrud, intersectGrants, isActiveAdminKeyRow, isAuthCause, isEncryptedKey, isResolverFrameError, isRestrictViolation, jsonResponse, listResolver, makeAuthorizationProvider, makeCtx, makeTokenProvider, newlyGranted, newlyGrantedPairs, normaliseMetadataOrderBy, normaliseMetadataWhere, normaliseVocabValues, normaliseVocabWhere, not, or, parseGrantEntries, parseJsonBody, parsePositiveInt, parseQualifiedKey, purgeResolver, queryAll, queryOne, requireCapability, requireIdentity, requireNamespace, resolveAdminCredential, resolveDefaultKeyPath, resolveDefaultKidPath, resolveEntityId, resolveEntityRow, resolveIdentity, revokedAtIso, row, selectAll, storedVocabSpellings, updateResolver, validateHardDeleteEnv, vocabImplication };
7
+ export { ADMIN_CAPABILITIES, BootstrapConfigError, BridgeUnreachableError, CLIENT_SUPPLIED_SERVER_FIELD, DEFAULT_CAPABILITIES, DEFAULT_ORDERED_BY, EngineQueryError, JSON_HEADERS, METADATA_AUTHOR_FIELDS, METADATA_FILTER_FIELDS, MissingReferentError, NamespaceMismatch, RESERVED_AUTOCRUD_FIELDS, RESERVED_AUTOCRUD_FIELD_NAMES, ROW_METADATA_FIELDS, RegistryBase, ReservedField, ResolverFrameError, RestrictViolation, SYSTEM_NAMESPACE, UnattributedWriteError, UnsupportedFilterError, WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, WS_REASON_SERVER_RESTART, WS_REASON_SUBSCRIPTION_OVERLOADED, adminClaimCapabilities, allCapabilities, allowAll, allowVerbs, and, applyRowFilters, applyUpdatePatch, assertHardDeleteAllowed, assertIndexDecl, assertNever, assertNoRepeatedIds, assertOrderedBy, autoCrudOptionsOf, canonicalVocabValue, canonicalize, capabilitiesFor, checkRevocable, checkUpdatable, confersAnywhere, coversNamespace, createKeyedMutex, createResolver, createResolverWithEdges, decodeList, defineBootstrap, defineNamespace, deleteResolver, deleteRow, denyAll, denyVerbs, describeGrant, encodeGrant, encodeList, error400, expandFlat, field, flattenGrant, formatQualifiedKey, getResolver, grantCovers, grantEntriesConfer, grantEntryError, grantIsUniform, grantOf, grantedIn, installAutoCrud, intersectGrants, isActiveAdminKeyRow, isAuthCause, isEncryptedKey, isImpossibleIsoTimestamp, isIsoTimestamp, isReservedAutoCrudField, isResolverFrameError, isRestrictViolation, jsonResponse, listResolver, makeAuthorizationProvider, makeCtx, makeTokenProvider, naturalOrderOf, newlyGranted, newlyGrantedPairs, normaliseMetadataOrderBy, normaliseMetadataWhere, normaliseVocabValues, normaliseVocabWhere, normalizeIsoTimestamp, not, or, parseGrantEntries, parseJsonBody, parsePositiveInt, parseQualifiedKey, purgeResolver, queryAll, queryOne, requireCapability, requireIdentity, requireNamespace, resolveAdminCredential, resolveDefaultKeyPath, resolveDefaultKidPath, resolveEntityId, resolveEntityRow, resolveIdentity, revokedAtIso, row, selectAll, storedVocabSpellings, trimTrailingSlashes, updateResolver, validateHardDeleteEnv, vocabImplication };