@valbuild/server 0.115.0 → 0.117.0

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,20 +1,21 @@
1
1
  import ts from 'typescript';
2
2
  import { pipe, result, array } from '@valbuild/core/fp';
3
3
  import { PatchError, deepEqual, parseAndValidateArrayIndex, isNotRoot, applyPatch, JSONOps, deepClone, sourceToPatchPath } from '@valbuild/core/patch';
4
- import { derefPatch, Internal, RecordSchema, extractValModules, computeValModuleShas, VAL_EXTENSION, ImageSchema, DEFAULT_CONTENT_HOST, hasRemoteFileSchema } from '@valbuild/core';
4
+ import { derefPatch, Internal, RecordSchema, extractValModules, computeValModuleShas, VAL_EXTENSION, ImageSchema, DEFAULT_CONTENT_HOST, hasRemoteFileSchema, getSourcePathFromRoute } from '@valbuild/core';
5
5
  export { hasRemoteFileSchema } from '@valbuild/core';
6
6
  import * as path from 'path';
7
7
  import path__default from 'path';
8
8
  import fs, { promises } from 'fs';
9
9
  import vm from 'node:vm';
10
10
  import { Module, createRequire } from 'node:module';
11
- import { resolveSchemaSourceFixForError, Patch, getErrorMessageFromUnknownJson, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, Api } from '@valbuild/shared/internal';
11
+ import { resolveSchemaSourceFixForError, Patch, getErrorMessageFromUnknownJson, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, Api, filterBlockingValidationErrors, describeContainerAtPath, safeParsePatch, buildDuplicatePatch, buildEmptyAtPathPatch, buildRemoveImageGalleryEntryPatch } from '@valbuild/shared/internal';
12
12
  import { createUIRequestHandler } from '@valbuild/ui/server';
13
13
  import crypto$1 from 'crypto';
14
14
  import z$1, { z } from 'zod';
15
15
  import sizeOf from 'image-size';
16
16
  import { fromError } from 'zod-validation-error';
17
17
  import os from 'os';
18
+ import { randomUUID, createHash } from 'node:crypto';
18
19
  import { transform } from 'sucrase';
19
20
  import http from 'http';
20
21
  import https from 'https';
@@ -1006,7 +1007,7 @@ function errorMessage(e) {
1006
1007
  return String(e);
1007
1008
  }
1008
1009
 
1009
- const jsonOps$2 = new JSONOps();
1010
+ const jsonOps$3 = new JSONOps();
1010
1011
 
1011
1012
  /**
1012
1013
  * Classification of a single patch op against a module's serialized schema,
@@ -1261,7 +1262,7 @@ function applyJsonValuesEntryPatches(args) {
1261
1262
  // on an entry that does not exist.
1262
1263
  continue;
1263
1264
  }
1264
- const applied = applyPatch(deepClone(content), jsonOps$2, [{
1265
+ const applied = applyPatch(deepClone(content), jsonOps$3, [{
1265
1266
  op: "add",
1266
1267
  path: cls.subPath.concat(...(op.nestedFilePath ?? [])).concat("patch_id"),
1267
1268
  value: patchId
@@ -1315,7 +1316,7 @@ function applyJsonValuesEntryPatches(args) {
1315
1316
  patchId
1316
1317
  };
1317
1318
  }
1318
- const applied = applyPatch(deepClone(content), jsonOps$2, [rebased.value]);
1319
+ const applied = applyPatch(deepClone(content), jsonOps$3, [rebased.value]);
1319
1320
  if (result.isErr(applied)) {
1320
1321
  return {
1321
1322
  kind: "error",
@@ -1598,7 +1599,7 @@ function findJsonEntryFilePath(moduleFilePath, valTsSourceFile, entryKey) {
1598
1599
  return resolveExistingJsonPath(moduleFilePath, entry.importPath);
1599
1600
  }
1600
1601
 
1601
- const jsonOps$1 = new JSONOps();
1602
+ const jsonOps$2 = new JSONOps();
1602
1603
 
1603
1604
  /**
1604
1605
  * Substitutes loaded `.jsonValues()` entry content back into a module's root
@@ -1889,7 +1890,7 @@ class Service {
1889
1890
  if (result.isErr(rebased)) {
1890
1891
  throw Error(`Could not apply ${op.op} to jsonValues entry '${entryKey}' of ${moduleFilePath}: ${rebased.error.message}`);
1891
1892
  }
1892
- const applied = applyPatch(deepClone(content), jsonOps$1, [rebased.value]);
1893
+ const applied = applyPatch(deepClone(content), jsonOps$2, [rebased.value]);
1893
1894
  if (result.isErr(applied)) {
1894
1895
  throw Error(`Could not apply ${op.op} to ${jsonPath}: ${applied.error.message}`);
1895
1896
  }
@@ -2058,7 +2059,7 @@ function encodeJwt(payload, sessionKey) {
2058
2059
  }
2059
2060
 
2060
2061
  /* eslint-disable @typescript-eslint/no-unused-vars */
