@mnmal-ai/substrate 1.0.0-beta.3 → 1.0.0-beta.5

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.
@@ -1,11 +1,11 @@
1
- import { A as isReservedAutoCrudField, Gt as WS_REASON_SERVER_RESTART, Ht as parseAuthConfig, It as HttpBridgeClient, Rt as buildContext, Vn as DEFAULT_FILTER_WRITE_LIMITS, Z as MemoryEdgesStore, _ as AUDIT_EVENT_TYPE, a as composeFromManifests, bt as registerExtensionOperator, c as MemoryDataset, et as effectiveFilterOperators, g as buildAuditRow, h as SYSTEM_TYPE_DEFS, i as PluginLoadError, n as kernelMigrationTracking, o as DEFAULT_NAMESPACE, r as mountKernelRoute, s as compose, t as composeKernelPlugins, u as isStoreProfileName, vt as getExtensionOperator, xt as unregisterExtensionOperator, yt as listExtensionOperators } from "./src-WYba7eEl.js";
1
+ import { A as isReservedAutoCrudField, Gt as WS_REASON_SERVER_RESTART, Ht as parseAuthConfig, It as HttpBridgeClient, Rt as buildContext, Vn as DEFAULT_FILTER_WRITE_LIMITS, Z as MemoryEdgesStore, _ as AUDIT_EVENT_TYPE, a as composeFromManifests, bt as registerExtensionOperator, c as MemoryDataset, et as effectiveFilterOperators, g as buildAuditRow, h as SYSTEM_TYPE_DEFS, i as PluginLoadError, n as kernelMigrationTracking, o as DEFAULT_NAMESPACE, r as mountKernelRoute, s as compose, t as composeKernelPlugins, u as isStoreProfileName, vt as getExtensionOperator, xt as unregisterExtensionOperator, yt as listExtensionOperators } from "./src-DR8cwQtS.js";
2
2
  import { a as adminClaimCapabilities, d as resolveDefaultKidPath, l as resolveAdminCredential, n as trimTrailingSlashes, r as ADMIN_CAPABILITIES, s as makeAuthorizationProvider, t as parsePositiveInt, u as resolveDefaultKeyPath } from "./env-utils-s25Z1YSA.js";
3
3
  import { D as isActiveAdminKeyRow, E as describeGrant, L as encodeList, M as grantEntryError, T as SYSTEM_NAMESPACE, v as grantEntriesConfer } from "./src-DmiUWOLp.js";
4
4
  import { r as FRAMES_JSON_MIME, s as decodeStreamFrames, u as withIdleTimeout } from "./src-B_kHkbsr.js";
5
- import { C as diagnose, S as DIAGNOSE_CHECKS, T as substrateFetch, _ as SKIPPABLE_STEPS, b as planOnboarding, h as CURRENT_MARK, i as tokenAudience, v as STEP_MARKS, x as requiredOutstanding, y as currentStep } from "./src-FXO5JPyk.js";
6
- import { b as runMigrations, g as deriveListIndexMigration, h as assertTablesLayout, n as PgEdgesStore, p as assertNotMigrating, r as PgDataset, t as PgIdempotencyStore, v as pendingMigrations, y as runDerivedMigrations } from "./src-DQMA57_1.js";
7
- import { a as InMemoryLexicalStore, i as PgClusterStore, n as PgLexicalStore, o as InMemoryEmbeddingsStore, r as PgEmbeddingsStore, s as InMemoryClusterStore } from "./src-D-UHaQiB.js";
8
- import { et as memberKey } from "./plugin-DkYf0ng8.js";
5
+ import { C as diagnose, S as DIAGNOSE_CHECKS, T as substrateFetch, _ as SKIPPABLE_STEPS, b as planOnboarding, h as CURRENT_MARK, i as tokenAudience, v as STEP_MARKS, x as requiredOutstanding, y as currentStep } from "./src-Bvl6kSZl.js";
6
+ import { b as runMigrations, g as deriveListIndexMigration, h as assertTablesLayout, n as PgEdgesStore, p as assertNotMigrating, r as PgDataset, t as PgIdempotencyStore, v as pendingMigrations, y as runDerivedMigrations } from "./src-CTufEe7y.js";
7
+ import { a as InMemoryLexicalStore, i as PgClusterStore, n as PgLexicalStore, o as InMemoryEmbeddingsStore, r as PgEmbeddingsStore, s as InMemoryClusterStore } from "./src-Dk_JtkUH.js";
8
+ import { et as memberKey } from "./plugin-DLBoldt-.js";
9
9
  import { existsSync, linkSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
10
  import { homedir } from "node:os";
11
11
  import { basename, dirname, join, resolve } from "node:path";
@@ -1753,7 +1753,7 @@ async function closeQuietly(sql) {
1753
1753
 
1754
1754
  //#endregion
1755
1755
  //#region package.json
1756
- var version = "1.0.0-beta.3";
1756
+ var version = "1.0.0-beta.5";
1757
1757
 
1758
1758
  //#endregion
1759
1759
  //#region src/plugin-manifest.ts
@@ -1,12 +1,12 @@
1
- import { _ as AUDIT_EVENT_TYPE, g as buildAuditRow, it as saveSweepState, m as runInviteSweep, mn as validateHardDeleteEnv, nt as loadSweepState, rt as runSweep, u as isStoreProfileName, v as INVITE_TYPE } from "./src-WYba7eEl.js";
1
+ import { _ as AUDIT_EVENT_TYPE, g as buildAuditRow, it as saveSweepState, m as runInviteSweep, mn as validateHardDeleteEnv, nt as loadSweepState, rt as runSweep, u as isStoreProfileName, v as INVITE_TYPE } from "./src-DR8cwQtS.js";
2
2
  import { n as trimTrailingSlashes, s as makeAuthorizationProvider } from "./env-utils-s25Z1YSA.js";
3
3
  import { L as encodeList, T as SYSTEM_NAMESPACE, f as coversNamespace, m as grantedIn, p as grantOf } from "./src-DmiUWOLp.js";
4
4
  import { B as EXPR_AGGREGATES, H as EXPR_LIMITS, V as EXPR_FUNCTIONS, z as DATE_UNITS } from "./src-B_kHkbsr.js";
5
- import { X as AdminCliError, _ as version, a as MS_PER_DAY, c as parseEnv, d as redactStoreSpec, h as startSentinelClient, m as runDeferredIndexBuilds, n as resolvePluginDir, o as parseBridgeCreds, p as reportUnguardedIndexBuilds, s as parseBridges, t as bootStore, v as openPgDataset } from "./boot-store-u_1PJSvo.js";
6
- import { T as substrateFetch, a as SubstrateClient, d as NetworkError, i as tokenAudience, n as resolveAgentCapabilities, p as AdminBackfillError, r as noRedirectFetch, t as createClientFromEnv, u as AuthError } from "./src-FXO5JPyk.js";
7
- import { n as runScript, t as DEFAULT_MAX_WRITES } from "./script-ByQ9pzhC.js";
8
- import { D as tryWithPgAdvisoryLock } from "./src-DQMA57_1.js";
9
- import { n as PgLexicalStore, r as PgEmbeddingsStore } from "./src-D-UHaQiB.js";
5
+ import { X as AdminCliError, _ as version, a as MS_PER_DAY, c as parseEnv, d as redactStoreSpec, h as startSentinelClient, m as runDeferredIndexBuilds, n as resolvePluginDir, o as parseBridgeCreds, p as reportUnguardedIndexBuilds, s as parseBridges, t as bootStore, v as openPgDataset } from "./boot-store-8T3XN40r.js";
6
+ import { T as substrateFetch, a as SubstrateClient, d as NetworkError, i as tokenAudience, n as resolveAgentCapabilities, p as AdminBackfillError, r as noRedirectFetch, t as createClientFromEnv, u as AuthError } from "./src-Bvl6kSZl.js";
7
+ import { n as runScript, t as DEFAULT_MAX_WRITES } from "./script-BgIowI9n.js";
8
+ import { D as tryWithPgAdvisoryLock } from "./src-CTufEe7y.js";
9
+ import { n as PgLexicalStore, r as PgEmbeddingsStore } from "./src-Dk_JtkUH.js";
10
10
  import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
11
11
  import { homedir, hostname, tmpdir } from "node:os";
12
12
  import { basename, dirname, join, resolve } from "node:path";
@@ -2165,7 +2165,7 @@ async function runInit(argv) {
2165
2165
  return 1;
2166
2166
  }
2167
2167
  if (!config.yes) try {
2168
- const { runRepl } = await import("./repl-Bm2nSvCW.js");
2168
+ const { runRepl } = await import("./repl-DDaLbsTM.js");
2169
2169
  config = await runRepl(config);
2170
2170
  } catch (err) {
2171
2171
  if (err.message?.includes("User force closed")) return 130;
@@ -3110,7 +3110,7 @@ function createMcpServer(endpoint, options = {}) {
3110
3110
  {
3111
3111
  name: "run",
3112
3112
  config: {
3113
- description: "Sandboxed script for 3+ dependent calls (paging, joins, read-driven writes). `script`: a module exporting default `async (s) => result`; type syntax is stripped. `s`: kid, mode, args, query(frame) (throws if refused), queryAll(key, { params, fields }), byShortId(key, n | n[], fields?), recall({ query, namespace, type, k?, where?, row? }), schema(ns?, type?), mutate(frame), log(). Modes: \"read\" (default; refuses mutate), \"dry-run\" (records, sends nothing), \"write\". Dry-run, check report.mutations, then write. Return ids/counts.",
3113
+ description: "Sandboxed script for 3+ dependent calls (paging, joins, read-driven writes). `script`: default export `async (s) => result`; type syntax is stripped. `s`: kid, mode, args, query(frame | key, entry) (throws if refused), queryAll(key, { params, fields }), byShortId(key, n | n[], fields?), recall({ query, namespace, type, k?, where?, row? }), schema(ns?, type?), mutate(frame | key, entry), log(). Modes: \"read\" (default, no mutate), \"dry-run\" (records only), \"write\". Dry-run, check report.mutations, then write. Return ids/counts.",
3114
3114
  inputSchema: {
3115
3115
  script: z.string().min(1).describe("e.g. export default async (s) => (await s.queryAll('ns/Todo', {})).length"),
3116
3116
  args: z.record(z.string(), z.unknown()).optional().describe("Passed as s.args"),
@@ -1998,7 +1998,9 @@ var HttpTransport = class {
1998
1998
  };
1999
1999
  throw new AuthError(`${res.status === 401 ? "Unauthorised" : "Forbidden"}: ${url}`, res.status, info);
2000
2000
  }
2001
- throw new NetworkError(`${res.status} from ${url}`, null, await errorInfo(res));
2001
+ const info = await errorInfo(res);
2002
+ const reason = [info.code, info.serverMessage].filter((s) => s !== void 0).join(": ");
2003
+ throw new NetworkError(`${res.status} from ${url}${reason ? `: ${reason}` : ""}`, null, info);
2002
2004
  }
2003
2005
  };
2004
2006
  /** The status plus whatever a JSON body says: the whole object as `body`, the first string of `error.message` (the recall plugin's nested shape), `error`, `message` as the message, and the first string of `error.code`, `code` as the code. Non-JSON bodies leave the status alone. */
@@ -2315,6 +2317,18 @@ function flatFrame(frame) {
2315
2317
 
2316
2318
  //#endregion
2317
2319
  //#region ../../packages/substrate-client/src/script.ts
2320
+ /**
2321
+ * The frame for `query`/`mutate`, called either way: `(frame)` or `(key, entry)`.
2322
+ * Anything else throws naming both forms, rather than reaching the server as a non-frame body.
2323
+ */
2324
+ function frameOf(op, frameOrKey, entry) {
2325
+ if (typeof frameOrKey === "string") {
2326
+ if (entry !== void 0 && (entry === null || typeof entry !== "object")) throw new Error(`s.${op}('${frameOrKey}', entry): entry must be { params?, fields? }, got ${entry === null ? "null" : typeof entry}`);
2327
+ return { [frameOrKey]: entry ?? {} };
2328
+ }
2329
+ if (frameOrKey === null || typeof frameOrKey !== "object" || Array.isArray(frameOrKey)) throw new Error(`s.${op} takes a frame { 'ns/Type': { params, fields } } or (key, { params, fields }), got ${frameOrKey === null ? "null" : Array.isArray(frameOrKey) ? "an array" : typeof frameOrKey}`);
2330
+ return frameOrKey;
2331
+ }
2318
2332
  const DEFAULT_MAX_WRITES = 50;
2319
2333
  const DEFAULT_MAX_PAGES = 200;
2320
2334
  /** Counts the frames in a mutate payload: an array under an op-key is one frame per element. */
@@ -2343,7 +2357,8 @@ async function runScript(script, opts) {
2343
2357
  ms: 0
2344
2358
  };
2345
2359
  const started = Date.now();
2346
- const query = async (frame) => {
2360
+ const query = async (frameOrKey, entry) => {
2361
+ const frame = frameOf("query", frameOrKey, entry);
2347
2362
  stats.queries++;
2348
2363
  const env = await client.query(frame);
2349
2364
  assertKeys(frame, env, "query");
@@ -2425,7 +2440,8 @@ async function runScript(script, opts) {
2425
2440
  if (t === void 0) throw new Error(`schema: unknown type '${namespace}/${type}'`);
2426
2441
  return t;
2427
2442
  },
2428
- async mutate(frame) {
2443
+ mutate: (async (frameOrKey, entry) => {
2444
+ const frame = frameOf("mutate", frameOrKey, entry);
2429
2445
  if (mode === "read") throw new Error("mutate refused: read mode (run in dry-run or write mode)");
2430
2446
  if (mode === "dry-run") {
2431
2447
  mutations.push({
@@ -2446,7 +2462,7 @@ async function runScript(script, opts) {
2446
2462
  });
2447
2463
  assertKeys(frame, env, "mutate");
2448
2464
  return env;
2449
- },
2465
+ }),
2450
2466
  log: (...args) => log(args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" "))
2451
2467
  };
2452
2468
  const report = (extra) => {
package/dist/client.d.ts CHANGED
@@ -815,6 +815,12 @@ interface RecallHit {
815
815
  row: RecallHitRow;
816
816
  }
817
817
  type ScriptRecallHit = RecallHit;
818
+ /** One key's entry, as queryAll takes it. */
819
+ interface ScriptFrameEntry {
820
+ params?: Record<string, unknown>;
821
+ fields?: unknown;
822
+ idempotencyKey?: string;
823
+ }
818
824
  /** What a script's default export receives. */
819
825
  interface ScriptContext {
820
826
  readonly kid: string | null;
@@ -822,10 +828,12 @@ interface ScriptContext {
822
828
  /** The caller's `--args` object; `{}` when none was passed. */
823
829
  readonly args: Readonly<Record<string, unknown>>;
824
830
  /**
825
- * One query. Throws when a requested key is missing from `data`, which is a
826
- * rejected frame, not an empty result.
831
+ * One query: a whole frame, or one key and its entry as queryAll takes them.
832
+ * Throws when a requested key is missing from `data`, which is a rejected
833
+ * frame, not an empty result.
827
834
  */
828
835
  query(frame: QualifiedFrame): Promise<PackEnvelope>;
836
+ query(key: string, entry: ScriptFrameEntry): Promise<PackEnvelope>;
829
837
  /** Every row of a single-key query, paging until `hasMore` is false. */
830
838
  queryAll(key: string, frame: {
831
839
  params?: Record<string, unknown>;
@@ -850,6 +858,7 @@ interface ScriptContext {
850
858
  * in `read`, past `maxWrites`, or when the server refuses any frame.
851
859
  */
852
860
  mutate(frame: QualifiedFrame): Promise<PackEnvelope | null>;
861
+ mutate(key: string, entry: ScriptFrameEntry | ScriptFrameEntry[]): Promise<PackEnvelope | null>;
853
862
  /** Writes to stderr; stdout carries only the result. */
854
863
  log(...args: unknown[]): void;
855
864
  }
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as adminClaimCapabilities, c as makeTokenProvider, d as resolveDefaultKidPath, i as DEFAULT_CAPABILITIES, l as resolveAdminCredential, o as isEncryptedKey, r as ADMIN_CAPABILITIES, s as makeAuthorizationProvider, u as resolveDefaultKeyPath } from "./env-utils-s25Z1YSA.js";
2
2
  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, g as checkUpdatable, h as checkRevocable, i as allowVerbs, j as flattenGrant, k as encodeGrant, l as requireNamespace, n as row, o as denyVerbs, r as allowAll, s as requireCapability, t as applyRowFilters, v as grantEntriesConfer, w as or, x as revokedAtIso, y as newlyGranted } from "./src-DmiUWOLp.js";
3
3
  import { x as SchemaDriftError } from "./src-B_kHkbsr.js";
4
- import { C as diagnose, E as createH2Fetch, S as DIAGNOSE_CHECKS, T as substrateFetch, _ as SKIPPABLE_STEPS, a as SubstrateClient, b as planOnboarding, c as reduceSubscribeRows, d as NetworkError, f as SubscribeError, g as ONBOARD_STEPS, h as CURRENT_MARK, i as tokenAudience, l as watchRows, m as BACKFILL_CHUNK, n as resolveAgentCapabilities, o as collectDiagnostics, p as AdminBackfillError, r as noRedirectFetch, s as createDefaultDiagnosticsSink, t as createClientFromEnv, u as AuthError, v as STEP_MARKS, w as reconcileIdentities, x as requiredOutstanding, y as currentStep } from "./src-FXO5JPyk.js";
5
- import { n as runScript, t as DEFAULT_MAX_WRITES } from "./script-ByQ9pzhC.js";
4
+ import { C as diagnose, E as createH2Fetch, S as DIAGNOSE_CHECKS, T as substrateFetch, _ as SKIPPABLE_STEPS, a as SubstrateClient, b as planOnboarding, c as reduceSubscribeRows, d as NetworkError, f as SubscribeError, g as ONBOARD_STEPS, h as CURRENT_MARK, i as tokenAudience, l as watchRows, m as BACKFILL_CHUNK, n as resolveAgentCapabilities, o as collectDiagnostics, p as AdminBackfillError, r as noRedirectFetch, s as createDefaultDiagnosticsSink, t as createClientFromEnv, u as AuthError, v as STEP_MARKS, w as reconcileIdentities, x as requiredOutstanding, y as currentStep } from "./src-Bvl6kSZl.js";
5
+ import { n as runScript, t as DEFAULT_MAX_WRITES } from "./script-BgIowI9n.js";
6
6
 
7
7
  export { ADMIN_CAPABILITIES, AdminBackfillError, AuthError, BACKFILL_CHUNK, CURRENT_MARK, DEFAULT_CAPABILITIES, DEFAULT_MAX_WRITES, DIAGNOSE_CHECKS, NetworkError, ONBOARD_STEPS, SKIPPABLE_STEPS, STEP_MARKS, SYSTEM_NAMESPACE, SchemaDriftError, SubscribeError, SubstrateClient, adminClaimCapabilities, allowAll, allowVerbs, and, applyRowFilters, capabilitiesFor, checkRevocable, checkUpdatable, collectDiagnostics, createClientFromEnv, createDefaultDiagnosticsSink, createH2Fetch, currentStep, decodeList, denyAll, denyVerbs, describeGrant, diagnose, encodeGrant, encodeList, expandFlat, flattenGrant, grantCovers, grantEntriesConfer, grantEntryError, grantIsUniform, intersectGrants, isActiveAdminKeyRow, isEncryptedKey, makeAuthorizationProvider, makeTokenProvider, newlyGranted, newlyGrantedPairs, noRedirectFetch, not, or, parseGrantEntries, planOnboarding, reconcileIdentities, reduceSubscribeRows, requireCapability, requireIdentity, requireNamespace, requiredOutstanding, resolveAdminCredential, resolveAgentCapabilities, resolveDefaultKeyPath, resolveDefaultKidPath, revokedAtIso, row, runScript, substrateFetch, tokenAudience, watchRows };
@@ -1,6 +1,6 @@
1
- import { Bt as jsonResponse, Rt as buildContext, tt as applyObligations, wn as ResolverFrameError } from "./src-WYba7eEl.js";
1
+ import { Bt as jsonResponse, Rt as buildContext, tt as applyObligations, wn as ResolverFrameError } from "./src-DR8cwQtS.js";
2
2
  import "./src-B_kHkbsr.js";
3
- import { w as queryTimeoutError } from "./src-DQMA57_1.js";
3
+ import { w as queryTimeoutError } from "./src-CTufEe7y.js";
4
4
  import { Worker } from "node:worker_threads";
5
5
 
6
6
  //#region ../../plugins/substrate-recall/src/candidate-selection.ts
@@ -1,5 +1,5 @@
1
- import { qn as defineBootstrap } from "./src-WYba7eEl.js";
2
- import { n as createNoopPubSub, t as createProposalsPlugin } from "./src-QOCo7BE_.js";
1
+ import { qn as defineBootstrap } from "./src-DR8cwQtS.js";
2
+ import { n as createNoopPubSub, t as createProposalsPlugin } from "./src-DPSGAy9n.js";
3
3
  import { z } from "zod";
4
4
 
5
5
  //#region ../../plugins/substrate-proposals/src/bootstrap.ts
package/dist/proposals.js CHANGED
@@ -1,3 +1,3 @@
1
- import { i as ProposalError, n as createNoopPubSub, r as storageSettled, t as createProposalsPlugin } from "./src-QOCo7BE_.js";
1
+ import { i as ProposalError, n as createNoopPubSub, r as storageSettled, t as createProposalsPlugin } from "./src-DPSGAy9n.js";
2
2
 
3
3
  export { ProposalError, createNoopPubSub, createProposalsPlugin, storageSettled };
@@ -1,6 +1,6 @@
1
- import { qn as defineBootstrap } from "./src-WYba7eEl.js";
1
+ import { qn as defineBootstrap } from "./src-DR8cwQtS.js";
2
2
  import { t as FakeEmbedder } from "./fake-DdXtb-m8.js";
3
- import { t as createRecallPlugin } from "./plugin-DkYf0ng8.js";
3
+ import { t as createRecallPlugin } from "./plugin-DLBoldt-.js";
4
4
  import { z } from "zod";
5
5
 
6
6
  //#region ../../packages/substrate-embedder/src/types.ts
package/dist/recall.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as InMemoryLexicalStore, i as PgClusterStore, n as PgLexicalStore, o as InMemoryEmbeddingsStore, r as PgEmbeddingsStore, s as InMemoryClusterStore, t as RECALL_VERSION } from "./src-D-UHaQiB.js";
2
- import { $ as CLUSTERER_BACKEND_VERSION, A as CLUSTER_MEMBER_FIELDS, C as EmbedSourceRegistry, D as makeReembed, E as makeEmbedPostWrite, F as unknownParams, G as DEFAULT_CRYSTALLISE_CONFIG, H as CRYSTALLISE_IN_FLIGHT_CODE, I as handleRecallRequest, J as runClusterer, K as handleCrystallise, L as RRF_K, M as recallRouteHandler, N as checkParams, O as crystalliseRouteHandler, P as unknownParamMessage, Q as CLUSTERER_BACKEND, R as armRanks, S as createEmbedStats, T as embedRowReporting, U as createCrystalliseGuard, X as l2normalize, _ as EMBEDDINGS_FETCH_MAX_REFS, a as REINDEX_MAX_LIMIT, b as handleLexicalCoverage, c as SALIENCE_BOOST_MAX_TARGETS, d as embeddingsMigration, et as memberKey, f as recallMcpTool, g as embeddingsFetchRouteHandler, h as embeddingSimilarOperator, i as REINDEX_DEFAULT_LIMIT, j as buildClusterSurface, k as CLUSTER_FIELDS, l as lexicalMigration, m as makeLexicalPostWrite, n as salienceBoostRouteHandler, nt as validateSelector, o as handleReindex, p as makeLexicalClassify, q as validateCrystalliseInput, r as reindexRouteHandler, s as validateReindexInput, t as createRecallPlugin, tt as SELECT_CANDIDATES_MAX_LIMIT, u as recallClustersMigration, v as embedStatsRouteHandler, w as embedAndStore, x as validateLexicalCoverageInput, y as handleEmbedStatsRequest, z as fuseByRank } from "./plugin-DkYf0ng8.js";
1
+ import { a as InMemoryLexicalStore, i as PgClusterStore, n as PgLexicalStore, o as InMemoryEmbeddingsStore, r as PgEmbeddingsStore, s as InMemoryClusterStore, t as RECALL_VERSION } from "./src-Dk_JtkUH.js";
2
+ import { $ as CLUSTERER_BACKEND_VERSION, A as CLUSTER_MEMBER_FIELDS, C as EmbedSourceRegistry, D as makeReembed, E as makeEmbedPostWrite, F as unknownParams, G as DEFAULT_CRYSTALLISE_CONFIG, H as CRYSTALLISE_IN_FLIGHT_CODE, I as handleRecallRequest, J as runClusterer, K as handleCrystallise, L as RRF_K, M as recallRouteHandler, N as checkParams, O as crystalliseRouteHandler, P as unknownParamMessage, Q as CLUSTERER_BACKEND, R as armRanks, S as createEmbedStats, T as embedRowReporting, U as createCrystalliseGuard, X as l2normalize, _ as EMBEDDINGS_FETCH_MAX_REFS, a as REINDEX_MAX_LIMIT, b as handleLexicalCoverage, c as SALIENCE_BOOST_MAX_TARGETS, d as embeddingsMigration, et as memberKey, f as recallMcpTool, g as embeddingsFetchRouteHandler, h as embeddingSimilarOperator, i as REINDEX_DEFAULT_LIMIT, j as buildClusterSurface, k as CLUSTER_FIELDS, l as lexicalMigration, m as makeLexicalPostWrite, n as salienceBoostRouteHandler, nt as validateSelector, o as handleReindex, p as makeLexicalClassify, q as validateCrystalliseInput, r as reindexRouteHandler, s as validateReindexInput, t as createRecallPlugin, tt as SELECT_CANDIDATES_MAX_LIMIT, u as recallClustersMigration, v as embedStatsRouteHandler, w as embedAndStore, x as validateLexicalCoverageInput, y as handleEmbedStatsRequest, z as fuseByRank } from "./plugin-DLBoldt-.js";
3
3
 
4
4
  export { CLUSTERER_BACKEND, CLUSTERER_BACKEND_VERSION, CLUSTER_FIELDS, CLUSTER_MEMBER_FIELDS, CRYSTALLISE_IN_FLIGHT_CODE, DEFAULT_CRYSTALLISE_CONFIG, EMBEDDINGS_FETCH_MAX_REFS, EmbedSourceRegistry, InMemoryClusterStore, InMemoryEmbeddingsStore, InMemoryLexicalStore, PgClusterStore, PgEmbeddingsStore, PgLexicalStore, RECALL_VERSION, REINDEX_DEFAULT_LIMIT, REINDEX_MAX_LIMIT, RRF_K, SALIENCE_BOOST_MAX_TARGETS, SELECT_CANDIDATES_MAX_LIMIT, armRanks, buildClusterSurface, checkParams, createCrystalliseGuard, createEmbedStats, createRecallPlugin, crystalliseRouteHandler, embedAndStore, embedRowReporting, embedStatsRouteHandler, embeddingSimilarOperator, embeddingsFetchRouteHandler, embeddingsMigration, fuseByRank, handleCrystallise, handleEmbedStatsRequest, handleLexicalCoverage, handleRecallRequest, handleReindex, l2normalize, lexicalMigration, makeEmbedPostWrite, makeLexicalClassify, makeLexicalPostWrite, makeReembed, memberKey, recallClustersMigration, recallMcpTool, recallRouteHandler, reindexRouteHandler, runClusterer, salienceBoostRouteHandler, unknownParamMessage, unknownParams, validateCrystalliseInput, validateLexicalCoverageInput, validateReindexInput, validateSelector };
@@ -1,4 +1,4 @@
1
- import { a as parsePositive, i as DEFAULT_SIZING, n as defaultPluginsForPersona, r as parsePort, t as KNOWN_PLUGINS } from "./cli-jlDJeDZi.js";
1
+ import { a as parsePositive, i as DEFAULT_SIZING, n as defaultPluginsForPersona, r as parsePort, t as KNOWN_PLUGINS } from "./cli-BlroGVRL.js";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import { stripVTControlCharacters, styleText } from "node:util";
@@ -1,10 +1,10 @@
1
- import { _ as AUDIT_EVENT_TYPE, g as buildAuditRow } from "./src-WYba7eEl.js";
1
+ import { _ as AUDIT_EVENT_TYPE, g as buildAuditRow } from "./src-DR8cwQtS.js";
2
2
  import { n as trimTrailingSlashes } from "./env-utils-s25Z1YSA.js";
3
3
  import { I as decodeList, L as encodeList, M as grantEntryError, g as checkUpdatable, h as checkRevocable, y as newlyGranted } from "./src-DmiUWOLp.js";
4
4
  import "./src-B_kHkbsr.js";
5
- import { A as REVOKE_EXIT_CODES, B as listActiveAdminKeys, C as runRegisterViaRoute, D as formatBootstrapOutput, E as formatDoctorReport, F as BootstrapError, G as ARGV_SPEC, H as describeAdminTarget, I as CLI_ACTOR_KID, J as USAGE, K as validateArgv, L as base64Url, M as runKeyListViaRoute, N as runKeyPatchViaRoute, O as parseBootstrapArgs, P as ACTOR_HINT, R as forUpdate, S as runRegister, T as doctorCommand, U as resolveAdminAuth, V as readKeyById, W as resolveAdminTarget, X as AdminCliError, Y as argvError, Z as pgNoticeOptions, _ as version, b as formatRegisterOutput, c as parseEnv, f as registeredTypes, g as loadPluginsFromDir, i as EnvConfigError, j as UPDATE_EXIT_CODES, k as runBootstrap, l as refuseContractViolation, n as resolvePluginDir, q as RESTART_NOTE, r as BINARY_CONTRACT_VERSION, t as bootStore, u as buildDeferredIndexes, v as openPgDataset, w as grantLines, x as parseRegisterArgs, y as onboardCommand, z as generateAdminKeypair } from "./boot-store-u_1PJSvo.js";
6
- import { T as substrateFetch } from "./src-FXO5JPyk.js";
7
- import { C as detectLayout, E as parseSourceBody, S as UUID_REGEX, T as copyRows, _ as isDerivedMigration, a as seqName, c as loadTypeTable, d as MIGRATE_STORE_MARKER_TABLE, f as PLAIN_SCHEMA_NAME, l as typeTableRef, m as assertStoreSchema, o as ensureTypeTable, x as UUID_CHECK_MIGRATION } from "./src-DQMA57_1.js";
5
+ import { A as REVOKE_EXIT_CODES, B as listActiveAdminKeys, C as runRegisterViaRoute, D as formatBootstrapOutput, E as formatDoctorReport, F as BootstrapError, G as ARGV_SPEC, H as describeAdminTarget, I as CLI_ACTOR_KID, J as USAGE, K as validateArgv, L as base64Url, M as runKeyListViaRoute, N as runKeyPatchViaRoute, O as parseBootstrapArgs, P as ACTOR_HINT, R as forUpdate, S as runRegister, T as doctorCommand, U as resolveAdminAuth, V as readKeyById, W as resolveAdminTarget, X as AdminCliError, Y as argvError, Z as pgNoticeOptions, _ as version, b as formatRegisterOutput, c as parseEnv, f as registeredTypes, g as loadPluginsFromDir, i as EnvConfigError, j as UPDATE_EXIT_CODES, k as runBootstrap, l as refuseContractViolation, n as resolvePluginDir, q as RESTART_NOTE, r as BINARY_CONTRACT_VERSION, t as bootStore, u as buildDeferredIndexes, v as openPgDataset, w as grantLines, x as parseRegisterArgs, y as onboardCommand, z as generateAdminKeypair } from "./boot-store-8T3XN40r.js";
6
+ import { T as substrateFetch } from "./src-Bvl6kSZl.js";
7
+ import { C as detectLayout, E as parseSourceBody, S as UUID_REGEX, T as copyRows, _ as isDerivedMigration, a as seqName, c as loadTypeTable, d as MIGRATE_STORE_MARKER_TABLE, f as PLAIN_SCHEMA_NAME, l as typeTableRef, m as assertStoreSchema, o as ensureTypeTable, x as UUID_CHECK_MIGRATION } from "./src-CTufEe7y.js";
8
8
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
9
9
  import { dirname } from "node:path";
10
10
  import { createHash, randomUUID } from "node:crypto";
@@ -1,4 +1,16 @@
1
1
  //#region ../../packages/substrate-client/src/script.ts
2
+ /**
3
+ * The frame for `query`/`mutate`, called either way: `(frame)` or `(key, entry)`.
4
+ * Anything else throws naming both forms, rather than reaching the server as a non-frame body.
5
+ */
6
+ function frameOf(op, frameOrKey, entry) {
7
+ if (typeof frameOrKey === "string") {
8
+ if (entry !== void 0 && (entry === null || typeof entry !== "object")) throw new Error(`s.${op}('${frameOrKey}', entry): entry must be { params?, fields? }, got ${entry === null ? "null" : typeof entry}`);
9
+ return { [frameOrKey]: entry ?? {} };
10
+ }
11
+ if (frameOrKey === null || typeof frameOrKey !== "object" || Array.isArray(frameOrKey)) throw new Error(`s.${op} takes a frame { 'ns/Type': { params, fields } } or (key, { params, fields }), got ${frameOrKey === null ? "null" : Array.isArray(frameOrKey) ? "an array" : typeof frameOrKey}`);
12
+ return frameOrKey;
13
+ }
2
14
  const DEFAULT_MAX_WRITES = 50;
3
15
  const DEFAULT_MAX_PAGES = 200;
4
16
  /** Counts the frames in a mutate payload: an array under an op-key is one frame per element. */
@@ -27,7 +39,8 @@ async function runScript(script, opts) {
27
39
  ms: 0
28
40
  };
29
41
  const started = Date.now();
30
- const query = async (frame) => {
42
+ const query = async (frameOrKey, entry) => {
43
+ const frame = frameOf("query", frameOrKey, entry);
31
44
  stats.queries++;
32
45
  const env = await client.query(frame);
33
46
  assertKeys(frame, env, "query");
@@ -109,7 +122,8 @@ async function runScript(script, opts) {
109
122
  if (t === void 0) throw new Error(`schema: unknown type '${namespace}/${type}'`);
110
123
  return t;
111
124
  },
112
- async mutate(frame) {
125
+ mutate: (async (frameOrKey, entry) => {
126
+ const frame = frameOf("mutate", frameOrKey, entry);
113
127
  if (mode === "read") throw new Error("mutate refused: read mode (run in dry-run or write mode)");
114
128
  if (mode === "dry-run") {
115
129
  mutations.push({
@@ -130,7 +144,7 @@ async function runScript(script, opts) {
130
144
  });
131
145
  assertKeys(frame, env, "mutate");
132
146
  return env;
133
- },
147
+ }),
134
148
  log: (...args) => log(args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" "))
135
149
  };
136
150
  const report = (extra) => {
@@ -46,12 +46,12 @@ async function start(m) {
46
46
  kid: m.kid,
47
47
  mode: m.mode,
48
48
  args: Object.freeze({ ...m.args }),
49
- query: (frame) => call("query", frame),
49
+ query: (frame, entry) => call("query", frame, entry),
50
50
  queryAll: (key, frame) => call("queryAll", key, frame),
51
51
  byShortId: (key, n, fields) => call("byShortId", key, n, fields),
52
52
  recall: (input) => call("recall", input),
53
53
  schema: (namespace, type) => call("schema", namespace, type),
54
- mutate: (frame) => call("mutate", frame),
54
+ mutate: (frame, entry) => call("mutate", frame, entry),
55
55
  log: (...args) => {
56
56
  call("log", ...args);
57
57
  }
package/dist/sdk.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $t as isColumnField, A as isReservedAutoCrudField, An as WALKS_IN_SUBSCRIPTION, B as createResolver, Bn as isRestrictViolation, Bt as jsonResponse, C as makeCtx, Cn as ReservedField, D as RESERVED_AUTOCRUD_FIELDS, Dn as UnsupportedFilterError, E as selectAll, En as STORE_BUSY, F as createResolverWithEdges, Fn as filterTooBroad, G as listResolver, Gn as canonicalize, Gt as WS_REASON_SERVER_RESTART, H as updateResolver, Hn as CLIENT_SUPPLIED_SERVER_FIELD, I as installAutoCrud, In as idHint, J as resolveIdentity, Jt as normaliseVocabValues, K as getResolver, Kn as BootstrapConfigError, Kt as WS_REASON_SUBSCRIPTION_OVERLOADED, L as deleteManyResolver, Ln as isAuthCause, Lt as JSON_HEADERS, M as field, Mn as WALKS_UNSUPPORTED_STORE, N as AutoCrudNameCollisionError, Nn as WALK_BUDGET_EXCEEDED, O as RESERVED_AUTOCRUD_FIELD_NAMES, On as VALUE_OUT_OF_RANGE, P as autoCrudOptionsOf, Pn as WALK_UNSUPPORTED_REF, Qt as DEFAULT_ORDERED_BY, R as updateManyResolver, Rn as isBatchElementError, S as EngineQueryError, Sn as ROW_POLICY_BLOCKS_WALK, T as queryOne, Tn as RestrictViolation, U as applyUpdatePatch, Un as ROW_METADATA_FIELDS, V as deleteResolver, Vn as DEFAULT_FILTER_WRITE_LIMITS, Vt as parseJsonBody, W as deleteRow, Wn as assertNoRepeatedIds, Wt as WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, X as resolveEntityRow, Xt as storedVocabSpellings, Y as resolveEntityId, Yt as normaliseVocabWhere, Zt as vocabImplication, _n as FILTER_TOO_BROAD, an as normaliseMetadataWhere, b as assertOrderedBy, bn as QUERY_TIMEOUT, cn as ISO_INSTANT_FORM, dn as isIsoTimestamp, en as naturalOrderOf, fn as normalizeIsoTimestamp, gn as BridgeUnreachableError, hn as BatchElementError, in as normaliseMetadataOrderBy, j as reservedMetadataFieldMessage, jn as WALKS_NEED_PARTITIONED, k as RESERVED_METADATA_FIELD_NAMES, kn as WALKS_IN_MUTATION, ln as isImpossibleIsoTimestamp, mn as validateHardDeleteEnv, nn as METADATA_AUTHOR_FIELDS, on as normaliseWalkNode, pn as assertHardDeleteAllowed, q as UnattributedWriteError, qn as defineBootstrap, qt as canonicalVocabValue, rn as METADATA_FILTER_FIELDS, sn as createKeyedMutex, tn as RegistryBase, un as isIsoInstant, vn as MissingReferentError, w as queryAll, wn as ResolverFrameError, x as defineNamespace, xn as REGEX_BUDGET_EXCEEDED, y as assertIndexDecl, yn as NamespaceMismatch, z as purgeResolver, zn as isResolverFrameError, zt as error400 } from "./src-WYba7eEl.js";
1
+ import { $t as isColumnField, A as isReservedAutoCrudField, An as WALKS_IN_SUBSCRIPTION, B as createResolver, Bn as isRestrictViolation, Bt as jsonResponse, C as makeCtx, Cn as ReservedField, D as RESERVED_AUTOCRUD_FIELDS, Dn as UnsupportedFilterError, E as selectAll, En as STORE_BUSY, F as createResolverWithEdges, Fn as filterTooBroad, G as listResolver, Gn as canonicalize, Gt as WS_REASON_SERVER_RESTART, H as updateResolver, Hn as CLIENT_SUPPLIED_SERVER_FIELD, I as installAutoCrud, In as idHint, J as resolveIdentity, Jt as normaliseVocabValues, K as getResolver, Kn as BootstrapConfigError, Kt as WS_REASON_SUBSCRIPTION_OVERLOADED, L as deleteManyResolver, Ln as isAuthCause, Lt as JSON_HEADERS, M as field, Mn as WALKS_UNSUPPORTED_STORE, N as AutoCrudNameCollisionError, Nn as WALK_BUDGET_EXCEEDED, O as RESERVED_AUTOCRUD_FIELD_NAMES, On as VALUE_OUT_OF_RANGE, P as autoCrudOptionsOf, Pn as WALK_UNSUPPORTED_REF, Qt as DEFAULT_ORDERED_BY, R as updateManyResolver, Rn as isBatchElementError, S as EngineQueryError, Sn as ROW_POLICY_BLOCKS_WALK, T as queryOne, Tn as RestrictViolation, U as applyUpdatePatch, Un as ROW_METADATA_FIELDS, V as deleteResolver, Vn as DEFAULT_FILTER_WRITE_LIMITS, Vt as parseJsonBody, W as deleteRow, Wn as assertNoRepeatedIds, Wt as WS_CODE_SUBSCRIPTION_UNSUPPORTED_FRAME, X as resolveEntityRow, Xt as storedVocabSpellings, Y as resolveEntityId, Yt as normaliseVocabWhere, Zt as vocabImplication, _n as FILTER_TOO_BROAD, an as normaliseMetadataWhere, b as assertOrderedBy, bn as QUERY_TIMEOUT, cn as ISO_INSTANT_FORM, dn as isIsoTimestamp, en as naturalOrderOf, fn as normalizeIsoTimestamp, gn as BridgeUnreachableError, hn as BatchElementError, in as normaliseMetadataOrderBy, j as reservedMetadataFieldMessage, jn as WALKS_NEED_PARTITIONED, k as RESERVED_METADATA_FIELD_NAMES, kn as WALKS_IN_MUTATION, ln as isImpossibleIsoTimestamp, mn as validateHardDeleteEnv, nn as METADATA_AUTHOR_FIELDS, on as normaliseWalkNode, pn as assertHardDeleteAllowed, q as UnattributedWriteError, qn as defineBootstrap, qt as canonicalVocabValue, rn as METADATA_FILTER_FIELDS, sn as createKeyedMutex, tn as RegistryBase, un as isIsoInstant, vn as MissingReferentError, w as queryAll, wn as ResolverFrameError, x as defineNamespace, xn as REGEX_BUDGET_EXCEEDED, y as assertIndexDecl, yn as NamespaceMismatch, z as purgeResolver, zn as isResolverFrameError, zt as error400 } from "./src-DR8cwQtS.js";
2
2
  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-s25Z1YSA.js";
3
3
  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-DmiUWOLp.js";
4
4
  import { B as EXPR_AGGREGATES, F as isInt32, H as EXPR_LIMITS, I as parseInt64, L as stringifyJson, M as formatQualifiedKey, N as parseQualifiedKey, P as isInt16, R as stringifyJsonExact, U as assertNever, V as EXPR_FUNCTIONS, z as DATE_UNITS } from "./src-B_kHkbsr.js";
@@ -1936,7 +1936,9 @@ var HttpTransport = class {
1936
1936
  };
1937
1937
  throw new AuthError(`${res.status === 401 ? "Unauthorised" : "Forbidden"}: ${url}`, res.status, info);
1938
1938
  }
1939
- throw new NetworkError(`${res.status} from ${url}`, null, await errorInfo(res));
1939
+ const info = await errorInfo(res);
1940
+ const reason = [info.code, info.serverMessage].filter((s) => s !== void 0).join(": ");
1941
+ throw new NetworkError(`${res.status} from ${url}${reason ? `: ${reason}` : ""}`, null, info);
1940
1942
  }
1941
1943
  };
1942
1944
  /** The status plus whatever a JSON body says: the whole object as `body`, the first string of `error.message` (the recall plugin's nested shape), `error`, `message` as the message, and the first string of `error.code`, `code` as the code. Non-JSON bodies leave the status alone. */
@@ -1,4 +1,4 @@
1
- import { $t as isColumnField, At as decodeCursor, Cn as ReservedField, Ct as metadataExprType, Dn as UnsupportedFilterError, Dt as LIKE_TRAILING_ESCAPE, En as STORE_BUSY, Et as isJsonPathPredicate, Fn as filterTooBroad, Ft as fieldRequested, Mt as normalizeOrderBy, Nt as fullBuiltinOperators, On as VALUE_OUT_OF_RANGE, Ot as endsWithEscape, Pn as WALK_UNSUPPORTED_REF, Pt as applyExtensionResultMeta, St as exprTypeOfField, Tt as assertJsonPathPredicate, Wn as assertNoRepeatedIds, _t as refNames, at as forEachWalkHop, bn as QUERY_TIMEOUT, ct as windowGroupBy, dt as aggType, en as naturalOrderOf, fn as normalizeIsoTimestamp, ft as canRaise, gt as isRefOperand, ht as groupConjuncts, jt as encodeCursor, kt as CursorDecodeError, lt as preResolveExtensionOperatorsDetailed, mt as bindingWalks, ot as whereUsesWalks, pt as isDateField, rn as METADATA_FILTER_FIELDS, sn as createKeyedMutex, st as sharedPicks, ut as aggParts, wn as ResolverFrameError, wt as walkAggExprType, yn as NamespaceMismatch } from "./src-WYba7eEl.js";
1
+ import { $t as isColumnField, At as decodeCursor, Cn as ReservedField, Ct as metadataExprType, Dn as UnsupportedFilterError, Dt as LIKE_TRAILING_ESCAPE, En as STORE_BUSY, Et as isJsonPathPredicate, Fn as filterTooBroad, Ft as fieldRequested, Mt as normalizeOrderBy, Nt as fullBuiltinOperators, On as VALUE_OUT_OF_RANGE, Ot as endsWithEscape, Pn as WALK_UNSUPPORTED_REF, Pt as applyExtensionResultMeta, St as exprTypeOfField, Tt as assertJsonPathPredicate, Wn as assertNoRepeatedIds, _t as refNames, at as forEachWalkHop, bn as QUERY_TIMEOUT, ct as windowGroupBy, dt as aggType, en as naturalOrderOf, fn as normalizeIsoTimestamp, ft as canRaise, gt as isRefOperand, ht as groupConjuncts, jt as encodeCursor, kt as CursorDecodeError, lt as preResolveExtensionOperatorsDetailed, mt as bindingWalks, ot as whereUsesWalks, pt as isDateField, rn as METADATA_FILTER_FIELDS, sn as createKeyedMutex, st as sharedPicks, ut as aggParts, wn as ResolverFrameError, wt as walkAggExprType, yn as NamespaceMismatch } from "./src-DR8cwQtS.js";
2
2
  import { F as isInt32, I as parseInt64, L as stringifyJson, P as isInt16, R as stringifyJsonExact, z as DATE_UNITS } from "./src-B_kHkbsr.js";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
 
@@ -1,4 +1,4 @@
1
- import { $ as publishSchema, D as RESERVED_AUTOCRUD_FIELDS, Gn as canonicalize$1, I as installAutoCrud, J as resolveIdentity, Lt as JSON_HEADERS, M as field, O as RESERVED_AUTOCRUD_FIELD_NAMES, P as autoCrudOptionsOf, b as assertOrderedBy, d as uuidFromName, f as emitFieldEvents, j as reservedMetadataFieldMessage, l as planServesShape, p as migrateFieldValues, wn as ResolverFrameError, x as defineNamespace, y as assertIndexDecl } from "./src-WYba7eEl.js";
1
+ import { $ as publishSchema, D as RESERVED_AUTOCRUD_FIELDS, Gn as canonicalize$1, I as installAutoCrud, J as resolveIdentity, Lt as JSON_HEADERS, M as field, O as RESERVED_AUTOCRUD_FIELD_NAMES, P as autoCrudOptionsOf, b as assertOrderedBy, d as uuidFromName, f as emitFieldEvents, j as reservedMetadataFieldMessage, l as planServesShape, p as migrateFieldValues, wn as ResolverFrameError, x as defineNamespace, y as assertIndexDecl } from "./src-DR8cwQtS.js";
2
2
  import { s as requireCapability } from "./src-DmiUWOLp.js";
3
3
  import "./src-B_kHkbsr.js";
4
4
  import { randomUUID } from "node:crypto";
@@ -1530,15 +1530,19 @@ function withRequestContext(handler, trustedProxies, authEnabled) {
1530
1530
  * validation. Anything that doesn't look like an object of objects (or arrays
1531
1531
  * of objects, for batched mutate §5.13) is rejected.
1532
1532
  */
1533
- function validateFrame(value) {
1534
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1535
- for (const entry of Object.values(value)) {
1536
- if (entry === null || typeof entry !== "object") return false;
1533
+ const FRAME_SHAPE = "a frame is { \"<ns>/<Type>\": { \"params\": {...}, \"fields\": {...} } }";
1534
+ const kindOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
1535
+ /** Why a request body is not a frame, naming the offending key; null when it is one. Entry keys are checked by the engine. */
1536
+ function frameShapeError(value) {
1537
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return `the body is ${kindOf(value)}, not a frame: ${FRAME_SHAPE}`;
1538
+ for (const [key, entry] of Object.entries(value)) {
1539
+ if (entry === null || typeof entry !== "object") return `'${key}' is ${kindOf(entry)}; each key maps to { params?, fields?, idempotencyKey? }: ${FRAME_SHAPE}`;
1537
1540
  if (Array.isArray(entry)) {
1538
- for (const sub of entry) if (sub === null || typeof sub !== "object" || Array.isArray(sub)) return false;
1541
+ const i = entry.findIndex((sub) => sub === null || typeof sub !== "object" || Array.isArray(sub));
1542
+ if (i >= 0) return `'${key}'[${i}] is ${kindOf(entry[i])}; each element of a batch is { params?, fields?, idempotencyKey? }`;
1539
1543
  }
1540
1544
  }
1541
- return true;
1545
+ return null;
1542
1546
  }
1543
1547
  function readAcceptHeader(req) {
1544
1548
  return req.headers.accept ?? req.headers.Accept;
@@ -2319,6 +2323,7 @@ var RegexRefusal = class extends Error {};
2319
2323
  * expression limits (`EXPR_LIMITS`). `int64` mixed with `number` widens to
2320
2324
  * `number`; a safe-integer literal beside an int64 stays int64.
2321
2325
  */
2326
+ const EXPR_FORMS = "an expression is a field name (\"title\"), a number, or an object with exactly one function key such as { \"lower\": [\"title\"] } or { \"lit\": \"text\" }";
2322
2327
  const SIGS = new Map(EXPR_FUNCTIONS.map((s) => [s.name, s]));
2323
2328
  const isNumeric = (t) => t === "number" || t === "int64";
2324
2329
  var Refusal = class extends Error {
@@ -2394,9 +2399,12 @@ function checkExpr(expr, scope, path) {
2394
2399
  depth
2395
2400
  };
2396
2401
  }
2397
- if (typeof e !== "object" || Array.isArray(e)) return refuse("not an expression", at);
2402
+ if (typeof e !== "object" || Array.isArray(e)) {
2403
+ const only = Array.isArray(e) && e.length === 1 && typeof e[0] === "string" ? `; for the field, write "${e[0]}"` : "";
2404
+ return refuse(`${EXPR_FORMS}; got ${Array.isArray(e) ? "an array" : typeof e}${only}`, at);
2405
+ }
2398
2406
  const keys = Object.keys(e);
2399
- if (keys.length !== 1) return refuse(`an expression object has exactly one key, got ${keys.length}`, at);
2407
+ if (keys.length !== 1) return refuse(`${EXPR_FORMS}; got an object with ${keys.length === 0 ? "no keys" : `keys ${keys.join(", ")}`}`, at);
2400
2408
  const key = keys[0];
2401
2409
  const val = e[key];
2402
2410
  if (key === "lit") return typeof val === "string" ? {
@@ -6322,7 +6330,7 @@ function validateFrameParams(p, scope, h) {
6322
6330
  "groupBy",
6323
6331
  "having",
6324
6332
  "offset"
6325
- ]) if (p[k] !== void 0 && !grouped) fail("agg_invalid", `${k} shapes an aggregate's groups; it needs aggregate`, [k]);
6333
+ ]) if (p[k] !== void 0 && !grouped) fail("agg_invalid", `${k} shapes an aggregate's groups; it needs aggregate.${k === "offset" ? " To page rows, pass the previous page's _pagination nextCursor as params.cursor; for a total, use count: true." : ""}`, [k]);
6326
6334
  if (p.aggregate !== void 0) {
6327
6335
  const refused = p.groupBy !== void 0 ? ["select", "cursor"] : [
6328
6336
  "select",
@@ -11291,13 +11299,20 @@ function coerceId(raw) {
11291
11299
  * their `params` IS the row body, so "unknown" keys are extra body fields,
11292
11300
  * which is a separate concern from top-level param-shape validation.
11293
11301
  */
11294
- function rejectUnknownParams(resolverName, typeName, params, allowed) {
11302
+ function rejectUnknownParams(resolverName, typeName, params, allowed, fields) {
11295
11303
  if (!params) return;
11296
- for (const key of Object.keys(params)) if (!allowed.has(key)) throw new ResolverFrameError("unknown_param", `${resolverName}('${typeName}'): unknown param '${key}'. Allowed: ${[...allowed].sort().join(", ")}.`, {
11304
+ for (const key of Object.keys(params)) if (!allowed.has(key)) throw new ResolverFrameError("unknown_param", `${resolverName}('${typeName}'): unknown param '${key}'. Allowed: ${[...allowed].sort().join(", ")}.${unknownParamHint(key, allowed, fields)}`, {
11297
11305
  field: key,
11298
11306
  allowed: [...allowed].sort()
11299
11307
  });
11300
11308
  }
11309
+ /** The likely fix for an unknown param, when one is obvious: a field name sent as a param, or a paging token under the wrong name. */
11310
+ function unknownParamHint(key, allowed, fields) {
11311
+ if (key === "fields" || key === "idempotencyKey") return ` '${key}' sits beside params, not inside it: { params: { ... }, ${key}: ... }.`;
11312
+ if (allowed.has("where") && fields !== void 0 && Object.hasOwn(fields, key)) return ` '${key}' is a field: filters go in where, e.g. params: { where: { ${key}: { eq: ... } } }.`;
11313
+ if (allowed.has("cursor") && /cursor|page|after|token/i.test(key)) return " To page, pass the previous page's _pagination nextCursor as params.cursor.";
11314
+ return "";
11315
+ }
11301
11316
  /**
11302
11317
  * Refuse a caller-supplied value for a `readonly` field, on create and update
11303
11318
  * alike. shortId is the main case: the engine allocates it.
@@ -11623,7 +11638,7 @@ function extractLimit(params) {
11623
11638
  }
11624
11639
  function listResolver(typeName, dataset, options = {}) {
11625
11640
  return async (_ctx, args) => {
11626
- rejectUnknownParams("list", typeName, args.params, KNOWN_LIST_PARAMS);
11641
+ rejectUnknownParams("list", typeName, args.params, KNOWN_LIST_PARAMS, options.fields);
11627
11642
  const ds = args.dataset ?? dataset;
11628
11643
  const limit = extractLimit(args.params);
11629
11644
  const readParams = {};
@@ -17831,7 +17846,8 @@ function mutateRoute(engine, trustedProxies, authEnabled) {
17831
17846
  return async (req) => {
17832
17847
  const parsed = parseJsonBody(req);
17833
17848
  if (!parsed.ok) return parsed.response;
17834
- if (!validateFrame(parsed.value)) return error400("frame must be an object of { params?, fields? } entries");
17849
+ const shapeError = frameShapeError(parsed.value);
17850
+ if (shapeError !== null) return error400(shapeError);
17835
17851
  const frame = parsed.value;
17836
17852
  const envelope = await engine.mutate({
17837
17853
  frame,
@@ -18101,7 +18117,8 @@ function queryRoute(engine, trustedProxies, authEnabled, pageLimits) {
18101
18117
  return async (req) => {
18102
18118
  const parsed = parseJsonBody(req);
18103
18119
  if (!parsed.ok) return parsed.response;
18104
- if (!validateFrame(parsed.value)) return error400("frame must be an object of { params?, fields? } entries");
18120
+ const shapeError = frameShapeError(parsed.value);
18121
+ if (shapeError !== null) return error400(shapeError);
18105
18122
  const frame = parsed.value;
18106
18123
  const envelope = await engine.query({
18107
18124
  frame,
@@ -1,8 +1,8 @@
1
- import { i as txScopeIdFor, l as typeTableRef, s as guardedRefRead, u as whileNoTypeTable } from "./src-DQMA57_1.js";
2
- import { B as ROW_FILTER_FIELD, V as matchesRowFilter, W as inFlightError, Y as unresolvedRow, Z as cosineSimilarity, et as memberKey } from "./plugin-DkYf0ng8.js";
1
+ import { i as txScopeIdFor, l as typeTableRef, s as guardedRefRead, u as whileNoTypeTable } from "./src-CTufEe7y.js";
2
+ import { B as ROW_FILTER_FIELD, V as matchesRowFilter, W as inFlightError, Y as unresolvedRow, Z as cosineSimilarity, et as memberKey } from "./plugin-DLBoldt-.js";
3
3
 
4
4
  //#region ../../plugins/substrate-recall/package.json
5
- var version = "1.0.0-beta.3";
5
+ var version = "1.0.0-beta.5";
6
6
 
7
7
  //#endregion
8
8
  //#region ../../plugins/substrate-recall/src/in-memory-cluster-store.ts
@@ -36,7 +36,7 @@ function isEntrypointPath(moduleUrl, argv1) {
36
36
  */
37
37
  if (isEntrypointPath(import.meta.url, process.argv[1])) {
38
38
  assertNodeVersion();
39
- import("./run-DmOyE-QQ.js").then(({ runAdminCli }) => runAdminCli());
39
+ import("./run-BAXS_V3M.js").then(({ runAdminCli }) => runAdminCli());
40
40
  }
41
41
 
42
42
  //#endregion
package/dist/substrate.js CHANGED
@@ -3,7 +3,7 @@ import { t as assertNodeVersion } from "./node-version-BtK_Nq6z.js";
3
3
 
4
4
  //#region src/bin/substrate.ts
5
5
  assertNodeVersion();
6
- import("./cli-jlDJeDZi.js").then(({ runCli }) => runCli(process.argv.slice(2))).then((code) => process.exit(code));
6
+ import("./cli-BlroGVRL.js").then(({ runCli }) => runCli(process.argv.slice(2))).then((code) => process.exit(code));
7
7
 
8
8
  //#endregion
9
9
  export { };
package/dist/testing.js CHANGED
@@ -1,6 +1,6 @@
1
- import { Gt as WS_REASON_SERVER_RESTART, Q as loadPlugins, Ut as signHs256, Z as MemoryEdgesStore, c as MemoryDataset, s as compose } from "./src-WYba7eEl.js";
1
+ import { Gt as WS_REASON_SERVER_RESTART, Q as loadPlugins, Ut as signHs256, Z as MemoryEdgesStore, c as MemoryDataset, s as compose } from "./src-DR8cwQtS.js";
2
2
  import "./src-B_kHkbsr.js";
3
- import { b as runMigrations, g as deriveListIndexMigration, n as PgEdgesStore, r as PgDataset, y as runDerivedMigrations } from "./src-DQMA57_1.js";
3
+ import { b as runMigrations, g as deriveListIndexMigration, n as PgEdgesStore, r as PgDataset, y as runDerivedMigrations } from "./src-CTufEe7y.js";
4
4
  import { t as FakeEmbedder } from "./fake-DdXtb-m8.js";
5
5
  import postgres from "postgres";
6
6
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mnmal-ai/substrate",
3
- "version": "1.0.0-beta.3",
3
+ "version": "1.0.0-beta.5",
4
4
  "description": "Substrate — an agent-first typed-data server: the substrate and substrate-admin binaries, the built-in plugins and the SDK subpaths.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -35,24 +35,24 @@
35
35
  },
36
36
  "devDependencies": {
37
37
  "@inquirer/prompts": "^8.7.2",
38
- "@mnmal-ai/substrate-bootstrap": "1.0.0-beta.3",
39
- "@mnmal-ai/substrate-client": "1.0.0-beta.3",
40
- "@mnmal-ai/substrate-compose": "1.0.0-beta.3",
41
- "@mnmal-ai/substrate-config": "1.0.0-beta.3",
42
- "@mnmal-ai/substrate-core": "1.0.0-beta.3",
43
- "@mnmal-ai/substrate-dataset-memory": "1.0.0-beta.3",
44
- "@mnmal-ai/substrate-dataset-pg": "1.0.0-beta.3",
45
- "@mnmal-ai/substrate-embedder": "1.0.0-beta.3",
46
- "@mnmal-ai/substrate-filter": "1.0.0-beta.3",
47
- "@mnmal-ai/substrate-pack": "1.0.0-beta.3",
48
- "@mnmal-ai/substrate-policy": "1.0.0-beta.3",
49
- "@mnmal-ai/substrate-proposals": "1.0.0-beta.3",
50
- "@mnmal-ai/substrate-recall": "1.0.0-beta.3",
51
- "@mnmal-ai/substrate-sdk": "1.0.0-beta.3",
52
- "@mnmal-ai/substrate-sentinel-client": "1.0.0-beta.3",
53
- "@mnmal-ai/substrate-server-fastify": "1.0.0-beta.3",
54
- "@mnmal-ai/substrate-server-memory": "1.0.0-beta.3",
55
- "@mnmal-ai/substrate-types": "1.0.0-beta.3",
38
+ "@mnmal-ai/substrate-bootstrap": "1.0.0-beta.5",
39
+ "@mnmal-ai/substrate-client": "1.0.0-beta.5",
40
+ "@mnmal-ai/substrate-compose": "1.0.0-beta.5",
41
+ "@mnmal-ai/substrate-config": "1.0.0-beta.5",
42
+ "@mnmal-ai/substrate-core": "1.0.0-beta.5",
43
+ "@mnmal-ai/substrate-dataset-memory": "1.0.0-beta.5",
44
+ "@mnmal-ai/substrate-dataset-pg": "1.0.0-beta.5",
45
+ "@mnmal-ai/substrate-embedder": "1.0.0-beta.5",
46
+ "@mnmal-ai/substrate-filter": "1.0.0-beta.5",
47
+ "@mnmal-ai/substrate-pack": "1.0.0-beta.5",
48
+ "@mnmal-ai/substrate-policy": "1.0.0-beta.5",
49
+ "@mnmal-ai/substrate-proposals": "1.0.0-beta.5",
50
+ "@mnmal-ai/substrate-recall": "1.0.0-beta.5",
51
+ "@mnmal-ai/substrate-sdk": "1.0.0-beta.5",
52
+ "@mnmal-ai/substrate-sentinel-client": "1.0.0-beta.5",
53
+ "@mnmal-ai/substrate-server-fastify": "1.0.0-beta.5",
54
+ "@mnmal-ai/substrate-server-memory": "1.0.0-beta.5",
55
+ "@mnmal-ai/substrate-types": "1.0.0-beta.5",
56
56
  "@mnmal-ai/surface-core": "0.17.1",
57
57
  "@types/node": "^26.6.4",
58
58
  "@types/semver": "^7.5.0",