2061
- const jsonOps = new JSONOps();
2062
+ const jsonOps$1 = new JSONOps();
2062
2063
  const tsOps = new TSOps(document => {
2063
2064
  return pipe(analyzeValModule(document), result.map(({
2064
2065
  source
@@ -2827,7 +2828,7 @@ class ValOps {
2827
2828
  }
2828
2829
  const patchRes = applyPatch(deepClone(patchedSources[path]),
2829
2830
  // applyPatch mutates the source. On add operations it adds more than once? There is something strange going on... deepClone seems to fix, but is that the right solution?
2830
- jsonOps, applicableOps.concat(...Object.values(fileFixOps)));
2831
+ jsonOps$1, applicableOps.concat(...Object.values(fileFixOps)));
2831
2832
  if (result.isErr(patchRes)) {
2832
2833
  console.error("Could not apply patch", JSON.stringify({
2833
2834
  path,
@@ -3527,7 +3528,7 @@ class ValOps {
3527
3528
  patchHadError = true;
3528
3529
  break;
3529
3530
  }
3530
- const applied = applyPatch(deepClone(contentRes.value), jsonOps, [rebasedRes.value]);
3531
+ const applied = applyPatch(deepClone(contentRes.value), jsonOps$1, [rebasedRes.value]);
3531
3532
  if (result.isErr(applied)) {
3532
3533
  collectPatchError(applied.error, patchId, op);
3533
3534
  patchHadError = true;
@@ -7433,6 +7434,227 @@ async function getSettings(projectName, auth) {
7433
7434
  }
7434
7435
  }
7435
7436
 
7437
+ /**
7438
+ * Resolving how Val is configured, and building the data layer from it.
7439
+ *
7440
+ * Both live here rather than inside `createValApiRouter` because the MCP tool
7441
+ * registry needs exactly the same answers: which mode we are in, which
7442
+ * credential to use, and which `ValOps` implementation that implies. Two copies
7443
+ * of this would drift, and the failure would be quiet — a registry that decides
7444
+ * it is in fs mode while the Studio decides it is in proxy mode reads different
7445
+ * content from the same project.
7446
+ *
7447
+ * The type-only import from `./ValRouter` is deliberate: it keeps `ValApiOptions`
7448
+ * where its documentation lives without creating a runtime cycle.
7449
+ *
7450
+ * The credential-bearing URL check at the bottom of this file lives here for the
7451
+ * same reason: it is a check on the URLs `initHandlerOptions` resolves, and its
7452
+ * only caller is that function. Leaving it in `./ValRouter` would have meant
7453
+ * importing it back from there, which is the runtime cycle the paragraph above
7454
+ * exists to avoid.
7455
+ */
7456
+
7457
+ const DEFAULT_VAL_BUILD_URL = "https://admin.val.build";
7458
+
7459
+ /**
7460
+ * Resolve options plus environment into a concrete {@link ValServerConfig}.
7461
+ *
7462
+ * Moved verbatim out of `createValApiRouter`; the precedence rules are load
7463
+ * bearing, so this is the one place they are written down. Note that "proxy"
7464
+ * mode is inferred when `VAL_API_KEY` or `VAL_SECRET` is present and no mode was
7465
+ * given, which is why a project can be pushed into proxy mode by setting an env
7466
+ * var alone.
7467
+ */
7468
+ async function initHandlerOptions(route, opts, config) {
7469
+ const maybeApiKey = opts.apiKey || process.env.VAL_API_KEY;
7470
+ const maybeValSecret = opts.valSecret || process.env.VAL_SECRET;
7471
+ const isProxyMode = opts.mode === "proxy" || opts.mode === undefined && (maybeApiKey || maybeValSecret);
7472
+ const valEnableRedirectUrl = opts.valEnableRedirectUrl || process.env.VAL_ENABLE_REDIRECT_URL;
7473
+ const valDisableRedirectUrl = opts.valDisableRedirectUrl || process.env.VAL_DISABLE_REDIRECT_URL;
7474
+ const maybeValProject = opts.project || process.env.VAL_PROJECT;
7475
+ const valBuildUrl = opts.valBuildUrl || process.env.VAL_BUILD_URL || DEFAULT_VAL_BUILD_URL;
7476
+ const valContentUrl = opts.valContentUrl || process.env.VAL_CONTENT_URL || DEFAULT_CONTENT_HOST;
7477
+ warnIfInsecureUrls({
7478
+ valBuildUrl,
7479
+ valContentUrl
7480
+ });
7481
+ if (isProxyMode) {
7482
+ var _opts$versions, _opts$versions2;
7483
+ if (!maybeApiKey || !maybeValSecret) {
7484
+ throw new Error("VAL_API_KEY and VAL_SECRET env vars must both be set in proxy mode");
7485
+ }
7486
+ const maybeGitCommit = opts.gitCommit || process.env.VAL_GIT_COMMIT;
7487
+ if (!maybeGitCommit) {
7488
+ throw new Error("VAL_GIT_COMMIT env var must be set in proxy mode");
7489
+ }
7490
+ const maybeGitBranch = opts.gitBranch || process.env.VAL_GIT_BRANCH;
7491
+ if (!maybeGitBranch) {
7492
+ throw new Error("VAL_GIT_BRANCH env var must be set in proxy mode");
7493
+ }
7494
+ if (!maybeValProject) {
7495
+ throw new Error("Proxy mode does not work unless the 'project' option in val.config is defined or the VAL_PROJECT env var is set.");
7496
+ }
7497
+ const coreVersion = (_opts$versions = opts.versions) === null || _opts$versions === void 0 ? void 0 : _opts$versions.core;
7498
+ if (!coreVersion) {
7499
+ throw new Error("Could not determine version of @valbuild/core");
7500
+ }
7501
+ const nextVersion = (_opts$versions2 = opts.versions) === null || _opts$versions2 === void 0 ? void 0 : _opts$versions2.next;
7502
+ if (!nextVersion) {
7503
+ throw new Error("Could not determine version of @valbuild/next");
7504
+ }
7505
+ return {
7506
+ mode: "http",
7507
+ route,
7508
+ apiKey: maybeApiKey,
7509
+ valSecret: maybeValSecret,
7510
+ commit: maybeGitCommit,
7511
+ branch: maybeGitBranch,
7512
+ root: opts.root,
7513
+ project: maybeValProject,
7514
+ valEnableRedirectUrl,
7515
+ valDisableRedirectUrl,
7516
+ valContentUrl,
7517
+ valBuildUrl,
7518
+ config
7519
+ };
7520
+ } else {
7521
+ const cwd = process.cwd();
7522
+ const valBuildUrl = opts.valBuildUrl || process.env.VAL_BUILD_URL || DEFAULT_VAL_BUILD_URL;
7523
+ return {
7524
+ mode: "fs",
7525
+ cwd,
7526
+ route,
7527
+ valDisableRedirectUrl,
7528
+ valEnableRedirectUrl,
7529
+ valBuildUrl,
7530
+ valContentUrl,
7531
+ apiKey: maybeApiKey,
7532
+ valSecret: maybeValSecret,
7533
+ project: maybeValProject,
7534
+ config
7535
+ };
7536
+ }
7537
+ }
7538
+
7539
+ /**
7540
+ * Build the data layer a {@link ValServerConfig} calls for.
7541
+ *
7542
+ * `auth` decides *whose* credential the http backend sees. Left out, it is the
7543
+ * app's own API key — which is what the Studio wants, because there the app has
7544
+ * already verified a session cookie and is acting on the user's behalf under its
7545
+ * own authority.
7546
+ *
7547
+ * A caller acting for a user it has *not* authenticated itself must pass that
7548
+ * user's personal access token instead, so the backend is the one that decides
7549
+ * what the caller may do. That is the whole of `docs/plans/mcp.md` D.2: the app
7550
+ * stops being an authority and goes back to being a pipe. Passing the app's API
7551
+ * key on such a request is the D.6 confused deputy, and it is worth being blunt
7552
+ * about why it is tempting — it works, and it works for every project the key
7553
+ * can reach, including the ones the caller cannot.
7554
+ */
7555
+ function createValOps(valModules, options, auth) {
7556
+ if (options.mode === "fs") {
7557
+ // No credential in fs mode: this reads and writes the developer's own
7558
+ // working tree, and there is no backend to authenticate to. A PAT handed in
7559
+ // here is not ignored quietly — the caller is told, in createValTools.
7560
+ return new ValOpsFS(options.valContentUrl, options.cwd, valModules, {
7561
+ formatter: options.formatter,
7562
+ config: options.config
7563
+ });
7564
+ }
7565
+ if (options.mode === "http") {
7566
+ return new ValOpsHttp(options.valContentUrl, options.project, options.commit, options.branch, auth ?? {
7567
+ apiKey: options.apiKey
7568
+ }, valModules, {
7569
+ formatter: options.formatter,
7570
+ root: options.root,
7571
+ config: options.config
7572
+ });
7573
+ }
7574
+ throw new Error(
7575
+ // The union is exhausted above; this catches a config that came from
7576
+ // somewhere untyped.
7577
+ "Invalid mode: " + (options === null || options === void 0 ? void 0 : options.mode));
7578
+ }
7579
+
7580
+ /**
7581
+ * Hosts we send credentials to, and what each one puts at risk. They differ:
7582
+ * only `valBuildUrl` hands back the app token that becomes the session cookie,
7583
+ * so a single shared sentence would overstate one and understate the other.
7584
+ */
7585
+
7586
+ const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl"];
7587
+ const WHAT_IS_AT_RISK = {
7588
+ valBuildUrl: "Val's api key is sent to this host, and the token it returns is what this server signs into the session cookie, " + "so both can be read - and the token replaced - by anyone on the network path.",
7589
+ valContentUrl: "Val's api key, or the caller's personal access token, is sent to this host, " + "so it can be read by anyone on the network path."
7590
+ };
7591
+
7592
+ // NOTE: `URL.hostname` keeps the brackets on an IPv6 literal, so this is
7593
+ // "[::1]" and not "::1" - and `http://[0:0:0:0:0:0:0:1]` normalises to the
7594
+ // same short form before it gets here. Dropping the brackets looks like a
7595
+ // tidy-up and silently stops matching IPv6 loopback.
7596
+ const LOOPBACK_HOSTNAMES = ["localhost", "127.0.0.1", "[::1]"];
7597
+
7598
+ /**
7599
+ * The URL as it is safe to print. `http://user:pass@host` is a legal override,
7600
+ * and a warning about credential exposure that puts the password in the log
7601
+ * would be the very thing it is warning about.
7602
+ */
7603
+ function forLog(parsed) {
7604
+ if (!parsed.username && !parsed.password) {
7605
+ return parsed.href;
7606
+ }
7607
+ const redacted = new URL(parsed.href);
7608
+ redacted.username = "";
7609
+ redacted.password = "";
7610
+ return `${redacted.href} (credentials redacted)`;
7611
+ }
7612
+
7613
+ /**
7614
+ * Returns a warning if `url` would send credentials somewhere they can be read
7615
+ * off the wire, or null if it is fine.
7616
+ *
7617
+ * Both URLs default to https, but each is overridable - `opts.valBuildUrl` /
7618
+ * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL` - and neither
7619
+ * override has ever been scheme-checked. Point one at a plain http host and the
7620
+ * api key goes out in clear text, and whatever comes back is whatever the
7621
+ * network says: for `valBuildUrl` that includes the app token this server
7622
+ * re-signs into the session cookie.
7623
+ *
7624
+ * Loopback over http is exempt: that is a val.build running on the developer's
7625
+ * own machine, and there is no network to be on the wrong side of.
7626
+ *
7627
+ * This warns rather than throws. Both overrides are set by the operator, not by
7628
+ * an attacker, so this is a misconfiguration to surface - not untrusted input to
7629
+ * reject - and refusing to boot would break anyone deliberately pointing at an
7630
+ * internal http host today.
7631
+ */
7632
+ function insecureUrlWarning(name, url) {
7633
+ let parsed;
7634
+ try {
7635
+ parsed = new URL(url);
7636
+ } catch {
7637
+ // NOTE: the URL is not echoed here. It did not parse, so there is nothing
7638
+ // to redact with, and an unparseable string can still hold a password.
7639
+ return `Val: ${name} is not a valid URL.`;
7640
+ }
7641
+ if (parsed.protocol === "https:") {
7642
+ return null;
7643
+ }
7644
+ if (parsed.protocol === "http:" && (LOOPBACK_HOSTNAMES.includes(parsed.hostname) || parsed.hostname.endsWith(".localhost"))) {
7645
+ return null;
7646
+ }
7647
+ return `Val: ${name} is set to ${forLog(parsed)}, which is not https. ` + `${WHAT_IS_AT_RISK[name]} ` + `Use https, or a loopback address for local development.`;
7648
+ }
7649
+ function warnIfInsecureUrls(urls) {
7650
+ for (const name of CREDENTIAL_BEARING_URLS) {
7651
+ const warning = insecureUrlWarning(name, urls[name]);
7652
+ if (warning) {
7653
+ console.warn(warning);
7654
+ }
7655
+ }
7656
+ }
7657
+
7436
7658
  function getPersonalAccessTokenPath(root) {
7437
7659
  return path__default.join(path__default.resolve(root), ".val", "pat.json");
7438
7660
  }
@@ -7506,24 +7728,7 @@ const ValServer = (valModules, options, callbacks) => {
7506
7728
  }).nullable()
7507
7729
  }))
7508
7730
  });
7509
- let serverOps;
7510
- if (options.mode === "fs") {
7511
- serverOps = new ValOpsFS(options.valContentUrl, options.cwd, valModules, {
7512
- formatter: options.formatter,
7513
- config: options.config
7514
- });
7515
- } else if (options.mode === "http") {
7516
- serverOps = new ValOpsHttp(options.valContentUrl, options.project, options.commit, options.branch, {
7517
- apiKey: options.apiKey
7518
- }, valModules, {
7519
- formatter: options.formatter,
7520
- root: options.root,
7521
- config: options.config
7522
- });
7523
- } else {
7524
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7525
- throw new Error("Invalid mode: " + (options === null || options === void 0 ? void 0 : options.mode));
7526
- }
7731
+ const serverOps = createValOps(valModules, options);
7527
7732
  const getAuthorizeUrl = (publicValApiRe, token) => {
7528
7733
  if (!options.project) {
7529
7734
  throw new Error("Project is not set");
@@ -10304,191 +10509,44 @@ async function createValServer(valModules, route, opts, config, callbacks, forma
10304
10509
  ...valServerConfig
10305
10510
  }, callbacks);
10306
10511
  }
10307
- async function initHandlerOptions(route, opts, config) {
10308
- const maybeApiKey = opts.apiKey || process.env.VAL_API_KEY;
10309
- const maybeValSecret = opts.valSecret || process.env.VAL_SECRET;
10310
- const isProxyMode = opts.mode === "proxy" || opts.mode === undefined && (maybeApiKey || maybeValSecret);
10311
- const valEnableRedirectUrl = opts.valEnableRedirectUrl || process.env.VAL_ENABLE_REDIRECT_URL;
10312
- const valDisableRedirectUrl = opts.valDisableRedirectUrl || process.env.VAL_DISABLE_REDIRECT_URL;
10313
- const maybeValProject = opts.project || process.env.VAL_PROJECT;
10314
- const valBuildUrl = opts.valBuildUrl || process.env.VAL_BUILD_URL || "https://admin.val.build";
10315
- const valContentUrl = opts.valContentUrl || process.env.VAL_CONTENT_URL || DEFAULT_CONTENT_HOST;
10316
- warnIfInsecureUrls({
10317
- valBuildUrl,
10318
- valContentUrl
10319
- });
10320
- if (isProxyMode) {
10321
- var _opts$versions, _opts$versions2;
10322
- if (!maybeApiKey || !maybeValSecret) {
10323
- throw new Error("VAL_API_KEY and VAL_SECRET env vars must both be set in proxy mode");
10324
- }
10325
- const maybeGitCommit = opts.gitCommit || process.env.VAL_GIT_COMMIT;
10326
- if (!maybeGitCommit) {
10327
- throw new Error("VAL_GIT_COMMIT env var must be set in proxy mode");
10512
+
10513
+ // TODO: remove
10514
+ async function safeReadGit(cwd) {
10515
+ async function findGitHead(currentDir, depth) {
10516
+ const gitHeadPath = path.join(currentDir, ".git", "HEAD");
10517
+ if (depth > 1000) {
10518
+ console.error(`Reached max depth while scanning for .git folder. Current working dir: ${cwd}.`);
10519
+ return {
10520
+ commit: undefined,
10521
+ branch: undefined
10522
+ };
10328
10523
  }
10329
- const maybeGitBranch = opts.gitBranch || process.env.VAL_GIT_BRANCH;
10330
- if (!maybeGitBranch) {
10331
- throw new Error("VAL_GIT_BRANCH env var must be set in proxy mode");
10332
- }
10333
- if (!maybeValProject) {
10334
- throw new Error("Proxy mode does not work unless the 'project' option in val.config is defined or the VAL_PROJECT env var is set.");
10335
- }
10336
- const coreVersion = (_opts$versions = opts.versions) === null || _opts$versions === void 0 ? void 0 : _opts$versions.core;
10337
- if (!coreVersion) {
10338
- throw new Error("Could not determine version of @valbuild/core");
10339
- }
10340
- const nextVersion = (_opts$versions2 = opts.versions) === null || _opts$versions2 === void 0 ? void 0 : _opts$versions2.next;
10341
- if (!nextVersion) {
10342
- throw new Error("Could not determine version of @valbuild/next");
10343
- }
10344
- return {
10345
- mode: "http",
10346
- route,
10347
- apiKey: maybeApiKey,
10348
- valSecret: maybeValSecret,
10349
- commit: maybeGitCommit,
10350
- branch: maybeGitBranch,
10351
- root: opts.root,
10352
- project: maybeValProject,
10353
- valEnableRedirectUrl,
10354
- valDisableRedirectUrl,
10355
- valContentUrl,
10356
- valBuildUrl,
10357
- config
10358
- };
10359
- } else {
10360
- const cwd = process.cwd();
10361
- return {
10362
- mode: "fs",
10363
- cwd,
10364
- route,
10365
- valDisableRedirectUrl,
10366
- valEnableRedirectUrl,
10367
- valBuildUrl,
10368
- valContentUrl,
10369
- apiKey: maybeApiKey,
10370
- valSecret: maybeValSecret,
10371
- project: maybeValProject,
10372
- config
10373
- };
10374
- }
10375
- }
10376
-
10377
- /**
10378
- * Hosts we send credentials to, and what each one puts at risk. They differ:
10379
- * only `valBuildUrl` hands back the app token that becomes the session cookie,
10380
- * so a single shared sentence would overstate one and understate the other.
10381
- */
10382
-
10383
- const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl"];
10384
- const WHAT_IS_AT_RISK = {
10385
- valBuildUrl: "Val's api key is sent to this host, and the token it returns is what this server signs into the session cookie, " + "so both can be read - and the token replaced - by anyone on the network path.",
10386
- valContentUrl: "Val's api key, or the caller's personal access token, is sent to this host, " + "so it can be read by anyone on the network path."
10387
- };
10388
-
10389
- // NOTE: `URL.hostname` keeps the brackets on an IPv6 literal, so this is
10390
- // "[::1]" and not "::1" - and `http://[0:0:0:0:0:0:0:1]` normalises to the
10391
- // same short form before it gets here. Dropping the brackets looks like a
10392
- // tidy-up and silently stops matching IPv6 loopback.
10393
- const LOOPBACK_HOSTNAMES = ["localhost", "127.0.0.1", "[::1]"];
10394
-
10395
- /**
10396
- * The URL as it is safe to print. `http://user:pass@host` is a legal override,
10397
- * and a warning about credential exposure that puts the password in the log
10398
- * would be the very thing it is warning about.
10399
- */
10400
- function forLog(parsed) {
10401
- if (!parsed.username && !parsed.password) {
10402
- return parsed.href;
10403
- }
10404
- const redacted = new URL(parsed.href);
10405
- redacted.username = "";
10406
- redacted.password = "";
10407
- return `${redacted.href} (credentials redacted)`;
10408
- }
10409
-
10410
- /**
10411
- * Returns a warning if `url` would send credentials somewhere they can be read
10412
- * off the wire, or null if it is fine.
10413
- *
10414
- * Both URLs default to https, but each is overridable - `opts.valBuildUrl` /
10415
- * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL` - and neither
10416
- * override has ever been scheme-checked. Point one at a plain http host and the
10417
- * api key goes out in clear text, and whatever comes back is whatever the
10418
- * network says: for `valBuildUrl` that includes the app token this server
10419
- * re-signs into the session cookie.
10420
- *
10421
- * Loopback over http is exempt: that is a val.build running on the developer's
10422
- * own machine, and there is no network to be on the wrong side of.
10423
- *
10424
- * This warns rather than throws. Both overrides are set by the operator, not by
10425
- * an attacker, so this is a misconfiguration to surface - not untrusted input to
10426
- * reject - and refusing to boot would break anyone deliberately pointing at an
10427
- * internal http host today.
10428
- */
10429
- function insecureUrlWarning(name, url) {
10430
- let parsed;
10431
- try {
10432
- parsed = new URL(url);
10433
- } catch {
10434
- // NOTE: the URL is not echoed here. It did not parse, so there is nothing
10435
- // to redact with, and an unparseable string can still hold a password.
10436
- return `Val: ${name} is not a valid URL.`;
10437
- }
10438
- if (parsed.protocol === "https:") {
10439
- return null;
10440
- }
10441
- if (parsed.protocol === "http:" && (LOOPBACK_HOSTNAMES.includes(parsed.hostname) || parsed.hostname.endsWith(".localhost"))) {
10442
- return null;
10443
- }
10444
- return `Val: ${name} is set to ${forLog(parsed)}, which is not https. ` + `${WHAT_IS_AT_RISK[name]} ` + `Use https, or a loopback address for local development.`;
10445
- }
10446
- function warnIfInsecureUrls(urls) {
10447
- for (const name of CREDENTIAL_BEARING_URLS) {
10448
- const warning = insecureUrlWarning(name, urls[name]);
10449
- if (warning) {
10450
- console.warn(warning);
10451
- }
10452
- }
10453
- }
10454
-
10455
- // TODO: remove
10456
- async function safeReadGit(cwd) {
10457
- async function findGitHead(currentDir, depth) {
10458
- const gitHeadPath = path.join(currentDir, ".git", "HEAD");
10459
- if (depth > 1000) {
10460
- console.error(`Reached max depth while scanning for .git folder. Current working dir: ${cwd}.`);
10461
- return {
10462
- commit: undefined,
10463
- branch: undefined
10464
- };
10465
- }
10466
- try {
10467
- const headContents = await promises.readFile(gitHeadPath, "utf-8");
10468
- const match = headContents.match(/^ref: refs\/heads\/(.+)/);
10469
- if (match) {
10470
- const branchName = match[1];
10471
- return {
10472
- branch: branchName,
10473
- commit: await readCommit(currentDir, branchName)
10474
- };
10475
- } else {
10476
- return {
10477
- commit: undefined,
10478
- branch: undefined
10479
- };
10480
- }
10481
- } catch {
10482
- const parentDir = path.dirname(currentDir);
10483
-
10484
- // We've reached the root directory
10485
- if (parentDir === currentDir) {
10486
- return {
10487
- commit: undefined,
10488
- branch: undefined
10489
- };
10490
- }
10491
- return findGitHead(parentDir, depth + 1);
10524
+ try {
10525
+ const headContents = await promises.readFile(gitHeadPath, "utf-8");
10526
+ const match = headContents.match(/^ref: refs\/heads\/(.+)/);
10527
+ if (match) {
10528
+ const branchName = match[1];
10529
+ return {
10530
+ branch: branchName,
10531
+ commit: await readCommit(currentDir, branchName)
10532
+ };
10533
+ } else {
10534
+ return {
10535
+ commit: undefined,
10536
+ branch: undefined
10537
+ };
10538
+ }
10539
+ } catch {
10540
+ const parentDir = path.dirname(currentDir);
10541
+
10542
+ // We've reached the root directory
10543
+ if (parentDir === currentDir) {
10544
+ return {
10545
+ commit: undefined,
10546
+ branch: undefined
10547
+ };
10548
+ }
10549
+ return findGitHead(parentDir, depth + 1);
10492
10550
  }
10493
10551
  }
10494
10552
  try {
@@ -10744,6 +10802,1288 @@ function getCookies(req, cookiesDef) {
10744
10802
  return z.object(cookiesDef).safeParse(input);
10745
10803
  }
10746
10804
 
10805
+ /**
10806
+ * How a tool is written, and what it is handed.
10807
+ *
10808
+ * Tools are defined with {@link defineTool} so that the handler's `args` are
10809
+ * inferred from the tool's own `inputSchema`. Without that the array of tools
10810
+ * would have to be typed at its widest and every handler would start by
10811
+ * re-narrowing `unknown`, which is exactly where a tool and its schema drift
10812
+ * apart unnoticed.
10813
+ */
10814
+
10815
+ /** Everything a tool is allowed to reach. Deliberately narrow. */
10816
+
10817
+ /**
10818
+ * Declare a tool, binding its handler to its input schema.
10819
+ *
10820
+ * The handler receives already-parsed arguments: the registry validates against
10821
+ * `inputSchema` before calling, so a handler never sees input its schema would
10822
+ * have rejected.
10823
+ */
10824
+ function defineTool(definition, handler) {
10825
+ return {
10826
+ ...definition,
10827
+ handler: (args, deps) => handler(args, deps)
10828
+ };
10829
+ }
10830
+ function ok(data) {
10831
+ return {
10832
+ status: "ok",
10833
+ data
10834
+ };
10835
+ }
10836
+ function err(code, message) {
10837
+ return {
10838
+ status: "error",
10839
+ code,
10840
+ message
10841
+ };
10842
+ }
10843
+
10844
+ /**
10845
+ * The tools that only read.
10846
+ *
10847
+ * Names match the Studio's chat tools exactly. MCP clients namespace by server,
10848
+ * so there is no `val_` prefix to add, and keeping the names identical means
10849
+ * converging the two definitions later is a move rather than a rename.
10850
+ *
10851
+ * All of these read from `deps.state`, which already has pending patches
10852
+ * applied — an agent should see the content as the Studio would show it, not the
10853
+ * last published version.
10854
+ */
10855
+
10856
+ const ModuleFilePathSchema$1 = z.string().describe('Path of the Val module, e.g. "/content/pages.val.ts". Use get_all_schema to discover these.');
10857
+ function readTools() {
10858
+ return [defineTool({
10859
+ name: "get_all_schema",
10860
+ title: "Get all schemas",
10861
+ description: "List every Val module in the project and its schema. Start here: the module paths this returns are what every other tool takes.",
10862
+ inputSchema: z.object({}),
10863
+ annotations: {
10864
+ readOnlyHint: true,
10865
+ idempotentHint: true
10866
+ }
10867
+ }, async (_args, {
10868
+ state
10869
+ }) => ok(state.serializedSchemas)), defineTool({
10870
+ name: "get_source",
10871
+ title: "Get source",
10872
+ description: "Read the content of one Val module, with any unpublished changes already applied.",
10873
+ inputSchema: z.object({
10874
+ moduleFilePath: ModuleFilePathSchema$1
10875
+ }),
10876
+ annotations: {
10877
+ readOnlyHint: true,
10878
+ idempotentHint: true
10879
+ }
10880
+ }, async ({
10881
+ moduleFilePath
10882
+ }, {
10883
+ state
10884
+ }) => {
10885
+ const path = moduleFilePath;
10886
+ if (!(path in state.serializedSchemas)) {
10887
+ return err("not-found", unknownModuleMessage(path, state));
10888
+ }
10889
+ const source = state.sources[path];
10890
+ return ok(source === undefined ? null : source);
10891
+ }), defineTool({
10892
+ name: "get_record_keys",
10893
+ title: "Get record keys",
10894
+ description: "List the keys of the record or object at a path inside a module, a page at a time. Use this to enumerate entries without reading their contents — and before adding one, so you do not collide with an existing key. Fails on arrays, galleries, richtext and primitives: use count_entries for an array or richtext length, and get_source to read a gallery.",
10895
+ inputSchema: z.object({
10896
+ moduleFilePath: ModuleFilePathSchema$1,
10897
+ path: z.array(z.string()).default([]).describe("Path within the module to the record or object. Empty means the module root."),
10898
+ // Clamped by the schema rather than in the handler: a negative offset
10899
+ // makes `slice` read from the END and a negative limit makes it drop
10900
+ // the last N, so either would return a window that is not the page
10901
+ // asked for while `total` alongside implied it was.
10902
+ limit: z.number().int().min(1).default(100).describe("Maximum number of keys to return."),
10903
+ offset: z.number().int().min(0).default(0).describe("Number of keys to skip, for paging.")
10904
+ }),
10905
+ annotations: {
10906
+ readOnlyHint: true,
10907
+ idempotentHint: true
10908
+ }
10909
+ }, async ({
10910
+ moduleFilePath,
10911
+ path,
10912
+ limit,
10913
+ offset
10914
+ }, {
10915
+ state
10916
+ }) => {
10917
+ const described = describeContainer(state, moduleFilePath, path);
10918
+ if (described.kind !== "ok") {
10919
+ return described.result;
10920
+ }
10921
+ const {
10922
+ container,
10923
+ value
10924
+ } = described;
10925
+ // Records and objects only, matching the Studio's tool of the same name.
10926
+ // A gallery's keys are file paths whose bytes live elsewhere, and
10927
+ // richtext blocks are positional — neither is a key set to hand back.
10928
+ if (container !== "record" && container !== "object" || !isPlainObject(value)) {
10929
+ return err("invalid-args", `The value at that path is ${article(container)} ${container}. get_record_keys only works on a record or an object — ${container === "array" ? "use count_entries for the array length" : container === "richtext" ? "use count_entries for the number of blocks" : "use get_source to read the gallery's entries"}.`);
10930
+ }
10931
+ const keys = Object.keys(value);
10932
+ return ok({
10933
+ kind: container,
10934
+ keys: keys.slice(offset, offset + limit),
10935
+ // The unpaged size, so a caller can tell a short page from the end of
10936
+ // the record without asking for another one.
10937
+ total: keys.length
10938
+ });
10939
+ }), defineTool({
10940
+ name: "count_entries",
10941
+ title: "Count entries",
10942
+ description: "Count the entries at a path inside a module — record or gallery keys, object fields, array indices, or top-level richtext blocks — without reading them. Use this to answer 'how many?' or to size a record before paging through it.",
10943
+ inputSchema: z.object({
10944
+ moduleFilePath: ModuleFilePathSchema$1,
10945
+ path: z.array(z.string()).default([]).describe("Path within the module to count at. Empty means the module root.")
10946
+ }),
10947
+ annotations: {
10948
+ readOnlyHint: true,
10949
+ idempotentHint: true
10950
+ }
10951
+ }, async ({
10952
+ moduleFilePath,
10953
+ path
10954
+ }, {
10955
+ state
10956
+ }) => {
10957
+ const described = describeContainer(state, moduleFilePath, path);
10958
+ if (described.kind !== "ok") {
10959
+ return described.result;
10960
+ }
10961
+ const {
10962
+ container,
10963
+ value
10964
+ } = described;
10965
+ // Every container `describeContainerAtPath` admits can be counted, so
10966
+ // unlike get_record_keys this does not narrow further. Non-containers
10967
+ // never get this far.
10968
+ if (Array.isArray(value)) {
10969
+ return ok({
10970
+ kind: container,
10971
+ count: value.length
10972
+ });
10973
+ }
10974
+ if (isPlainObject(value)) {
10975
+ return ok({
10976
+ kind: container,
10977
+ count: Object.keys(value).length
10978
+ });
10979
+ }
10980
+ return err("invalid-args", `The value at that path is ${article(container)} ${container}, which has nothing to count.`);
10981
+ }), defineTool({
10982
+ name: "validate_content",
10983
+ title: "Validate content",
10984
+ description: "Check the project's content against its schemas, including unpublished changes. Returns only errors that would block publishing.",
10985
+ inputSchema: z.object({
10986
+ moduleFilePath: ModuleFilePathSchema$1.optional().describe("Limit the check to one module. Omit to validate everything.")
10987
+ }),
10988
+ annotations: {
10989
+ readOnlyHint: true
10990
+ }
10991
+ }, async ({
10992
+ moduleFilePath
10993
+ }, {
10994
+ ops,
10995
+ state
10996
+ }) => {
10997
+ const validation = await ops.validateSources(state.schemas, state.sources,
10998
+ // Every module. The third argument filters which modules are
10999
+ // validated at all, so passing the pending-patch analysis would make
11000
+ // a project with no pending changes report `valid: true` without
11001
+ // having checked anything. Scoping to one module, when asked, is done
11002
+ // on the results below.
11003
+ undefined);
11004
+ // `validateSources` hands back the files it could not check on its own;
11005
+ // running them is what turns "this path holds a file" into "that file is
11006
+ // actually there and matches its recorded metadata".
11007
+ const fileErrors = await ops.validateFiles(state.schemas, state.sources, validation.files, state.analysis.fileLastUpdatedByPatchId);
11008
+
11009
+ // Per-module results, flattened to the by-source-path shape the filter
11010
+ // takes. Merged rather than overwritten: a path can pick up an error
11011
+ // from validation and another from its file.
11012
+ const bySourcePath = {};
11013
+ const add = (path, errors) => {
11014
+ bySourcePath[path] = (bySourcePath[path] ?? []).concat(errors);
11015
+ };
11016
+ for (const moduleErrors of Object.values(validation.errors)) {
11017
+ for (const [path, errors] of Object.entries(moduleErrors.validations ?? {})) {
11018
+ add(path, errors);
11019
+ }
11020
+ }
11021
+ for (const [path, errors] of Object.entries(fileErrors)) {
11022
+ add(path, errors);
11023
+ }
11024
+
11025
+ // Drops the errors the Studio would not show either: ones whose only
11026
+ // effect is an offered fix. Left in, an agent would loop trying to
11027
+ // "repair" content that is already publishable.
11028
+ const blocking = filterBlockingValidationErrors(bySourcePath, state.serializedSchemas, state.sources);
11029
+
11030
+ // A module whose source could not be read at all has no source path to
11031
+ // hang an error on, so it is reported separately rather than lost.
11032
+ const unreadable = Object.entries(validation.errors).filter(([, moduleErrors]) => moduleErrors.invalidSource).map(([path, moduleErrors]) => {
11033
+ var _moduleErrors$invalid;
11034
+ return {
11035
+ moduleFilePath: path,
11036
+ message: ((_moduleErrors$invalid = moduleErrors.invalidSource) === null || _moduleErrors$invalid === void 0 ? void 0 : _moduleErrors$invalid.message) ?? "Invalid source"
11037
+ };
11038
+ });
11039
+ const scope = moduleFilePath;
11040
+ const errors = scope === undefined ? blocking : filterKeysByModule(blocking, scope);
11041
+ const unreadableInScope = scope === undefined ? unreadable : unreadable.filter(u => u.moduleFilePath === scope);
11042
+ return ok({
11043
+ valid: Object.keys(errors).length === 0 && unreadableInScope.length === 0,
11044
+ errors: Object.fromEntries(Object.entries(errors).map(([path, errs]) => [path, errs.map(toJsonValidationError)])),
11045
+ // Always present, empty when there are none: a caller should not have
11046
+ // to tell "absent" from "empty" to decide whether content is publishable.
11047
+ unreadableModules: unreadableInScope
11048
+ });
11049
+ }), defineTool({
11050
+ name: "get_patches",
11051
+ title: "Get patches",
11052
+ description: "List the unpublished changes in the project, oldest first, with who made each one. A change reported as not applying is why a module's content may not match what publishing would produce, and why writing to that module is refused.",
11053
+ inputSchema: z.object({
11054
+ moduleFilePath: ModuleFilePathSchema$1.optional().describe("Limit to changes touching one module.")
11055
+ }),
11056
+ annotations: {
11057
+ readOnlyHint: true
11058
+ }
11059
+ }, async ({
11060
+ moduleFilePath
11061
+ }, {
11062
+ state
11063
+ }) => {
11064
+ const wanted = moduleFilePath === undefined ? state.patches.patches : state.patches.patches.filter(p => p.path === moduleFilePath);
11065
+ // Which patches would not apply, flattened to one lookup by id: without
11066
+ // this a module's content can silently differ from what publishing
11067
+ // would produce, and nothing anywhere says why.
11068
+ const failures = new Map();
11069
+ for (const unapplied of Object.values(state.unappliedPatches)) {
11070
+ for (const failure of unapplied) {
11071
+ failures.set(failure.patchId, failure.error.message);
11072
+ }
11073
+ }
11074
+ return ok(wanted.map(patch => {
11075
+ const failure = failures.get(patch.patchId);
11076
+ return {
11077
+ patchId: patch.patchId,
11078
+ moduleFilePath: patch.path,
11079
+ createdAt: patch.createdAt,
11080
+ authorId: patch.authorId,
11081
+ // `appliedAt` non-null means this change is already committed, so
11082
+ // it is history rather than something still pending.
11083
+ published: patch.appliedAt !== null,
11084
+ // Always present, so "applies cleanly" is stated rather than
11085
+ // inferred from the absence of a field.
11086
+ appliesCleanly: failure === undefined,
11087
+ ...(failure === undefined ? {} : {
11088
+ applyError: failure
11089
+ })
11090
+ };
11091
+ }));
11092
+ }), defineTool({
11093
+ name: "get_source_path_from_route",
11094
+ title: "Get source path from route",
11095
+ description: "Given a URL path on the site, find the Val module and source path that renders it. Use this when the user names a page rather than a module.",
11096
+ inputSchema: z.object({
11097
+ route: z.string().describe('A route on the site, e.g. "/blog/my-post".')
11098
+ }),
11099
+ annotations: {
11100
+ readOnlyHint: true,
11101
+ idempotentHint: true
11102
+ }
11103
+ }, async ({
11104
+ route
11105
+ }, {
11106
+ state
11107
+ }) => {
11108
+ const found = getSourcePathFromRoute(route, state.serializedSchemas);
11109
+ if (!found) {
11110
+ return err("not-found", `No Val module renders the route ${JSON.stringify(route)}. Routes come from modules with a router configured; get_all_schema shows which have one.`);
11111
+ }
11112
+ return ok(found);
11113
+ })];
11114
+ }
11115
+
11116
+ /**
11117
+ * Resolve a module and classify the value at a path inside it.
11118
+ *
11119
+ * Shared by `get_record_keys` and `count_entries` so the two cannot drift on
11120
+ * what counts as a missing module, and so both map the same failure to the same
11121
+ * error code: a path that is not there is `not-found`, while a path that is
11122
+ * there but holds a string or an image is `invalid-args` — the caller should
11123
+ * reach for a different tool, not go looking for the path again.
11124
+ */
11125
+ function describeContainer(state, moduleFilePath, path) {
11126
+ const modulePath = moduleFilePath;
11127
+ const schema = state.serializedSchemas[modulePath];
11128
+ if (!schema) {
11129
+ return {
11130
+ kind: "error",
11131
+ result: err("not-found", unknownModuleMessage(modulePath, state))
11132
+ };
11133
+ }
11134
+ const described = describeContainerAtPath(schema, state.sources[modulePath], path);
11135
+ if (described.kind === "error") {
11136
+ return {
11137
+ kind: "error",
11138
+ result: err(described.reason === "missing" ? "not-found" : "invalid-args", described.message)
11139
+ };
11140
+ }
11141
+ return described;
11142
+ }
11143
+
11144
+ /** "a record", but "an object" and "an array". */
11145
+ function article(container) {
11146
+ return container === "object" || container === "array" ? "an" : "a";
11147
+ }
11148
+ function unknownModuleMessage(path, state) {
11149
+ const known = Object.keys(state.serializedSchemas);
11150
+ return `No Val module at ${JSON.stringify(path)}. Known modules: ${known.length === 0 ? "(none)" : known.join(", ")}`;
11151
+ }
11152
+
11153
+ /**
11154
+ * Project a validation error into something JSON-safe and worth reading.
11155
+ *
11156
+ * `ValidationError.value` is dropped rather than serialized: it is `unknown` (so
11157
+ * not `Json` to begin with) and it holds the offending source value, which can
11158
+ * be arbitrarily large. A caller already has the source path and can read the
11159
+ * value with `get_source` if it needs to — putting it here would bloat every
11160
+ * result for the rare case that wants it.
11161
+ *
11162
+ * `fixes` is kept, because it names what Val already knows how to repair, which
11163
+ * is directly actionable.
11164
+ */
11165
+ function toJsonValidationError(error) {
11166
+ return {
11167
+ message: error.message,
11168
+ fixes: error.fixes ? [...error.fixes] : [],
11169
+ typeError: error.typeError === true,
11170
+ schemaError: error.schemaError === true,
11171
+ keyError: error.keyError === true
11172
+ };
11173
+ }
11174
+ function isPlainObject(value) {
11175
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11176
+ }
11177
+
11178
+ /**
11179
+ * Keep only the entries belonging to one module.
11180
+ *
11181
+ * Keyed by SourcePath, which begins with the module file path, so a prefix match
11182
+ * is the right test — there is no per-module grouping left to index by.
11183
+ */
11184
+ function filterKeysByModule(record, moduleFilePath) {
11185
+ const out = {};
11186
+ for (const [path, value] of Object.entries(record)) {
11187
+ if (path.startsWith(moduleFilePath)) {
11188
+ out[path] = value;
11189
+ }
11190
+ }
11191
+ return out;
11192
+ }
11193
+
11194
+ /**
11195
+ * Everything the Studio does client-side before a patch can be saved, done
11196
+ * server-side.
11197
+ *
11198
+ * Three things had no server equivalent, and each is a way to be quietly wrong:
11199
+ * where the patch id comes from, what the patch says its parent is, and whether
11200
+ * the result would even be valid. `docs/plans/mcp.md` Part C is the design.
11201
+ */
11202
+
11203
+ const jsonOps = new JSONOps();
11204
+
11205
+ /**
11206
+ * A patch id, minted before the write is attempted.
11207
+ *
11208
+ * Same shape the Studio mints (a v4 UUID), and minting one that never gets used
11209
+ * costs nothing — ids are not registered anywhere until a patch carries them.
11210
+ */
11211
+ function mintPatchId() {
11212
+ // A branded string has no constructor; this is the same conversion the Studio
11213
+ // and ValServer both make.
11214
+ return randomUUID();
11215
+ }
11216
+
11217
+ /**
11218
+ * What the new patch should hang off.
11219
+ *
11220
+ * The last known patch if there is one, otherwise the current head. Note the
11221
+ * asymmetry between the two backends: `ValOpsFS` ignores `parentRef` entirely
11222
+ * because its append-only ordering log defines order, while `ValOpsHttp` sends
11223
+ * it up as `parentPatchId` for optimistic concurrency. So a wrong value here is
11224
+ * invisible locally and a conflict in production — which is why this is derived
11225
+ * fresh rather than remembered.
11226
+ */
11227
+ async function deriveParentRef(ops,
11228
+ // Only the ids matter, so this accepts either shape `fetchPatches` can
11229
+ // return — the metadata-only variant omits the ops but keeps the ids.
11230
+ patches) {
11231
+ const last = patches.patches[patches.patches.length - 1];
11232
+ if (last) {
11233
+ return {
11234
+ type: "patch",
11235
+ patchId: last.patchId
11236
+ };
11237
+ }
11238
+ return {
11239
+ type: "head",
11240
+ headBaseSha: await ops.getBaseSha()
11241
+ };
11242
+ }
11243
+
11244
+ /**
11245
+ * Would this patch leave the content valid?
11246
+ *
11247
+ * Applied to a **clone** of the sources, never the real ones: `applyPatch`
11248
+ * mutates the document it is given, and ValOps carries a standing note that
11249
+ * add operations misbehave without a clone. Validating in place would corrupt
11250
+ * the sources every later call in this process reads.
11251
+ *
11252
+ * Server-side this is strictly better than the Studio's speculative check.
11253
+ * `getSchemas()` returns real `Schema` instances, so the user's own `validate`
11254
+ * closures run — and those are not carried by the serialized schema the browser
11255
+ * has, which means the browser cannot run them at all.
11256
+ */
11257
+ async function validateSpeculatively(ops, state, moduleFilePath, patch) {
11258
+ const current = state.sources[moduleFilePath];
11259
+ if (current === undefined) {
11260
+ return {
11261
+ status: "unapplicable",
11262
+ result: {
11263
+ status: "error",
11264
+ code: "not-found",
11265
+ message: `No Val module at ${JSON.stringify(moduleFilePath)}.`
11266
+ }
11267
+ };
11268
+ }
11269
+ const applied = applyPatch(deepClone(current), jsonOps, patch);
11270
+ if (result.isErr(applied)) {
11271
+ return {
11272
+ status: "unapplicable",
11273
+ result: {
11274
+ status: "error",
11275
+ code: "invalid-args",
11276
+ message: `The patch cannot be applied to ${moduleFilePath}: ${applied.error.message}`
11277
+ }
11278
+ };
11279
+ }
11280
+ const speculativeSources = {
11281
+ ...state.sources,
11282
+ [moduleFilePath]: applied.value
11283
+ };
11284
+ const after = await blockingErrorsIn(ops, state, speculativeSources, moduleFilePath);
11285
+ if (after.length === 0) {
11286
+ return {
11287
+ status: "valid"
11288
+ };
11289
+ }
11290
+
11291
+ // Only the errors this patch *introduces*. A module can already be broken for
11292
+ // reasons this change has nothing to do with -- the example app ships with a
11293
+ // missing image file -- and refusing on the total would make every such module
11294
+ // permanently read-only: an agent could not fix a typo in a file that also
11295
+ // holds a broken image reference. Paid for only when there is something to
11296
+ // refuse, so an ordinary clean edit still validates once.
11297
+ const before = await blockingErrorsIn(ops, state, state.sources, moduleFilePath);
11298
+ const existing = new Set(before.map(identify));
11299
+ const introduced = after.filter(error => !existing.has(identify(error)));
11300
+ if (introduced.length === 0) {
11301
+ return {
11302
+ status: "valid"
11303
+ };
11304
+ }
11305
+ return {
11306
+ status: "invalid",
11307
+ errors: describeErrors(introduced)
11308
+ };
11309
+ }
11310
+ /** Path and message together: the same message at another path is another problem. */
11311
+ function identify(error) {
11312
+ return `${error.path}\u0000${error.message}`;
11313
+ }
11314
+
11315
+ /**
11316
+ * The publishing-blocking errors in one module, for a given set of sources.
11317
+ *
11318
+ * Scoped to one module by source path, which starts with the module file path.
11319
+ * Errors elsewhere in the project are somebody else's: refusing on them would
11320
+ * let the first broken module in a repo make every other module read-only.
11321
+ */
11322
+ async function blockingErrorsIn(ops, state, sources, moduleFilePath) {
11323
+ const validation = await ops.validateSources(state.schemas, sources,
11324
+ // Every module, deliberately -- `patchesByModule` is a FILTER on which
11325
+ // modules get validated, not context for validating them. Passing the
11326
+ // analysis from before this write skips the very module being written
11327
+ // whenever it had no pending patch, so the first change to a module went
11328
+ // unchecked; and a change that breaks a `keyOf` or a router in a *different*
11329
+ // module reports its error there, which a filtered run never visits.
11330
+ undefined);
11331
+ // `validateSources` hands back the files it could not check on its own;
11332
+ // running them is what turns "this path holds a file" into "that file is
11333
+ // actually there and matches its recorded metadata".
11334
+ const fileErrors = await ops.validateFiles(state.schemas, sources, validation.files, state.analysis.fileLastUpdatedByPatchId);
11335
+
11336
+ // Merged rather than overwritten: a path can pick up an error from validation
11337
+ // and another from its file.
11338
+ const bySourcePath = {};
11339
+ const add = (path, errors) => {
11340
+ bySourcePath[path] = (bySourcePath[path] ?? []).concat(errors);
11341
+ };
11342
+ for (const moduleErrors of Object.values(validation.errors)) {
11343
+ for (const [path, errors] of Object.entries(moduleErrors.validations ?? {})) {
11344
+ add(path, errors);
11345
+ }
11346
+ }
11347
+ for (const [path, errors] of Object.entries(fileErrors)) {
11348
+ add(path, errors);
11349
+ }
11350
+ const blocking = filterBlockingValidationErrors(bySourcePath, state.serializedSchemas, sources);
11351
+ const located = [];
11352
+ for (const [path, errors] of Object.entries(blocking)) {
11353
+ if (!path.startsWith(moduleFilePath)) {
11354
+ continue;
11355
+ }
11356
+ for (const error of errors) {
11357
+ located.push({
11358
+ path: path,
11359
+ message: error.message
11360
+ });
11361
+ }
11362
+ }
11363
+ return located;
11364
+ }
11365
+ function describeErrors(errors) {
11366
+ return errors.map(e => `${e.path}: ${e.message}`).join("; ");
11367
+ }
11368
+
11369
+ /**
11370
+ * What to do when the change would leave the content invalid.
11371
+ *
11372
+ * `"reject"` for a tool that is editing existing content: an agent should not be
11373
+ * able to break a site, and a rejected patch stores nothing.
11374
+ *
11375
+ * `"report"` for a tool whose whole purpose is to create something incomplete.
11376
+ * `empty_at_path` scaffolds an entry the caller is then expected to fill in, so
11377
+ * on most real schemas — anything with a non-empty string — the value it creates
11378
+ * is invalid by construction. Rejecting that would make the tool useless on
11379
+ * exactly the schemas it exists for, so instead the patch is saved and the
11380
+ * remaining errors come back as a to-do list. This mirrors the Studio, where
11381
+ * creating an empty entry is normal and the errors show until it is filled in.
11382
+ */
11383
+
11384
+ /**
11385
+ * Validate, then save — and retry once if someone else got there first.
11386
+ *
11387
+ * The retry exists because the parent ref is derived from a read that happened
11388
+ * before the write. A conflict means the chain moved underneath us, and
11389
+ * re-deriving is usually enough. Once only: a loop here would be an agent
11390
+ * fighting a human editor in the Studio, and losing slowly is worse than
11391
+ * failing clearly.
11392
+ */
11393
+ async function savePatch(deps, moduleFilePath, patch, onInvalid = "reject") {
11394
+ var _ctx$auth;
11395
+ const {
11396
+ ops,
11397
+ ctx,
11398
+ state
11399
+ } = deps;
11400
+ const unapplied = state.unappliedPatches[moduleFilePath];
11401
+ if (unapplied && unapplied.length > 0) {
11402
+ // Refused before anything is validated, because the state to validate
11403
+ // against is wrong. `sources` for this module silently lacks these pending
11404
+ // changes, so a patch built on it would be based on content that will never
11405
+ // exist -- and its parent ref would chain onto changes that do not apply.
11406
+ return {
11407
+ status: "error",
11408
+ code: "internal",
11409
+ message: `Cannot write to ${moduleFilePath}: it has ${unapplied.length} pending change${unapplied.length === 1 ? "" : "s"} that will not apply, so what is stored is not what publishing would produce. Resolve or discard ${unapplied.map(u => u.patchId).join(", ")} first -- get_patches shows them.`
11410
+ };
11411
+ }
11412
+ const speculative = await validateSpeculatively(ops, state, moduleFilePath, patch);
11413
+ if (speculative.status === "unapplicable") {
11414
+ // Never negotiable: the patch does not fit the content, so there is nothing
11415
+ // to save whatever the caller's tolerance for invalid results.
11416
+ return speculative.result;
11417
+ }
11418
+ let unresolved = null;
11419
+ if (speculative.status === "invalid") {
11420
+ if (onInvalid === "reject") {
11421
+ return {
11422
+ status: "error",
11423
+ code: "validation-failed",
11424
+ message: `The change was rejected and nothing was saved, because it would leave the content invalid: ${speculative.errors}`
11425
+ };
11426
+ }
11427
+ unresolved = speculative.errors;
11428
+ }
11429
+
11430
+ /**
11431
+ * Null on the PAT path, and the verified profile on the token path.
11432
+ *
11433
+ * The PAT case is unchanged and still deliberate: the app cannot resolve a
11434
+ * PAT, so any id it wrote here would be an unverified claim dressed up as a
11435
+ * checked one — and the request already carries the caller's own token, which
11436
+ * is a better answer to "who did this" than anything the app could assert.
11437
+ * Attributing that patch is the backend's job.
11438
+ *
11439
+ * The token case is the opposite situation, which is why it gets the opposite
11440
+ * answer. The host verified a signature over a key it does not hold, so the
11441
+ * profile is checked rather than claimed, and the backend has no token of its
11442
+ * own to attribute from — the call reaches it under the app's API key. If this
11443
+ * stayed null, every edit made through a signed-in editor's own session would
11444
+ * land with no author at all, which is worse than useless on a CMS whose
11445
+ * review screen is organised by who changed what.
11446
+ */
11447
+ const authorId = ((_ctx$auth = ctx.auth) === null || _ctx$auth === void 0 ? void 0 : _ctx$auth.type) === "verified-profile" ? ctx.auth.profileId : null;
11448
+ for (let attempt = 0; attempt < 2; attempt++) {
11449
+ const patchId = mintPatchId();
11450
+ // Re-derived on the retry rather than reused: reusing the ref that just
11451
+ // conflicted would conflict again by definition.
11452
+ const patches = attempt === 0 ? state.patches : await ops.fetchPatches({
11453
+ excludePatchOps: true
11454
+ });
11455
+ const parentRef = await deriveParentRef(ops, patches);
11456
+ const saved = await ops.createPatch(moduleFilePath, patch, patchId, parentRef, ctx.sessionId, authorId);
11457
+ if (result.isOk(saved)) {
11458
+ return {
11459
+ status: "ok",
11460
+ data: {
11461
+ patchId: saved.value.patchId,
11462
+ moduleFilePath,
11463
+ createdAt: saved.value.createdAt,
11464
+ // Always present, so a caller does not have to tell "absent" from
11465
+ // "nothing left to do" to know whether the content is publishable.
11466
+ unresolvedValidationErrors: unresolved
11467
+ }
11468
+ };
11469
+ }
11470
+ if (saved.error.errorType === "patch-head-conflict") {
11471
+ continue;
11472
+ }
11473
+ return {
11474
+ status: "error",
11475
+ code: "internal",
11476
+ // Note the nesting: createPatch wraps the underlying flat error as
11477
+ // `{ errorType: "other", error: <that> }`.
11478
+ message: saved.error.error.message
11479
+ };
11480
+ }
11481
+ return {
11482
+ status: "error",
11483
+ code: "conflict",
11484
+ message: "Another change was saved while this one was being written, twice in a row. Read the content again before retrying — it has moved."
11485
+ };
11486
+ }
11487
+
11488
+ /**
11489
+ * The tools that change content.
11490
+ *
11491
+ * Every one of them goes through {@link savePatch}, so they all inherit the same
11492
+ * guarantees: the change is validated against the real schemas before anything
11493
+ * is stored, a rejected change stores nothing, and a lost race with another
11494
+ * writer is retried once and then reported rather than looped on.
11495
+ *
11496
+ * Images are not here. The Studio's image tools work from a handle into Val's
11497
+ * AI session store — bytes the browser got from the vision system — and MCP has
11498
+ * no equivalent, so they need a different affordance (a local file path, or
11499
+ * inline base64) rather than a port. `docs/plans/mcp.md` Part B has the reasoning.
11500
+ */
11501
+
11502
+ const ModuleFilePathSchema = z.string().describe('Path of the Val module, e.g. "/content/pages.val.ts".');
11503
+ function writeTools() {
11504
+ return [defineTool({
11505
+ name: "create_patch",
11506
+ title: "Create patch",
11507
+ description: "Change content in a Val module by applying JSON Patch operations. The change is validated first and is rejected outright if it would make the content invalid. Text and JSON values only — not files or images.",
11508
+ inputSchema: z.object({
11509
+ moduleFilePath: ModuleFilePathSchema,
11510
+ patch: z.array(z.unknown()).describe('JSON Patch operations, e.g. [{"op":"replace","path":["title"],"value":"New title"}]. Paths are arrays of keys, not slash-separated strings.')
11511
+ }),
11512
+ annotations: {
11513
+ idempotentHint: false
11514
+ }
11515
+ }, async ({
11516
+ moduleFilePath,
11517
+ patch
11518
+ }, deps) => {
11519
+ // Before parsing, not after: a file op that is also malformed should be
11520
+ // told that files are not supported, rather than handed a schema error
11521
+ // about the shape of a thing it was never going to be allowed to do.
11522
+ const rejected = rejectFileOps(patch);
11523
+ if (rejected) {
11524
+ return rejected;
11525
+ }
11526
+ const parsed = safeParsePatch(patch);
11527
+ if (parsed.kind !== "ok") {
11528
+ return fromBuildResult(parsed);
11529
+ }
11530
+ return savePatch(deps, moduleFilePath, parsed.patch);
11531
+ }), defineTool({
11532
+ name: "duplicate_source",
11533
+ title: "Duplicate source",
11534
+ description: "Copy the value at one path in a module to another path. Use this to add an entry modelled on an existing one, rather than composing it field by field.",
11535
+ inputSchema: z.object({
11536
+ moduleFilePath: ModuleFilePathSchema,
11537
+ sourcePath: z.array(z.string()).describe("Path of the value to copy."),
11538
+ destinationPath: z.array(z.string()).describe("Path to copy it to. Must not already exist.")
11539
+ }),
11540
+ annotations: {
11541
+ idempotentHint: false
11542
+ }
11543
+ }, async ({
11544
+ moduleFilePath,
11545
+ sourcePath,
11546
+ destinationPath
11547
+ }, deps) => {
11548
+ const modulePath = moduleFilePath;
11549
+ const schema = deps.state.serializedSchemas[modulePath];
11550
+ if (!schema) {
11551
+ return err("not-found", `No Val module at ${JSON.stringify(modulePath)}.`);
11552
+ }
11553
+ const built = buildDuplicatePatch({
11554
+ sourcePath,
11555
+ destinationPath
11556
+ }, schema, deps.state.sources[modulePath]);
11557
+ if (built.kind !== "ok") {
11558
+ return fromBuildResult(built);
11559
+ }
11560
+ return savePatch(deps, modulePath, built.patch);
11561
+ }), defineTool({
11562
+ name: "empty_at_path",
11563
+ title: "Create an empty value at a path",
11564
+ description: "Create a new, schema-correct empty value at a path — an empty entry in a record or array, for instance. Prefer this over composing one by hand: it derives the shape from the schema, including required fields. The value it creates is usually not yet publishable; the result lists what still needs filling in, which you can then do with create_patch.",
11565
+ inputSchema: z.object({
11566
+ moduleFilePath: ModuleFilePathSchema,
11567
+ destinationPath: z.array(z.string()).describe("Path to create the empty value at.")
11568
+ }),
11569
+ annotations: {
11570
+ idempotentHint: false
11571
+ }
11572
+ }, async ({
11573
+ moduleFilePath,
11574
+ destinationPath
11575
+ }, deps) => {
11576
+ const modulePath = moduleFilePath;
11577
+ const schema = deps.state.serializedSchemas[modulePath];
11578
+ if (!schema) {
11579
+ return err("not-found", `No Val module at ${JSON.stringify(modulePath)}.`);
11580
+ }
11581
+ const built = buildEmptyAtPathPatch({
11582
+ destinationPath
11583
+ }, schema, deps.state.sources[modulePath]);
11584
+ if (built.kind !== "ok") {
11585
+ return fromBuildResult(built);
11586
+ }
11587
+ // "report", not "reject": an empty entry is invalid by construction on
11588
+ // any schema with a required non-empty field, which is most of them.
11589
+ // See OnInvalid in writePath.ts.
11590
+ return savePatch(deps, modulePath, built.patch, "report");
11591
+ }), defineTool({
11592
+ name: "remove_image_gallery_entry",
11593
+ title: "Remove an image gallery entry",
11594
+ description: "Remove one image from an image gallery module by its file path. This deletes the entry and the file it refers to.",
11595
+ inputSchema: z.object({
11596
+ moduleFilePath: ModuleFilePathSchema.describe("The gallery module, i.e. one declared with s.images() or s.files()."),
11597
+ filePath: z.string().describe('The gallery key to remove, e.g. "/public/val/photo_a1b2c.jpg".')
11598
+ }),
11599
+ // Destructive: it removes content and the underlying file, so a host
11600
+ // that asks for confirmation should ask here.
11601
+ annotations: {
11602
+ destructiveHint: true,
11603
+ idempotentHint: false
11604
+ }
11605
+ }, async ({
11606
+ moduleFilePath,
11607
+ filePath
11608
+ }, deps) => {
11609
+ const modulePath = moduleFilePath;
11610
+ const schema = deps.state.serializedSchemas[modulePath];
11611
+ if (!schema) {
11612
+ return err("not-found", `No Val module at ${JSON.stringify(modulePath)}.`);
11613
+ }
11614
+ const built = buildRemoveImageGalleryEntryPatch({
11615
+ filePath
11616
+ }, schema, deps.state.sources[modulePath]);
11617
+ if (built.kind !== "ok") {
11618
+ return fromBuildResult(built);
11619
+ }
11620
+ return savePatch(deps, modulePath, built.patch);
11621
+ })];
11622
+ }
11623
+
11624
+ /**
11625
+ * Turn a helper's build failure into a tool error.
11626
+ *
11627
+ * `wrong-tool` is worth keeping distinct: the helpers can tell that the caller
11628
+ * reached for the wrong tool and which one it should have used, and passing that
11629
+ * through is what lets a model correct itself in one step instead of retrying
11630
+ * the same call.
11631
+ */
11632
+ function fromBuildResult(built) {
11633
+ if (built.kind === "wrong-tool") {
11634
+ return {
11635
+ status: "error",
11636
+ code: "invalid-args",
11637
+ message: `${built.reason} Use the ${built.suggestedTool} tool instead.`
11638
+ };
11639
+ }
11640
+ return {
11641
+ status: "error",
11642
+ code: "invalid-args",
11643
+ message: built.message
11644
+ };
11645
+ }
11646
+
11647
+ /**
11648
+ * File operations are refused rather than half-supported.
11649
+ *
11650
+ * A `file` op carries binary content that has to be uploaded before the patch
11651
+ * is synced — a two-phase flow this pass does not implement. Letting one through
11652
+ * would store a patch referring to bytes that were never uploaded, which fails
11653
+ * later and a long way from the cause.
11654
+ *
11655
+ * Takes the unparsed patch, so this answer does not depend on the op being
11656
+ * otherwise well formed. All it needs is the caller's own claim about what the
11657
+ * op is.
11658
+ */
11659
+ function rejectFileOps(patch) {
11660
+ const hasFileOp = patch.some(op => typeof op === "object" && op !== null && "op" in op && op.op === "file");
11661
+ if (!hasFileOp) {
11662
+ return null;
11663
+ }
11664
+ return {
11665
+ status: "error",
11666
+ code: "unsupported",
11667
+ message: "This patch contains a file operation. Uploading files is not supported over MCP yet — only text and JSON values can be changed."
11668
+ };
11669
+ }
11670
+
11671
+ /**
11672
+ * The public surface of Val's server-side tool registry.
11673
+ *
11674
+ * Types only, deliberately: this file is the contract that the MCP hosts, the
11675
+ * CLI's stdio transport and the tools themselves are all written against, and
11676
+ * keeping it free of implementation means those can be built in any order
11677
+ * without one of them owning the shape.
11678
+ *
11679
+ * The design this implements is `docs/plans/mcp.md`, Part A. Two constraints
11680
+ * from it are load-bearing and easy to break by accident:
11681
+ *
11682
+ * 1. **Nothing here may import an MCP SDK.** That is what lets hosts other
11683
+ * than the template consume these tools, and it is not hypothetical
11684
+ * hygiene — the TypeScript SDK reorganised itself at v2.0.0, and a registry
11685
+ * coupled to it would have moved with it.
11686
+ * 2. **The result type is deliberately not MCP's `CallToolResult`.** Each host
11687
+ * adapts {@link ValToolResult} at its own edge, which is also where an
11688
+ * error becomes an in-band `isError` result the model can recover from
11689
+ * rather than a transport failure.
11690
+ */
11691
+
11692
+ /** Why a tool call failed, in a form a host can map onto its own errors. */
11693
+
11694
+ /**
11695
+ * The same definition with `inputSchema` as JSON Schema, for hosts that want the
11696
+ * wire shape rather than a Standard Schema.
11697
+ *
11698
+ * Typed as whatever zod's own converter produces, so deriving it needs no cast
11699
+ * and no second hand-written description of the same input.
11700
+ */
11701
+
11702
+ /**
11703
+ * How the caller was established, and it is a union because there are two
11704
+ * genuinely different answers — with different consequences downstream.
11705
+ *
11706
+ * The distinction that matters is **who checked**. A PAT is forwarded to the
11707
+ * backend unchecked, because the app cannot resolve one; an access token is
11708
+ * verified by the app itself, against a public key it does not hold and
11709
+ * therefore cannot forge. The first is a credential being relayed. The second
11710
+ * is a signature that has already been checked.
11711
+ */
11712
+
11713
+ /**
11714
+ * Who is calling, established once per request by the host.
11715
+ *
11716
+ * `null` means local fs mode, where there is no credential to hold and patches
11717
+ * are written with no author, exactly as the Studio does locally (D.1). In
11718
+ * proxy mode `null` is refused rather than falling back to the app's own API
11719
+ * key: that key can do more than any single user, and quietly substituting it
11720
+ * would turn a missing credential into full access.
11721
+ */
11722
+
11723
+ /**
11724
+ * Brand a verified subject as an {@link AuthorId}.
11725
+ *
11726
+ * `AuthorId` is a branded string so that an id cannot be conjured from any
11727
+ * string that happens to be lying around — which is exactly the mistake this
11728
+ * type is guarding against. That makes one assertion unavoidable at the boundary
11729
+ * where a real id enters the system, so it lives here, once, with a name that
11730
+ * says what makes it legitimate: the caller has *verified* this subject, not
11731
+ * received it.
11732
+ *
11733
+ * Do not reach for this to satisfy a type. If you are holding a string you did
11734
+ * not verify, the honest value is `null`.
11735
+ */
11736
+ function authorIdFromVerifiedSubject(subject) {
11737
+ return subject;
11738
+ }
11739
+
11740
+ /** Read access. Every call needs it, the writes included. */
11741
+ const VAL_SCOPE_READ = "val:read";
11742
+ /** Write access. Needed *in addition* by any tool not marked `readOnlyHint`. */
11743
+ const VAL_SCOPE_WRITE = "val:write";
11744
+
11745
+ /**
11746
+ * How many callers' data layers to keep around in proxy mode.
11747
+ *
11748
+ * Each entry holds one `ValOpsHttp`, and each of those caches the project's
11749
+ * evaluated modules once `initSources` has run — so this bounds memory, not just
11750
+ * entry count. Small on purpose: the cost of a miss is re-evaluating the
11751
+ * modules on the next call, which is what happened on *every* call before this
11752
+ * cache existed.
11753
+ */
11754
+ const MAX_CACHED_OPS = 8;
11755
+
11756
+ /**
11757
+ * Val's server-side tool registry.
11758
+ *
11759
+ * This is the piece Val did not have: the Studio's chat tools are defined *and
11760
+ * executed in the browser*, against its client stores, so nothing here could be
11761
+ * re-exposed. These tools run against {@link ValOps} instead, which is what lets
11762
+ * an MCP server — or a stdio transport, or anything else — drive Val content
11763
+ * without a browser.
11764
+ *
11765
+ * Transport-agnostic on purpose: nothing under `tools/` imports an MCP SDK. A
11766
+ * host adapts {@link ValToolResult} at its own edge.
11767
+ */
11768
+ function createValTools(valModules, options) {
11769
+ const resolveOps = createOpsResolver(valModules, options);
11770
+ const tools = [...readTools(), ...writeTools()];
11771
+ const byName = new Map(tools.map(tool => [tool.name, tool]));
11772
+ return {
11773
+ list() {
11774
+ return tools.map(({
11775
+ handler: _handler,
11776
+ ...definition
11777
+ }) => definition);
11778
+ },
11779
+ listJsonSchema() {
11780
+ return tools.map(({
11781
+ handler: _handler,
11782
+ inputSchema,
11783
+ ...rest
11784
+ }) => ({
11785
+ ...rest,
11786
+ // zod 4 derives this itself, so there is no JSON-Schema-to-zod
11787
+ // converter anywhere in the stack and no second description of the
11788
+ // same input to keep in step.
11789
+ inputSchema: z.toJSONSchema(inputSchema, {
11790
+ io: "input"
11791
+ })
11792
+ }));
11793
+ },
11794
+ async call(name, args, ctx) {
11795
+ const tool = byName.get(name);
11796
+ if (!tool) {
11797
+ return {
11798
+ status: "error",
11799
+ code: "unknown-tool",
11800
+ message: `No tool named ${JSON.stringify(name)}. Available: ${tools.map(t => t.name).join(", ")}`
11801
+ };
11802
+ }
11803
+ const parsed = tool.inputSchema.safeParse(args ?? {});
11804
+ if (!parsed.success) {
11805
+ return {
11806
+ status: "error",
11807
+ code: "invalid-args",
11808
+ message: describeZodError(parsed.error)
11809
+ };
11810
+ }
11811
+ const insufficient = refuseInsufficientScope(tool, ctx);
11812
+ if (insufficient) {
11813
+ return insufficient;
11814
+ }
11815
+ const resolved = resolveOps(ctx);
11816
+ if (resolved.status === "error") {
11817
+ return resolved.result;
11818
+ }
11819
+ const ops = resolved.ops;
11820
+ try {
11821
+ const state = await loadState(ops);
11822
+ if (state.status === "error") {
11823
+ return state.result;
11824
+ }
11825
+ const deps = {
11826
+ ops,
11827
+ ctx,
11828
+ state: state.state
11829
+ };
11830
+ return await tool.handler(parsed.data, deps);
11831
+ } catch (error) {
11832
+ // A thrown error here is a bug or an unreachable backend, not something
11833
+ // the model can act on — but it still comes back in-band so the client
11834
+ // sees a tool failure rather than a dead transport.
11835
+ return {
11836
+ status: "error",
11837
+ code: "internal",
11838
+ message: error instanceof Error ? error.message : String(error)
11839
+ };
11840
+ }
11841
+ },
11842
+ async dispose() {
11843
+ // Nothing to release today: ValOps holds no handle that needs closing, and
11844
+ // the fs watcher it can start is owned by the Studio's server. Kept in the
11845
+ // contract so hosts wire up teardown now rather than when it starts to
11846
+ // matter.
11847
+ }
11848
+ };
11849
+ }
11850
+
11851
+ /**
11852
+ * Pick the data layer for a call, which in proxy mode means picking whose
11853
+ * credential the backend will see.
11854
+ *
11855
+ * This is the one place authorization is decided, and it decides it by *not*
11856
+ * deciding: in proxy mode the caller's own personal access token goes to the
11857
+ * backend, which is the only party that can say what that token may do. The app
11858
+ * never inspects it, never caches a verdict about it, and never substitutes its
11859
+ * own API key for a missing one — see `docs/plans/mcp.md` D.2.
11860
+ *
11861
+ * The alternative shape, and the reason this function exists at all, is an
11862
+ * `authenticate()` that checks the PAT once and then acts under the app's key.
11863
+ * That reads as more secure and is strictly less so: the check happens in the
11864
+ * app, so every bug in it becomes full access to every project the app's key
11865
+ * can reach, and the backend's own permission model stops being consulted (D.6).
11866
+ */
11867
+ function createOpsResolver(valModules, options) {
11868
+ if (options.mode === "fs") {
11869
+ // One instance, built once: fs mode is a developer's own working tree, so
11870
+ // there is no credential to vary by and no reason to re-evaluate modules.
11871
+ const ops = createValOps(valModules, options);
11872
+ return ctx => {
11873
+ if (ctx.auth) {
11874
+ // Refused rather than ignored. A host that thinks it is passing a
11875
+ // credential should not silently get local filesystem access instead —
11876
+ // and the difference matters, because fs mode writes straight to disk
11877
+ // with no backend permission check at all.
11878
+ return {
11879
+ status: "error",
11880
+ result: {
11881
+ status: "error",
11882
+ code: "unsupported",
11883
+ message: "This Val project is running in local filesystem mode, where there is nothing to authenticate against. Do not send a credential."
11884
+ }
11885
+ };
11886
+ }
11887
+ return {
11888
+ status: "ok",
11889
+ ops
11890
+ };
11891
+ };
11892
+ }
11893
+
11894
+ // Keyed by a hash of the PAT, so the same caller reuses their own instance and
11895
+ // two callers can never share one. Hashing is not a security boundary — the
11896
+ // instance holds the token regardless — but it keeps credentials out of the
11897
+ // key set, which is the thing that ends up in a heap dump or an error dump.
11898
+ const byPatHash = new Map();
11899
+ /**
11900
+ * One instance for every verified caller, and unlike the PAT map that is
11901
+ * correct rather than a shortcut: this instance authenticates with the app's
11902
+ * own API key, so there is nothing per-caller in it to keep apart. Who did
11903
+ * what travels as the patch's `authorId` instead — see `writePath`.
11904
+ */
11905
+ let sharedOps = null;
11906
+ return ctx => {
11907
+ if (!ctx.auth) {
11908
+ return {
11909
+ status: "error",
11910
+ result: {
11911
+ status: "error",
11912
+ code: "forbidden",
11913
+ message: "This Val project talks to the Val content backend, so every call needs a credential: an access token from the Val authorization server, or the caller's own personal access token from `val login`."
11914
+ }
11915
+ };
11916
+ }
11917
+ if (ctx.auth.type === "verified-profile") {
11918
+ if (!options.apiKey) {
11919
+ // Proxy mode is inferred from the api key being present, so this is
11920
+ // unreachable through `initHandlerOptions`. It stays because the
11921
+ // alternative to refusing is building ops with no credential at all.
11922
+ return {
11923
+ status: "error",
11924
+ result: {
11925
+ status: "error",
11926
+ code: "forbidden",
11927
+ message: "This Val project has no API key configured, so a verified access token cannot be exchanged for backend access."
11928
+ }
11929
+ };
11930
+ }
11931
+ if (!sharedOps) {
11932
+ sharedOps = createValOps(valModules, options);
11933
+ }
11934
+ return {
11935
+ status: "ok",
11936
+ ops: sharedOps
11937
+ };
11938
+ }
11939
+ const key = createHash("sha256").update(ctx.auth.pat).digest("hex");
11940
+ const cached = byPatHash.get(key);
11941
+ if (cached) {
11942
+ // Re-inserted so eviction drops the least recently used rather than the
11943
+ // oldest — a long-running caller should not be evicted by a burst of
11944
+ // one-off ones.
11945
+ byPatHash.delete(key);
11946
+ byPatHash.set(key, cached);
11947
+ return {
11948
+ status: "ok",
11949
+ ops: cached
11950
+ };
11951
+ }
11952
+ const ops = createValOps(valModules, options, {
11953
+ pat: ctx.auth.pat
11954
+ });
11955
+ byPatHash.set(key, ops);
11956
+ while (byPatHash.size > MAX_CACHED_OPS) {
11957
+ const oldest = byPatHash.keys().next();
11958
+ if (oldest.done) {
11959
+ break;
11960
+ }
11961
+ byPatHash.delete(oldest.value);
11962
+ }
11963
+ return {
11964
+ status: "ok",
11965
+ ops
11966
+ };
11967
+ };
11968
+ }
11969
+ /**
11970
+ * The content as the caller should see it, loaded once per call.
11971
+ *
11972
+ * Pending patches are applied, because an agent looking at a project mid-edit
11973
+ * should see what the Studio would show rather than the last published state.
11974
+ *
11975
+ * Deliberately not cached across calls. In fs mode a save recomputes the base
11976
+ * sha within the same process, so a cached view would go stale silently — and
11977
+ * the cost of being wrong here is an agent writing a patch against content that
11978
+ * has already moved.
11979
+ */
11980
+ async function loadState(ops) {
11981
+ const patches = await ops.fetchPatches({
11982
+ excludePatchOps: false
11983
+ });
11984
+ // fetchPatches resolves with its failures on the result rather than rejecting,
11985
+ // so not checking these reads as "no pending changes" — which would quietly
11986
+ // hand back published content and let a write be based on it.
11987
+ if (patches.unauthorized) {
11988
+ return {
11989
+ status: "error",
11990
+ result: {
11991
+ status: "error",
11992
+ code: "forbidden",
11993
+ message: "Not authorized to read this project's pending changes. Check that the credential is valid and has access."
11994
+ }
11995
+ };
11996
+ }
11997
+ if (patches.networkError) {
11998
+ return {
11999
+ status: "error",
12000
+ result: {
12001
+ status: "error",
12002
+ code: "internal",
12003
+ message: "Could not reach the Val content backend."
12004
+ }
12005
+ };
12006
+ }
12007
+ if (patches.error) {
12008
+ return {
12009
+ status: "error",
12010
+ result: {
12011
+ status: "error",
12012
+ code: "internal",
12013
+ message: patches.error.message
12014
+ }
12015
+ };
12016
+ }
12017
+ const analysis = ops.analyzePatches(patches.patches);
12018
+ // getSourcesWithPatchesApplied, not getSources(analysis): the latter returns
12019
+ // only the modules that had patches, and validating that subset reports
12020
+ // spurious errors for anything that looks across modules, like keyOf or a
12021
+ // router.
12022
+ const sourcesRes = await ops.getSourcesWithPatchesApplied({
12023
+ ...analysis,
12024
+ ...patches
12025
+ });
12026
+ const [schemas, serializedSchemas] = await Promise.all([ops.getSchemas(), ops.getSerializedSchemas()]);
12027
+ return {
12028
+ status: "ok",
12029
+ state: {
12030
+ schemas,
12031
+ serializedSchemas,
12032
+ sources: sourcesRes.sources,
12033
+ patches,
12034
+ analysis,
12035
+ // Which modules hold a pending patch that would not apply. Carried rather
12036
+ // than discarded because their `sources` silently lack that change: the
12037
+ // content here is not what publishing would produce, so a write against
12038
+ // it would be based on a state that does not exist. See
12039
+ // `unappliedPatchesFor`.
12040
+ unappliedPatches: sourcesRes.errors
12041
+ }
12042
+ };
12043
+ }
12044
+ function describeZodError(error) {
12045
+ return error.issues.map(issue => {
12046
+ const path = issue.path.join(".");
12047
+ return path ? `${path}: ${issue.message}` : issue.message;
12048
+ }).join("; ");
12049
+ }
12050
+
12051
+ /**
12052
+ * Refuse a call the token was not granted, before anything is attempted.
12053
+ *
12054
+ * Derived from `readOnlyHint` rather than from a second list of tool names,
12055
+ * because a second list is a thing that drifts. The derivation also fails in
12056
+ * the safe direction: a tool that forgets the hint is treated as a write and
12057
+ * demands the wider scope, rather than a write slipping through as a read.
12058
+ *
12059
+ * Only the verified-token path is checked. A PAT carries no scopes here by
12060
+ * design — the backend resolves it and decides — so there is nothing to
12061
+ * enforce, and inventing a default would be this app claiming an authority it
12062
+ * does not have.
12063
+ */
12064
+ function refuseInsufficientScope(tool, ctx) {
12065
+ var _ctx$auth, _tool$annotations;
12066
+ if (((_ctx$auth = ctx.auth) === null || _ctx$auth === void 0 ? void 0 : _ctx$auth.type) !== "verified-profile") {
12067
+ return null;
12068
+ }
12069
+ // Read is needed by every call, including the writes: a tool that changes
12070
+ // content reads it first, and `ValToolAuth` says as much. Checking only the
12071
+ // wider scope would let a write-but-not-read token through here — today's
12072
+ // verifier refuses such a token before this point, but `createValTools` is
12073
+ // exported and another host may not.
12074
+ const needed = (_tool$annotations = tool.annotations) !== null && _tool$annotations !== void 0 && _tool$annotations.readOnlyHint ? [VAL_SCOPE_READ] : [VAL_SCOPE_READ, VAL_SCOPE_WRITE];
12075
+ const granted = ctx.auth.scopes;
12076
+ const missing = needed.filter(scope => !granted.includes(scope));
12077
+ if (missing.length === 0) {
12078
+ return null;
12079
+ }
12080
+ return {
12081
+ status: "error",
12082
+ code: "forbidden",
12083
+ message: `This access token does not have the ${missing.join(" and ")} scope, which ${tool.name} requires. Granted: ${granted.length > 0 ? granted.join(" ") : "(none)"}.`
12084
+ };
12085
+ }
12086
+
10747
12087
  const JsFileLookupMapping = [
10748
12088
  // NOTE: first one matching will be used
10749
12089
  [".cjs.d.ts", [".esm.js", ".mjs.js"]], [".cjs.js", [".esm.js", ".mjs.js"]], [".cjs", [".mjs"]], [".d.ts", [".js", ".esm.js", ".mjs.js"]]];
@@ -12923,4 +14263,4 @@ function readCapturedReport(snapshotDir) {
12923
14263
  return JSON.parse(fs.readFileSync(reportPath, "utf-8"));
12924
14264
  }
12925
14265
 
12926
- export { DEFAULT_LOGIN_EXPIRES_IN_SECONDS, DEFAULT_LOGIN_HOST, DEFAULT_LOGIN_POLL_INTERVAL_SECONDS, Service, ValFSHost, ValLoginError, ValModuleLoader, ValOpsFS, ValOpsHttp, ValSourceFileHandler, analyzeValModule, awaitValLoginConfirmation, checkRemoteRef, classifyJsonValuesOp, compareWithCapturedReport, createDefaultValFSHost, createFixPatch, createJsonEntryPathMap, createModulePathMap, createService, createValApiRouter, createValModuleFileInspector, createValServer, currentFixHandlers, decodeJwtWithoutVerifying, describePatchStoreProblems, downloadFileFromRemote, encodeJwt, evalValConfigFile, extractFileMetadata, extractImageMetadata, extractJsonValuesEntry, findAndEvalValConfigFile, findJsonEntryFilePath, fixHandlers, formatPatchSourceError, formatSyntaxErrorTree, getCachedRemoteFileDir, getCachedRemoteFilePath, getCompilerOptions, getExpire, getFileExt, getModulePathRange, getPersonalAccessTokenPath, getSettings, getValidationErrorFileRef, handleCheckAllFiles, handleFileMetadata, handleJsonValuesExtractEntry, handleRemoteFileCheck, handleRemoteFileDownload, handleRemoteFileUpload, handleRemoteGalleryFileUpload, handleUniqueFolderCheck, loadValModules, parsePersonalAccessTokenFile, patchSourceFile, persistPersonalAccessToken, readCapturedReport, readPatchStore, rebaseContentOp, replaySnapshot, safeReadGit, startValLogin, uploadRemoteFile, validateMetadata, verifyJwt };
14266
+ export { DEFAULT_LOGIN_EXPIRES_IN_SECONDS, DEFAULT_LOGIN_HOST, DEFAULT_LOGIN_POLL_INTERVAL_SECONDS, Service, VAL_SCOPE_READ, VAL_SCOPE_WRITE, ValFSHost, ValLoginError, ValModuleLoader, ValOpsFS, ValOpsHttp, ValSourceFileHandler, analyzeValModule, authorIdFromVerifiedSubject, awaitValLoginConfirmation, checkRemoteRef, classifyJsonValuesOp, compareWithCapturedReport, createDefaultValFSHost, createFixPatch, createJsonEntryPathMap, createModulePathMap, createService, createValApiRouter, createValModuleFileInspector, createValOps, createValServer, createValTools, currentFixHandlers, decodeJwtWithoutVerifying, describePatchStoreProblems, downloadFileFromRemote, encodeJwt, evalValConfigFile, extractFileMetadata, extractImageMetadata, extractJsonValuesEntry, findAndEvalValConfigFile, findJsonEntryFilePath, fixHandlers, formatPatchSourceError, formatSyntaxErrorTree, getCachedRemoteFileDir, getCachedRemoteFilePath, getCompilerOptions, getExpire, getFileExt, getModulePathRange, getPersonalAccessTokenPath, getSettings, getValidationErrorFileRef, handleCheckAllFiles, handleFileMetadata, handleJsonValuesExtractEntry, handleRemoteFileCheck, handleRemoteFileDownload, handleRemoteFileUpload, handleRemoteGalleryFileUpload, handleUniqueFolderCheck, initHandlerOptions, loadValModules, parsePersonalAccessTokenFile, patchSourceFile, persistPersonalAccessToken, readCapturedReport, readPatchStore, rebaseContentOp, replaySnapshot, safeReadGit, startValLogin, uploadRemoteFile, validateMetadata, verifyJwt };