@valbuild/server 0.114.0 → 0.116.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.
@@ -17,6 +17,7 @@ var z = require('zod');
17
17
  var sizeOf = require('image-size');
18
18
  var zodValidationError = require('zod-validation-error');
19
19
  var os = require('os');
20
+ var node_crypto = require('node:crypto');
20
21
  var sucrase = require('sucrase');
21
22
  var http = require('http');
22
23
  var https = require('https');
@@ -1040,7 +1041,7 @@ function errorMessage(e) {
1040
1041
  return String(e);
1041
1042
  }
1042
1043
 
1043
- const jsonOps$2 = new patch.JSONOps();
1044
+ const jsonOps$3 = new patch.JSONOps();
1044
1045
 
1045
1046
  /**
1046
1047
  * Classification of a single patch op against a module's serialized schema,
@@ -1295,7 +1296,7 @@ function applyJsonValuesEntryPatches(args) {
1295
1296
  // on an entry that does not exist.
1296
1297
  continue;
1297
1298
  }
1298
- const applied = patch.applyPatch(patch.deepClone(content), jsonOps$2, [{
1299
+ const applied = patch.applyPatch(patch.deepClone(content), jsonOps$3, [{
1299
1300
  op: "add",
1300
1301
  path: cls.subPath.concat(...(op.nestedFilePath ?? [])).concat("patch_id"),
1301
1302
  value: patchId
@@ -1349,7 +1350,7 @@ function applyJsonValuesEntryPatches(args) {
1349
1350
  patchId
1350
1351
  };
1351
1352
  }
1352
- const applied = patch.applyPatch(patch.deepClone(content), jsonOps$2, [rebased.value]);
1353
+ const applied = patch.applyPatch(patch.deepClone(content), jsonOps$3, [rebased.value]);
1353
1354
  if (fp.result.isErr(applied)) {
1354
1355
  return {
1355
1356
  kind: "error",
@@ -1632,7 +1633,7 @@ function findJsonEntryFilePath(moduleFilePath, valTsSourceFile, entryKey) {
1632
1633
  return resolveExistingJsonPath(moduleFilePath, entry.importPath);
1633
1634
  }
1634
1635
 
1635
- const jsonOps$1 = new patch.JSONOps();
1636
+ const jsonOps$2 = new patch.JSONOps();
1636
1637
 
1637
1638
  /**
1638
1639
  * Substitutes loaded `.jsonValues()` entry content back into a module's root
@@ -1923,7 +1924,7 @@ class Service {
1923
1924
  if (fp.result.isErr(rebased)) {
1924
1925
  throw Error(`Could not apply ${op.op} to jsonValues entry '${entryKey}' of ${moduleFilePath}: ${rebased.error.message}`);
1925
1926
  }
1926
- const applied = patch.applyPatch(patch.deepClone(content), jsonOps$1, [rebased.value]);
1927
+ const applied = patch.applyPatch(patch.deepClone(content), jsonOps$2, [rebased.value]);
1927
1928
  if (fp.result.isErr(applied)) {
1928
1929
  throw Error(`Could not apply ${op.op} to ${jsonPath}: ${applied.error.message}`);
1929
1930
  }
@@ -2092,7 +2093,7 @@ function encodeJwt(payload, sessionKey) {
2092
2093
  }
2093
2094
 
2094
2095
  /* eslint-disable @typescript-eslint/no-unused-vars */
2095
- const jsonOps = new patch.JSONOps();
2096
+ const jsonOps$1 = new patch.JSONOps();
2096
2097
  const tsOps = new TSOps(document => {
2097
2098
  return fp.pipe(analyzeValModule(document), fp.result.map(({
2098
2099
  source
@@ -2861,7 +2862,7 @@ class ValOps {
2861
2862
  }
2862
2863
  const patchRes = patch.applyPatch(patch.deepClone(patchedSources[path]),
2863
2864
  // 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?
2864
- jsonOps, applicableOps.concat(...Object.values(fileFixOps)));
2865
+ jsonOps$1, applicableOps.concat(...Object.values(fileFixOps)));
2865
2866
  if (fp.result.isErr(patchRes)) {
2866
2867
  console.error("Could not apply patch", JSON.stringify({
2867
2868
  path,
@@ -3561,7 +3562,7 @@ class ValOps {
3561
3562
  patchHadError = true;
3562
3563
  break;
3563
3564
  }
3564
- const applied = patch.applyPatch(patch.deepClone(contentRes.value), jsonOps, [rebasedRes.value]);
3565
+ const applied = patch.applyPatch(patch.deepClone(contentRes.value), jsonOps$1, [rebasedRes.value]);
3565
3566
  if (fp.result.isErr(applied)) {
3566
3567
  collectPatchError(applied.error, patchId, op);
3567
3568
  patchHadError = true;
@@ -7467,6 +7468,227 @@ async function getSettings(projectName, auth) {
7467
7468
  }
7468
7469
  }
7469
7470
 
7471
+ /**
7472
+ * Resolving how Val is configured, and building the data layer from it.
7473
+ *
7474
+ * Both live here rather than inside `createValApiRouter` because the MCP tool
7475
+ * registry needs exactly the same answers: which mode we are in, which
7476
+ * credential to use, and which `ValOps` implementation that implies. Two copies
7477
+ * of this would drift, and the failure would be quiet — a registry that decides
7478
+ * it is in fs mode while the Studio decides it is in proxy mode reads different
7479
+ * content from the same project.
7480
+ *
7481
+ * The type-only import from `./ValRouter` is deliberate: it keeps `ValApiOptions`
7482
+ * where its documentation lives without creating a runtime cycle.
7483
+ *
7484
+ * The credential-bearing URL check at the bottom of this file lives here for the
7485
+ * same reason: it is a check on the URLs `initHandlerOptions` resolves, and its
7486
+ * only caller is that function. Leaving it in `./ValRouter` would have meant
7487
+ * importing it back from there, which is the runtime cycle the paragraph above
7488
+ * exists to avoid.
7489
+ */
7490
+
7491
+ const DEFAULT_VAL_BUILD_URL = "https://admin.val.build";
7492
+
7493
+ /**
7494
+ * Resolve options plus environment into a concrete {@link ValServerConfig}.
7495
+ *
7496
+ * Moved verbatim out of `createValApiRouter`; the precedence rules are load
7497
+ * bearing, so this is the one place they are written down. Note that "proxy"
7498
+ * mode is inferred when `VAL_API_KEY` or `VAL_SECRET` is present and no mode was
7499
+ * given, which is why a project can be pushed into proxy mode by setting an env
7500
+ * var alone.
7501
+ */
7502
+ async function initHandlerOptions(route, opts, config) {
7503
+ const maybeApiKey = opts.apiKey || process.env.VAL_API_KEY;
7504
+ const maybeValSecret = opts.valSecret || process.env.VAL_SECRET;
7505
+ const isProxyMode = opts.mode === "proxy" || opts.mode === undefined && (maybeApiKey || maybeValSecret);
7506
+ const valEnableRedirectUrl = opts.valEnableRedirectUrl || process.env.VAL_ENABLE_REDIRECT_URL;
7507
+ const valDisableRedirectUrl = opts.valDisableRedirectUrl || process.env.VAL_DISABLE_REDIRECT_URL;
7508
+ const maybeValProject = opts.project || process.env.VAL_PROJECT;
7509
+ const valBuildUrl = opts.valBuildUrl || process.env.VAL_BUILD_URL || DEFAULT_VAL_BUILD_URL;
7510
+ const valContentUrl = opts.valContentUrl || process.env.VAL_CONTENT_URL || core.DEFAULT_CONTENT_HOST;
7511
+ warnIfInsecureUrls({
7512
+ valBuildUrl,
7513
+ valContentUrl
7514
+ });
7515
+ if (isProxyMode) {
7516
+ var _opts$versions, _opts$versions2;
7517
+ if (!maybeApiKey || !maybeValSecret) {
7518
+ throw new Error("VAL_API_KEY and VAL_SECRET env vars must both be set in proxy mode");
7519
+ }
7520
+ const maybeGitCommit = opts.gitCommit || process.env.VAL_GIT_COMMIT;
7521
+ if (!maybeGitCommit) {
7522
+ throw new Error("VAL_GIT_COMMIT env var must be set in proxy mode");
7523
+ }
7524
+ const maybeGitBranch = opts.gitBranch || process.env.VAL_GIT_BRANCH;
7525
+ if (!maybeGitBranch) {
7526
+ throw new Error("VAL_GIT_BRANCH env var must be set in proxy mode");
7527
+ }
7528
+ if (!maybeValProject) {
7529
+ 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.");
7530
+ }
7531
+ const coreVersion = (_opts$versions = opts.versions) === null || _opts$versions === void 0 ? void 0 : _opts$versions.core;
7532
+ if (!coreVersion) {
7533
+ throw new Error("Could not determine version of @valbuild/core");
7534
+ }
7535
+ const nextVersion = (_opts$versions2 = opts.versions) === null || _opts$versions2 === void 0 ? void 0 : _opts$versions2.next;
7536
+ if (!nextVersion) {
7537
+ throw new Error("Could not determine version of @valbuild/next");
7538
+ }
7539
+ return {
7540
+ mode: "http",
7541
+ route,
7542
+ apiKey: maybeApiKey,
7543
+ valSecret: maybeValSecret,
7544
+ commit: maybeGitCommit,
7545
+ branch: maybeGitBranch,
7546
+ root: opts.root,
7547
+ project: maybeValProject,
7548
+ valEnableRedirectUrl,
7549
+ valDisableRedirectUrl,
7550
+ valContentUrl,
7551
+ valBuildUrl,
7552
+ config
7553
+ };
7554
+ } else {
7555
+ const cwd = process.cwd();
7556
+ const valBuildUrl = opts.valBuildUrl || process.env.VAL_BUILD_URL || DEFAULT_VAL_BUILD_URL;
7557
+ return {
7558
+ mode: "fs",
7559
+ cwd,
7560
+ route,
7561
+ valDisableRedirectUrl,
7562
+ valEnableRedirectUrl,
7563
+ valBuildUrl,
7564
+ valContentUrl,
7565
+ apiKey: maybeApiKey,
7566
+ valSecret: maybeValSecret,
7567
+ project: maybeValProject,
7568
+ config
7569
+ };
7570
+ }
7571
+ }
7572
+
7573
+ /**
7574
+ * Build the data layer a {@link ValServerConfig} calls for.
7575
+ *
7576
+ * `auth` decides *whose* credential the http backend sees. Left out, it is the
7577
+ * app's own API key — which is what the Studio wants, because there the app has
7578
+ * already verified a session cookie and is acting on the user's behalf under its
7579
+ * own authority.
7580
+ *
7581
+ * A caller acting for a user it has *not* authenticated itself must pass that
7582
+ * user's personal access token instead, so the backend is the one that decides
7583
+ * what the caller may do. That is the whole of `docs/plans/mcp.md` D.2: the app
7584
+ * stops being an authority and goes back to being a pipe. Passing the app's API
7585
+ * key on such a request is the D.6 confused deputy, and it is worth being blunt
7586
+ * about why it is tempting — it works, and it works for every project the key
7587
+ * can reach, including the ones the caller cannot.
7588
+ */
7589
+ function createValOps(valModules, options, auth) {
7590
+ if (options.mode === "fs") {
7591
+ // No credential in fs mode: this reads and writes the developer's own
7592
+ // working tree, and there is no backend to authenticate to. A PAT handed in
7593
+ // here is not ignored quietly — the caller is told, in createValTools.
7594
+ return new ValOpsFS(options.valContentUrl, options.cwd, valModules, {
7595
+ formatter: options.formatter,
7596
+ config: options.config
7597
+ });
7598
+ }
7599
+ if (options.mode === "http") {
7600
+ return new ValOpsHttp(options.valContentUrl, options.project, options.commit, options.branch, auth ?? {
7601
+ apiKey: options.apiKey
7602
+ }, valModules, {
7603
+ formatter: options.formatter,
7604
+ root: options.root,
7605
+ config: options.config
7606
+ });
7607
+ }
7608
+ throw new Error(
7609
+ // The union is exhausted above; this catches a config that came from
7610
+ // somewhere untyped.
7611
+ "Invalid mode: " + (options === null || options === void 0 ? void 0 : options.mode));
7612
+ }
7613
+
7614
+ /**
7615
+ * Hosts we send credentials to, and what each one puts at risk. They differ:
7616
+ * only `valBuildUrl` hands back the app token that becomes the session cookie,
7617
+ * so a single shared sentence would overstate one and understate the other.
7618
+ */
7619
+
7620
+ const CREDENTIAL_BEARING_URLS = ["valBuildUrl", "valContentUrl"];
7621
+ const WHAT_IS_AT_RISK = {
7622
+ 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.",
7623
+ 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."
7624
+ };
7625
+
7626
+ // NOTE: `URL.hostname` keeps the brackets on an IPv6 literal, so this is
7627
+ // "[::1]" and not "::1" - and `http://[0:0:0:0:0:0:0:1]` normalises to the
7628
+ // same short form before it gets here. Dropping the brackets looks like a
7629
+ // tidy-up and silently stops matching IPv6 loopback.
7630
+ const LOOPBACK_HOSTNAMES = ["localhost", "127.0.0.1", "[::1]"];
7631
+
7632
+ /**
7633
+ * The URL as it is safe to print. `http://user:pass@host` is a legal override,
7634
+ * and a warning about credential exposure that puts the password in the log
7635
+ * would be the very thing it is warning about.
7636
+ */
7637
+ function forLog(parsed) {
7638
+ if (!parsed.username && !parsed.password) {
7639
+ return parsed.href;
7640
+ }
7641
+ const redacted = new URL(parsed.href);
7642
+ redacted.username = "";
7643
+ redacted.password = "";
7644
+ return `${redacted.href} (credentials redacted)`;
7645
+ }
7646
+
7647
+ /**
7648
+ * Returns a warning if `url` would send credentials somewhere they can be read
7649
+ * off the wire, or null if it is fine.
7650
+ *
7651
+ * Both URLs default to https, but each is overridable - `opts.valBuildUrl` /
7652
+ * `VAL_BUILD_URL`, `opts.valContentUrl` / `VAL_CONTENT_URL` - and neither
7653
+ * override has ever been scheme-checked. Point one at a plain http host and the
7654
+ * api key goes out in clear text, and whatever comes back is whatever the
7655
+ * network says: for `valBuildUrl` that includes the app token this server
7656
+ * re-signs into the session cookie.
7657
+ *
7658
+ * Loopback over http is exempt: that is a val.build running on the developer's
7659
+ * own machine, and there is no network to be on the wrong side of.
7660
+ *
7661
+ * This warns rather than throws. Both overrides are set by the operator, not by
7662
+ * an attacker, so this is a misconfiguration to surface - not untrusted input to
7663
+ * reject - and refusing to boot would break anyone deliberately pointing at an
7664
+ * internal http host today.
7665
+ */
7666
+ function insecureUrlWarning(name, url) {
7667
+ let parsed;
7668
+ try {
7669
+ parsed = new URL(url);
7670
+ } catch {
7671
+ // NOTE: the URL is not echoed here. It did not parse, so there is nothing
7672
+ // to redact with, and an unparseable string can still hold a password.
7673
+ return `Val: ${name} is not a valid URL.`;
7674
+ }
7675
+ if (parsed.protocol === "https:") {
7676
+ return null;
7677
+ }
7678
+ if (parsed.protocol === "http:" && (LOOPBACK_HOSTNAMES.includes(parsed.hostname) || parsed.hostname.endsWith(".localhost"))) {
7679
+ return null;
7680
+ }
7681
+ 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.`;
7682
+ }
7683
+ function warnIfInsecureUrls(urls) {
7684
+ for (const name of CREDENTIAL_BEARING_URLS) {
7685
+ const warning = insecureUrlWarning(name, urls[name]);
7686
+ if (warning) {
7687
+ console.warn(warning);
7688
+ }
7689
+ }
7690
+ }
7691
+
7470
7692
  function getPersonalAccessTokenPath(root) {
7471
7693
  return path__namespace["default"].join(path__namespace["default"].resolve(root), ".val", "pat.json");
7472
7694
  }
@@ -7540,24 +7762,7 @@ const ValServer = (valModules, options, callbacks) => {
7540
7762
  }).nullable()
7541
7763
  }))
7542
7764
  });
7543
- let serverOps;
7544
- if (options.mode === "fs") {
7545
- serverOps = new ValOpsFS(options.valContentUrl, options.cwd, valModules, {
7546
- formatter: options.formatter,
7547
- config: options.config
7548
- });
7549
- } else if (options.mode === "http") {
7550
- serverOps = new ValOpsHttp(options.valContentUrl, options.project, options.commit, options.branch, {
7551
- apiKey: options.apiKey
7552
- }, valModules, {
7553
- formatter: options.formatter,
7554
- root: options.root,
7555
- config: options.config
7556
- });
7557
- } else {
7558
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7559
- throw new Error("Invalid mode: " + (options === null || options === void 0 ? void 0 : options.mode));
7560
- }
7765
+ const serverOps = createValOps(valModules, options);
7561
7766
  const getAuthorizeUrl = (publicValApiRe, token) => {
7562
7767
  if (!options.project) {
7563
7768
  throw new Error("Project is not set");
@@ -10338,72 +10543,6 @@ async function createValServer(valModules, route, opts, config, callbacks, forma
10338
10543
  ...valServerConfig
10339
10544
  }, callbacks);
10340
10545
  }
10341
- async function initHandlerOptions(route, opts, config) {
10342
- const maybeApiKey = opts.apiKey || process.env.VAL_API_KEY;
10343
- const maybeValSecret = opts.valSecret || process.env.VAL_SECRET;
10344
- const isProxyMode = opts.mode === "proxy" || opts.mode === undefined && (maybeApiKey || maybeValSecret);
10345
- const valEnableRedirectUrl = opts.valEnableRedirectUrl || process.env.VAL_ENABLE_REDIRECT_URL;
10346
- const valDisableRedirectUrl = opts.valDisableRedirectUrl || process.env.VAL_DISABLE_REDIRECT_URL;
10347
- const maybeValProject = opts.project || process.env.VAL_PROJECT;
10348
- const valBuildUrl = opts.valBuildUrl || process.env.VAL_BUILD_URL || "https://admin.val.build";
10349
- const valContentUrl = opts.valContentUrl || process.env.VAL_CONTENT_URL || core.DEFAULT_CONTENT_HOST;
10350
- if (isProxyMode) {
10351
- var _opts$versions, _opts$versions2;
10352
- if (!maybeApiKey || !maybeValSecret) {
10353
- throw new Error("VAL_API_KEY and VAL_SECRET env vars must both be set in proxy mode");
10354
- }
10355
- const maybeGitCommit = opts.gitCommit || process.env.VAL_GIT_COMMIT;
10356
- if (!maybeGitCommit) {
10357
- throw new Error("VAL_GIT_COMMIT env var must be set in proxy mode");
10358
- }
10359
- const maybeGitBranch = opts.gitBranch || process.env.VAL_GIT_BRANCH;
10360
- if (!maybeGitBranch) {
10361
- throw new Error("VAL_GIT_BRANCH env var must be set in proxy mode");
10362
- }
10363
- if (!maybeValProject) {
10364
- 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.");
10365
- }
10366
- const coreVersion = (_opts$versions = opts.versions) === null || _opts$versions === void 0 ? void 0 : _opts$versions.core;
10367
- if (!coreVersion) {
10368
- throw new Error("Could not determine version of @valbuild/core");
10369
- }
10370
- const nextVersion = (_opts$versions2 = opts.versions) === null || _opts$versions2 === void 0 ? void 0 : _opts$versions2.next;
10371
- if (!nextVersion) {
10372
- throw new Error("Could not determine version of @valbuild/next");
10373
- }
10374
- return {
10375
- mode: "http",
10376
- route,
10377
- apiKey: maybeApiKey,
10378
- valSecret: maybeValSecret,
10379
- commit: maybeGitCommit,
10380
- branch: maybeGitBranch,
10381
- root: opts.root,
10382
- project: maybeValProject,
10383
- valEnableRedirectUrl,
10384
- valDisableRedirectUrl,
10385
- valContentUrl,
10386
- valBuildUrl,
10387
- config
10388
- };
10389
- } else {
10390
- const cwd = process.cwd();
10391
- const valBuildUrl = opts.valBuildUrl || process.env.VAL_BUILD_URL || "https://admin.val.build";
10392
- return {
10393
- mode: "fs",
10394
- cwd,
10395
- route,
10396
- valDisableRedirectUrl,
10397
- valEnableRedirectUrl,
10398
- valBuildUrl,
10399
- valContentUrl,
10400
- apiKey: maybeApiKey,
10401
- valSecret: maybeValSecret,
10402
- project: maybeValProject,
10403
- config
10404
- };
10405
- }
10406
- }
10407
10546
 
10408
10547
  // TODO: remove
10409
10548
  async function safeReadGit(cwd) {
@@ -10697,32 +10836,1159 @@ function getCookies(req, cookiesDef) {
10697
10836
  return z.z.object(cookiesDef).safeParse(input);
10698
10837
  }
10699
10838
 
10700
- const JsFileLookupMapping = [
10701
- // NOTE: first one matching will be used
10702
- [".cjs.d.ts", [".esm.js", ".mjs.js"]], [".cjs.js", [".esm.js", ".mjs.js"]], [".cjs", [".mjs"]], [".d.ts", [".js", ".esm.js", ".mjs.js"]]];
10703
- const MAX_CACHE_SIZE = 100 * 1024 * 1024; // 100 mb
10704
- const MAX_OBJECT_KEY_SIZE = 2 ** 27; // https://stackoverflow.com/questions/13367391/is-there-a-limit-on-length-of-the-key-string-in-js-object
10839
+ /**
10840
+ * How a tool is written, and what it is handed.
10841
+ *
10842
+ * Tools are defined with {@link defineTool} so that the handler's `args` are
10843
+ * inferred from the tool's own `inputSchema`. Without that the array of tools
10844
+ * would have to be typed at its widest and every handler would start by
10845
+ * re-narrowing `unknown`, which is exactly where a tool and its schema drift
10846
+ * apart unnoticed.
10847
+ */
10705
10848
 
10706
- class ValModuleLoader {
10707
- constructor(projectRoot, compilerOptions,
10708
- // TODO: remove this?
10709
- sourceFileHandler, host = {
10710
- ...ts__default["default"].sys,
10711
- writeFile: (fileName, data, encoding) => {
10712
- fs__default["default"].mkdirSync(path__namespace["default"].dirname(fileName), {
10713
- recursive: true
10714
- });
10715
- fs__default["default"].writeFileSync(fileName, typeof data === "string" ? data : new Uint8Array(data), encoding);
10716
- },
10717
- rmFile: fs__default["default"].rmSync,
10718
- readBuffer: fileName => {
10719
- try {
10720
- return fs__default["default"].readFileSync(fileName);
10721
- } catch {
10722
- return undefined;
10723
- }
10849
+ /** Everything a tool is allowed to reach. Deliberately narrow. */
10850
+
10851
+ /**
10852
+ * Declare a tool, binding its handler to its input schema.
10853
+ *
10854
+ * The handler receives already-parsed arguments: the registry validates against
10855
+ * `inputSchema` before calling, so a handler never sees input its schema would
10856
+ * have rejected.
10857
+ */
10858
+ function defineTool(definition, handler) {
10859
+ return {
10860
+ ...definition,
10861
+ handler: (args, deps) => handler(args, deps)
10862
+ };
10863
+ }
10864
+ function ok(data) {
10865
+ return {
10866
+ status: "ok",
10867
+ data
10868
+ };
10869
+ }
10870
+ function err(code, message) {
10871
+ return {
10872
+ status: "error",
10873
+ code,
10874
+ message
10875
+ };
10876
+ }
10877
+
10878
+ /**
10879
+ * The tools that only read.
10880
+ *
10881
+ * Names match the Studio's chat tools exactly. MCP clients namespace by server,
10882
+ * so there is no `val_` prefix to add, and keeping the names identical means
10883
+ * converging the two definitions later is a move rather than a rename.
10884
+ *
10885
+ * All of these read from `deps.state`, which already has pending patches
10886
+ * applied — an agent should see the content as the Studio would show it, not the
10887
+ * last published version.
10888
+ */
10889
+
10890
+ const ModuleFilePathSchema$1 = z.z.string().describe('Path of the Val module, e.g. "/content/pages.val.ts". Use get_all_schema to discover these.');
10891
+ function readTools() {
10892
+ return [defineTool({
10893
+ name: "get_all_schema",
10894
+ title: "Get all schemas",
10895
+ description: "List every Val module in the project and its schema. Start here: the module paths this returns are what every other tool takes.",
10896
+ inputSchema: z.z.object({}),
10897
+ annotations: {
10898
+ readOnlyHint: true,
10899
+ idempotentHint: true
10900
+ }
10901
+ }, async (_args, {
10902
+ state
10903
+ }) => ok(state.serializedSchemas)), defineTool({
10904
+ name: "get_source",
10905
+ title: "Get source",
10906
+ description: "Read the content of one Val module, with any unpublished changes already applied.",
10907
+ inputSchema: z.z.object({
10908
+ moduleFilePath: ModuleFilePathSchema$1
10909
+ }),
10910
+ annotations: {
10911
+ readOnlyHint: true,
10912
+ idempotentHint: true
10913
+ }
10914
+ }, async ({
10915
+ moduleFilePath
10916
+ }, {
10917
+ state
10918
+ }) => {
10919
+ const path = moduleFilePath;
10920
+ if (!(path in state.serializedSchemas)) {
10921
+ return err("not-found", unknownModuleMessage(path, state));
10922
+ }
10923
+ const source = state.sources[path];
10924
+ return ok(source === undefined ? null : source);
10925
+ }), defineTool({
10926
+ name: "get_record_keys",
10927
+ title: "Get record keys",
10928
+ 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.",
10929
+ inputSchema: z.z.object({
10930
+ moduleFilePath: ModuleFilePathSchema$1,
10931
+ path: z.z.array(z.z.string()).default([]).describe("Path within the module to the record or object. Empty means the module root."),
10932
+ // Clamped by the schema rather than in the handler: a negative offset
10933
+ // makes `slice` read from the END and a negative limit makes it drop
10934
+ // the last N, so either would return a window that is not the page
10935
+ // asked for while `total` alongside implied it was.
10936
+ limit: z.z.number().int().min(1).default(100).describe("Maximum number of keys to return."),
10937
+ offset: z.z.number().int().min(0).default(0).describe("Number of keys to skip, for paging.")
10938
+ }),
10939
+ annotations: {
10940
+ readOnlyHint: true,
10941
+ idempotentHint: true
10724
10942
  }
10725
- }, disableCache = false) {
10943
+ }, async ({
10944
+ moduleFilePath,
10945
+ path,
10946
+ limit,
10947
+ offset
10948
+ }, {
10949
+ state
10950
+ }) => {
10951
+ const described = describeContainer(state, moduleFilePath, path);
10952
+ if (described.kind !== "ok") {
10953
+ return described.result;
10954
+ }
10955
+ const {
10956
+ container,
10957
+ value
10958
+ } = described;
10959
+ // Records and objects only, matching the Studio's tool of the same name.
10960
+ // A gallery's keys are file paths whose bytes live elsewhere, and
10961
+ // richtext blocks are positional — neither is a key set to hand back.
10962
+ if (container !== "record" && container !== "object" || !isPlainObject(value)) {
10963
+ 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"}.`);
10964
+ }
10965
+ const keys = Object.keys(value);
10966
+ return ok({
10967
+ kind: container,
10968
+ keys: keys.slice(offset, offset + limit),
10969
+ // The unpaged size, so a caller can tell a short page from the end of
10970
+ // the record without asking for another one.
10971
+ total: keys.length
10972
+ });
10973
+ }), defineTool({
10974
+ name: "count_entries",
10975
+ title: "Count entries",
10976
+ 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.",
10977
+ inputSchema: z.z.object({
10978
+ moduleFilePath: ModuleFilePathSchema$1,
10979
+ path: z.z.array(z.z.string()).default([]).describe("Path within the module to count at. Empty means the module root.")
10980
+ }),
10981
+ annotations: {
10982
+ readOnlyHint: true,
10983
+ idempotentHint: true
10984
+ }
10985
+ }, async ({
10986
+ moduleFilePath,
10987
+ path
10988
+ }, {
10989
+ state
10990
+ }) => {
10991
+ const described = describeContainer(state, moduleFilePath, path);
10992
+ if (described.kind !== "ok") {
10993
+ return described.result;
10994
+ }
10995
+ const {
10996
+ container,
10997
+ value
10998
+ } = described;
10999
+ // Every container `describeContainerAtPath` admits can be counted, so
11000
+ // unlike get_record_keys this does not narrow further. Non-containers
11001
+ // never get this far.
11002
+ if (Array.isArray(value)) {
11003
+ return ok({
11004
+ kind: container,
11005
+ count: value.length
11006
+ });
11007
+ }
11008
+ if (isPlainObject(value)) {
11009
+ return ok({
11010
+ kind: container,
11011
+ count: Object.keys(value).length
11012
+ });
11013
+ }
11014
+ return err("invalid-args", `The value at that path is ${article(container)} ${container}, which has nothing to count.`);
11015
+ }), defineTool({
11016
+ name: "validate_content",
11017
+ title: "Validate content",
11018
+ description: "Check the project's content against its schemas, including unpublished changes. Returns only errors that would block publishing.",
11019
+ inputSchema: z.z.object({
11020
+ moduleFilePath: ModuleFilePathSchema$1.optional().describe("Limit the check to one module. Omit to validate everything.")
11021
+ }),
11022
+ annotations: {
11023
+ readOnlyHint: true
11024
+ }
11025
+ }, async ({
11026
+ moduleFilePath
11027
+ }, {
11028
+ ops,
11029
+ state
11030
+ }) => {
11031
+ const validation = await ops.validateSources(state.schemas, state.sources,
11032
+ // Every module. The third argument filters which modules are
11033
+ // validated at all, so passing the pending-patch analysis would make
11034
+ // a project with no pending changes report `valid: true` without
11035
+ // having checked anything. Scoping to one module, when asked, is done
11036
+ // on the results below.
11037
+ undefined);
11038
+ // `validateSources` hands back the files it could not check on its own;
11039
+ // running them is what turns "this path holds a file" into "that file is
11040
+ // actually there and matches its recorded metadata".
11041
+ const fileErrors = await ops.validateFiles(state.schemas, state.sources, validation.files, state.analysis.fileLastUpdatedByPatchId);
11042
+
11043
+ // Per-module results, flattened to the by-source-path shape the filter
11044
+ // takes. Merged rather than overwritten: a path can pick up an error
11045
+ // from validation and another from its file.
11046
+ const bySourcePath = {};
11047
+ const add = (path, errors) => {
11048
+ bySourcePath[path] = (bySourcePath[path] ?? []).concat(errors);
11049
+ };
11050
+ for (const moduleErrors of Object.values(validation.errors)) {
11051
+ for (const [path, errors] of Object.entries(moduleErrors.validations ?? {})) {
11052
+ add(path, errors);
11053
+ }
11054
+ }
11055
+ for (const [path, errors] of Object.entries(fileErrors)) {
11056
+ add(path, errors);
11057
+ }
11058
+
11059
+ // Drops the errors the Studio would not show either: ones whose only
11060
+ // effect is an offered fix. Left in, an agent would loop trying to
11061
+ // "repair" content that is already publishable.
11062
+ const blocking = internal.filterBlockingValidationErrors(bySourcePath, state.serializedSchemas, state.sources);
11063
+
11064
+ // A module whose source could not be read at all has no source path to
11065
+ // hang an error on, so it is reported separately rather than lost.
11066
+ const unreadable = Object.entries(validation.errors).filter(([, moduleErrors]) => moduleErrors.invalidSource).map(([path, moduleErrors]) => {
11067
+ var _moduleErrors$invalid;
11068
+ return {
11069
+ moduleFilePath: path,
11070
+ message: ((_moduleErrors$invalid = moduleErrors.invalidSource) === null || _moduleErrors$invalid === void 0 ? void 0 : _moduleErrors$invalid.message) ?? "Invalid source"
11071
+ };
11072
+ });
11073
+ const scope = moduleFilePath;
11074
+ const errors = scope === undefined ? blocking : filterKeysByModule(blocking, scope);
11075
+ const unreadableInScope = scope === undefined ? unreadable : unreadable.filter(u => u.moduleFilePath === scope);
11076
+ return ok({
11077
+ valid: Object.keys(errors).length === 0 && unreadableInScope.length === 0,
11078
+ errors: Object.fromEntries(Object.entries(errors).map(([path, errs]) => [path, errs.map(toJsonValidationError)])),
11079
+ // Always present, empty when there are none: a caller should not have
11080
+ // to tell "absent" from "empty" to decide whether content is publishable.
11081
+ unreadableModules: unreadableInScope
11082
+ });
11083
+ }), defineTool({
11084
+ name: "get_patches",
11085
+ title: "Get patches",
11086
+ 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.",
11087
+ inputSchema: z.z.object({
11088
+ moduleFilePath: ModuleFilePathSchema$1.optional().describe("Limit to changes touching one module.")
11089
+ }),
11090
+ annotations: {
11091
+ readOnlyHint: true
11092
+ }
11093
+ }, async ({
11094
+ moduleFilePath
11095
+ }, {
11096
+ state
11097
+ }) => {
11098
+ const wanted = moduleFilePath === undefined ? state.patches.patches : state.patches.patches.filter(p => p.path === moduleFilePath);
11099
+ // Which patches would not apply, flattened to one lookup by id: without
11100
+ // this a module's content can silently differ from what publishing
11101
+ // would produce, and nothing anywhere says why.
11102
+ const failures = new Map();
11103
+ for (const unapplied of Object.values(state.unappliedPatches)) {
11104
+ for (const failure of unapplied) {
11105
+ failures.set(failure.patchId, failure.error.message);
11106
+ }
11107
+ }
11108
+ return ok(wanted.map(patch => {
11109
+ const failure = failures.get(patch.patchId);
11110
+ return {
11111
+ patchId: patch.patchId,
11112
+ moduleFilePath: patch.path,
11113
+ createdAt: patch.createdAt,
11114
+ authorId: patch.authorId,
11115
+ // `appliedAt` non-null means this change is already committed, so
11116
+ // it is history rather than something still pending.
11117
+ published: patch.appliedAt !== null,
11118
+ // Always present, so "applies cleanly" is stated rather than
11119
+ // inferred from the absence of a field.
11120
+ appliesCleanly: failure === undefined,
11121
+ ...(failure === undefined ? {} : {
11122
+ applyError: failure
11123
+ })
11124
+ };
11125
+ }));
11126
+ }), defineTool({
11127
+ name: "get_source_path_from_route",
11128
+ title: "Get source path from route",
11129
+ 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.",
11130
+ inputSchema: z.z.object({
11131
+ route: z.z.string().describe('A route on the site, e.g. "/blog/my-post".')
11132
+ }),
11133
+ annotations: {
11134
+ readOnlyHint: true,
11135
+ idempotentHint: true
11136
+ }
11137
+ }, async ({
11138
+ route
11139
+ }, {
11140
+ state
11141
+ }) => {
11142
+ const found = core.getSourcePathFromRoute(route, state.serializedSchemas);
11143
+ if (!found) {
11144
+ 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.`);
11145
+ }
11146
+ return ok(found);
11147
+ })];
11148
+ }
11149
+
11150
+ /**
11151
+ * Resolve a module and classify the value at a path inside it.
11152
+ *
11153
+ * Shared by `get_record_keys` and `count_entries` so the two cannot drift on
11154
+ * what counts as a missing module, and so both map the same failure to the same
11155
+ * error code: a path that is not there is `not-found`, while a path that is
11156
+ * there but holds a string or an image is `invalid-args` — the caller should
11157
+ * reach for a different tool, not go looking for the path again.
11158
+ */
11159
+ function describeContainer(state, moduleFilePath, path) {
11160
+ const modulePath = moduleFilePath;
11161
+ const schema = state.serializedSchemas[modulePath];
11162
+ if (!schema) {
11163
+ return {
11164
+ kind: "error",
11165
+ result: err("not-found", unknownModuleMessage(modulePath, state))
11166
+ };
11167
+ }
11168
+ const described = internal.describeContainerAtPath(schema, state.sources[modulePath], path);
11169
+ if (described.kind === "error") {
11170
+ return {
11171
+ kind: "error",
11172
+ result: err(described.reason === "missing" ? "not-found" : "invalid-args", described.message)
11173
+ };
11174
+ }
11175
+ return described;
11176
+ }
11177
+
11178
+ /** "a record", but "an object" and "an array". */
11179
+ function article(container) {
11180
+ return container === "object" || container === "array" ? "an" : "a";
11181
+ }
11182
+ function unknownModuleMessage(path, state) {
11183
+ const known = Object.keys(state.serializedSchemas);
11184
+ return `No Val module at ${JSON.stringify(path)}. Known modules: ${known.length === 0 ? "(none)" : known.join(", ")}`;
11185
+ }
11186
+
11187
+ /**
11188
+ * Project a validation error into something JSON-safe and worth reading.
11189
+ *
11190
+ * `ValidationError.value` is dropped rather than serialized: it is `unknown` (so
11191
+ * not `Json` to begin with) and it holds the offending source value, which can
11192
+ * be arbitrarily large. A caller already has the source path and can read the
11193
+ * value with `get_source` if it needs to — putting it here would bloat every
11194
+ * result for the rare case that wants it.
11195
+ *
11196
+ * `fixes` is kept, because it names what Val already knows how to repair, which
11197
+ * is directly actionable.
11198
+ */
11199
+ function toJsonValidationError(error) {
11200
+ return {
11201
+ message: error.message,
11202
+ fixes: error.fixes ? [...error.fixes] : [],
11203
+ typeError: error.typeError === true,
11204
+ schemaError: error.schemaError === true,
11205
+ keyError: error.keyError === true
11206
+ };
11207
+ }
11208
+ function isPlainObject(value) {
11209
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11210
+ }
11211
+
11212
+ /**
11213
+ * Keep only the entries belonging to one module.
11214
+ *
11215
+ * Keyed by SourcePath, which begins with the module file path, so a prefix match
11216
+ * is the right test — there is no per-module grouping left to index by.
11217
+ */
11218
+ function filterKeysByModule(record, moduleFilePath) {
11219
+ const out = {};
11220
+ for (const [path, value] of Object.entries(record)) {
11221
+ if (path.startsWith(moduleFilePath)) {
11222
+ out[path] = value;
11223
+ }
11224
+ }
11225
+ return out;
11226
+ }
11227
+
11228
+ /**
11229
+ * Everything the Studio does client-side before a patch can be saved, done
11230
+ * server-side.
11231
+ *
11232
+ * Three things had no server equivalent, and each is a way to be quietly wrong:
11233
+ * where the patch id comes from, what the patch says its parent is, and whether
11234
+ * the result would even be valid. `docs/plans/mcp.md` Part C is the design.
11235
+ */
11236
+
11237
+ const jsonOps = new patch.JSONOps();
11238
+
11239
+ /**
11240
+ * A patch id, minted before the write is attempted.
11241
+ *
11242
+ * Same shape the Studio mints (a v4 UUID), and minting one that never gets used
11243
+ * costs nothing — ids are not registered anywhere until a patch carries them.
11244
+ */
11245
+ function mintPatchId() {
11246
+ // A branded string has no constructor; this is the same conversion the Studio
11247
+ // and ValServer both make.
11248
+ return node_crypto.randomUUID();
11249
+ }
11250
+
11251
+ /**
11252
+ * What the new patch should hang off.
11253
+ *
11254
+ * The last known patch if there is one, otherwise the current head. Note the
11255
+ * asymmetry between the two backends: `ValOpsFS` ignores `parentRef` entirely
11256
+ * because its append-only ordering log defines order, while `ValOpsHttp` sends
11257
+ * it up as `parentPatchId` for optimistic concurrency. So a wrong value here is
11258
+ * invisible locally and a conflict in production — which is why this is derived
11259
+ * fresh rather than remembered.
11260
+ */
11261
+ async function deriveParentRef(ops,
11262
+ // Only the ids matter, so this accepts either shape `fetchPatches` can
11263
+ // return — the metadata-only variant omits the ops but keeps the ids.
11264
+ patches) {
11265
+ const last = patches.patches[patches.patches.length - 1];
11266
+ if (last) {
11267
+ return {
11268
+ type: "patch",
11269
+ patchId: last.patchId
11270
+ };
11271
+ }
11272
+ return {
11273
+ type: "head",
11274
+ headBaseSha: await ops.getBaseSha()
11275
+ };
11276
+ }
11277
+
11278
+ /**
11279
+ * Would this patch leave the content valid?
11280
+ *
11281
+ * Applied to a **clone** of the sources, never the real ones: `applyPatch`
11282
+ * mutates the document it is given, and ValOps carries a standing note that
11283
+ * add operations misbehave without a clone. Validating in place would corrupt
11284
+ * the sources every later call in this process reads.
11285
+ *
11286
+ * Server-side this is strictly better than the Studio's speculative check.
11287
+ * `getSchemas()` returns real `Schema` instances, so the user's own `validate`
11288
+ * closures run — and those are not carried by the serialized schema the browser
11289
+ * has, which means the browser cannot run them at all.
11290
+ */
11291
+ async function validateSpeculatively(ops, state, moduleFilePath, patch$1) {
11292
+ const current = state.sources[moduleFilePath];
11293
+ if (current === undefined) {
11294
+ return {
11295
+ status: "unapplicable",
11296
+ result: {
11297
+ status: "error",
11298
+ code: "not-found",
11299
+ message: `No Val module at ${JSON.stringify(moduleFilePath)}.`
11300
+ }
11301
+ };
11302
+ }
11303
+ const applied = patch.applyPatch(patch.deepClone(current), jsonOps, patch$1);
11304
+ if (fp.result.isErr(applied)) {
11305
+ return {
11306
+ status: "unapplicable",
11307
+ result: {
11308
+ status: "error",
11309
+ code: "invalid-args",
11310
+ message: `The patch cannot be applied to ${moduleFilePath}: ${applied.error.message}`
11311
+ }
11312
+ };
11313
+ }
11314
+ const speculativeSources = {
11315
+ ...state.sources,
11316
+ [moduleFilePath]: applied.value
11317
+ };
11318
+ const after = await blockingErrorsIn(ops, state, speculativeSources, moduleFilePath);
11319
+ if (after.length === 0) {
11320
+ return {
11321
+ status: "valid"
11322
+ };
11323
+ }
11324
+
11325
+ // Only the errors this patch *introduces*. A module can already be broken for
11326
+ // reasons this change has nothing to do with -- the example app ships with a
11327
+ // missing image file -- and refusing on the total would make every such module
11328
+ // permanently read-only: an agent could not fix a typo in a file that also
11329
+ // holds a broken image reference. Paid for only when there is something to
11330
+ // refuse, so an ordinary clean edit still validates once.
11331
+ const before = await blockingErrorsIn(ops, state, state.sources, moduleFilePath);
11332
+ const existing = new Set(before.map(identify));
11333
+ const introduced = after.filter(error => !existing.has(identify(error)));
11334
+ if (introduced.length === 0) {
11335
+ return {
11336
+ status: "valid"
11337
+ };
11338
+ }
11339
+ return {
11340
+ status: "invalid",
11341
+ errors: describeErrors(introduced)
11342
+ };
11343
+ }
11344
+ /** Path and message together: the same message at another path is another problem. */
11345
+ function identify(error) {
11346
+ return `${error.path}\u0000${error.message}`;
11347
+ }
11348
+
11349
+ /**
11350
+ * The publishing-blocking errors in one module, for a given set of sources.
11351
+ *
11352
+ * Scoped to one module by source path, which starts with the module file path.
11353
+ * Errors elsewhere in the project are somebody else's: refusing on them would
11354
+ * let the first broken module in a repo make every other module read-only.
11355
+ */
11356
+ async function blockingErrorsIn(ops, state, sources, moduleFilePath) {
11357
+ const validation = await ops.validateSources(state.schemas, sources,
11358
+ // Every module, deliberately -- `patchesByModule` is a FILTER on which
11359
+ // modules get validated, not context for validating them. Passing the
11360
+ // analysis from before this write skips the very module being written
11361
+ // whenever it had no pending patch, so the first change to a module went
11362
+ // unchecked; and a change that breaks a `keyOf` or a router in a *different*
11363
+ // module reports its error there, which a filtered run never visits.
11364
+ undefined);
11365
+ // `validateSources` hands back the files it could not check on its own;
11366
+ // running them is what turns "this path holds a file" into "that file is
11367
+ // actually there and matches its recorded metadata".
11368
+ const fileErrors = await ops.validateFiles(state.schemas, sources, validation.files, state.analysis.fileLastUpdatedByPatchId);
11369
+
11370
+ // Merged rather than overwritten: a path can pick up an error from validation
11371
+ // and another from its file.
11372
+ const bySourcePath = {};
11373
+ const add = (path, errors) => {
11374
+ bySourcePath[path] = (bySourcePath[path] ?? []).concat(errors);
11375
+ };
11376
+ for (const moduleErrors of Object.values(validation.errors)) {
11377
+ for (const [path, errors] of Object.entries(moduleErrors.validations ?? {})) {
11378
+ add(path, errors);
11379
+ }
11380
+ }
11381
+ for (const [path, errors] of Object.entries(fileErrors)) {
11382
+ add(path, errors);
11383
+ }
11384
+ const blocking = internal.filterBlockingValidationErrors(bySourcePath, state.serializedSchemas, sources);
11385
+ const located = [];
11386
+ for (const [path, errors] of Object.entries(blocking)) {
11387
+ if (!path.startsWith(moduleFilePath)) {
11388
+ continue;
11389
+ }
11390
+ for (const error of errors) {
11391
+ located.push({
11392
+ path: path,
11393
+ message: error.message
11394
+ });
11395
+ }
11396
+ }
11397
+ return located;
11398
+ }
11399
+ function describeErrors(errors) {
11400
+ return errors.map(e => `${e.path}: ${e.message}`).join("; ");
11401
+ }
11402
+
11403
+ /**
11404
+ * What to do when the change would leave the content invalid.
11405
+ *
11406
+ * `"reject"` for a tool that is editing existing content: an agent should not be
11407
+ * able to break a site, and a rejected patch stores nothing.
11408
+ *
11409
+ * `"report"` for a tool whose whole purpose is to create something incomplete.
11410
+ * `empty_at_path` scaffolds an entry the caller is then expected to fill in, so
11411
+ * on most real schemas — anything with a non-empty string — the value it creates
11412
+ * is invalid by construction. Rejecting that would make the tool useless on
11413
+ * exactly the schemas it exists for, so instead the patch is saved and the
11414
+ * remaining errors come back as a to-do list. This mirrors the Studio, where
11415
+ * creating an empty entry is normal and the errors show until it is filled in.
11416
+ */
11417
+
11418
+ /**
11419
+ * Validate, then save — and retry once if someone else got there first.
11420
+ *
11421
+ * The retry exists because the parent ref is derived from a read that happened
11422
+ * before the write. A conflict means the chain moved underneath us, and
11423
+ * re-deriving is usually enough. Once only: a loop here would be an agent
11424
+ * fighting a human editor in the Studio, and losing slowly is worse than
11425
+ * failing clearly.
11426
+ */
11427
+ async function savePatch(deps, moduleFilePath, patch, onInvalid = "reject") {
11428
+ const {
11429
+ ops,
11430
+ ctx,
11431
+ state
11432
+ } = deps;
11433
+ const unapplied = state.unappliedPatches[moduleFilePath];
11434
+ if (unapplied && unapplied.length > 0) {
11435
+ // Refused before anything is validated, because the state to validate
11436
+ // against is wrong. `sources` for this module silently lacks these pending
11437
+ // changes, so a patch built on it would be based on content that will never
11438
+ // exist -- and its parent ref would chain onto changes that do not apply.
11439
+ return {
11440
+ status: "error",
11441
+ code: "internal",
11442
+ 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.`
11443
+ };
11444
+ }
11445
+ const speculative = await validateSpeculatively(ops, state, moduleFilePath, patch);
11446
+ if (speculative.status === "unapplicable") {
11447
+ // Never negotiable: the patch does not fit the content, so there is nothing
11448
+ // to save whatever the caller's tolerance for invalid results.
11449
+ return speculative.result;
11450
+ }
11451
+ let unresolved = null;
11452
+ if (speculative.status === "invalid") {
11453
+ if (onInvalid === "reject") {
11454
+ return {
11455
+ status: "error",
11456
+ code: "validation-failed",
11457
+ message: `The change was rejected and nothing was saved, because it would leave the content invalid: ${speculative.errors}`
11458
+ };
11459
+ }
11460
+ unresolved = speculative.errors;
11461
+ }
11462
+
11463
+ // Always null, and deliberately so. The app cannot resolve a PAT to a
11464
+ // profile, so any id it put here would be an unverified claim dressed up as a
11465
+ // checked one — and the request already carries the caller's own token, which
11466
+ // is a better answer to "who did this" than anything the app could assert.
11467
+ // Attributing the patch from that token is a backend concern; see
11468
+ // `docs/plans/mcp.md` D.3.
11469
+ const authorId = null;
11470
+ for (let attempt = 0; attempt < 2; attempt++) {
11471
+ const patchId = mintPatchId();
11472
+ // Re-derived on the retry rather than reused: reusing the ref that just
11473
+ // conflicted would conflict again by definition.
11474
+ const patches = attempt === 0 ? state.patches : await ops.fetchPatches({
11475
+ excludePatchOps: true
11476
+ });
11477
+ const parentRef = await deriveParentRef(ops, patches);
11478
+ const saved = await ops.createPatch(moduleFilePath, patch, patchId, parentRef, ctx.sessionId, authorId);
11479
+ if (fp.result.isOk(saved)) {
11480
+ return {
11481
+ status: "ok",
11482
+ data: {
11483
+ patchId: saved.value.patchId,
11484
+ moduleFilePath,
11485
+ createdAt: saved.value.createdAt,
11486
+ // Always present, so a caller does not have to tell "absent" from
11487
+ // "nothing left to do" to know whether the content is publishable.
11488
+ unresolvedValidationErrors: unresolved
11489
+ }
11490
+ };
11491
+ }
11492
+ if (saved.error.errorType === "patch-head-conflict") {
11493
+ continue;
11494
+ }
11495
+ return {
11496
+ status: "error",
11497
+ code: "internal",
11498
+ // Note the nesting: createPatch wraps the underlying flat error as
11499
+ // `{ errorType: "other", error: <that> }`.
11500
+ message: saved.error.error.message
11501
+ };
11502
+ }
11503
+ return {
11504
+ status: "error",
11505
+ code: "conflict",
11506
+ message: "Another change was saved while this one was being written, twice in a row. Read the content again before retrying — it has moved."
11507
+ };
11508
+ }
11509
+
11510
+ /**
11511
+ * The tools that change content.
11512
+ *
11513
+ * Every one of them goes through {@link savePatch}, so they all inherit the same
11514
+ * guarantees: the change is validated against the real schemas before anything
11515
+ * is stored, a rejected change stores nothing, and a lost race with another
11516
+ * writer is retried once and then reported rather than looped on.
11517
+ *
11518
+ * Images are not here. The Studio's image tools work from a handle into Val's
11519
+ * AI session store — bytes the browser got from the vision system — and MCP has
11520
+ * no equivalent, so they need a different affordance (a local file path, or
11521
+ * inline base64) rather than a port. `docs/plans/mcp.md` Part B has the reasoning.
11522
+ */
11523
+
11524
+ const ModuleFilePathSchema = z.z.string().describe('Path of the Val module, e.g. "/content/pages.val.ts".');
11525
+ function writeTools() {
11526
+ return [defineTool({
11527
+ name: "create_patch",
11528
+ title: "Create patch",
11529
+ 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.",
11530
+ inputSchema: z.z.object({
11531
+ moduleFilePath: ModuleFilePathSchema,
11532
+ patch: z.z.array(z.z.unknown()).describe('JSON Patch operations, e.g. [{"op":"replace","path":["title"],"value":"New title"}]. Paths are arrays of keys, not slash-separated strings.')
11533
+ }),
11534
+ annotations: {
11535
+ idempotentHint: false
11536
+ }
11537
+ }, async ({
11538
+ moduleFilePath,
11539
+ patch
11540
+ }, deps) => {
11541
+ // Before parsing, not after: a file op that is also malformed should be
11542
+ // told that files are not supported, rather than handed a schema error
11543
+ // about the shape of a thing it was never going to be allowed to do.
11544
+ const rejected = rejectFileOps(patch);
11545
+ if (rejected) {
11546
+ return rejected;
11547
+ }
11548
+ const parsed = internal.safeParsePatch(patch);
11549
+ if (parsed.kind !== "ok") {
11550
+ return fromBuildResult(parsed);
11551
+ }
11552
+ return savePatch(deps, moduleFilePath, parsed.patch);
11553
+ }), defineTool({
11554
+ name: "duplicate_source",
11555
+ title: "Duplicate source",
11556
+ 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.",
11557
+ inputSchema: z.z.object({
11558
+ moduleFilePath: ModuleFilePathSchema,
11559
+ sourcePath: z.z.array(z.z.string()).describe("Path of the value to copy."),
11560
+ destinationPath: z.z.array(z.z.string()).describe("Path to copy it to. Must not already exist.")
11561
+ }),
11562
+ annotations: {
11563
+ idempotentHint: false
11564
+ }
11565
+ }, async ({
11566
+ moduleFilePath,
11567
+ sourcePath,
11568
+ destinationPath
11569
+ }, deps) => {
11570
+ const modulePath = moduleFilePath;
11571
+ const schema = deps.state.serializedSchemas[modulePath];
11572
+ if (!schema) {
11573
+ return err("not-found", `No Val module at ${JSON.stringify(modulePath)}.`);
11574
+ }
11575
+ const built = internal.buildDuplicatePatch({
11576
+ sourcePath,
11577
+ destinationPath
11578
+ }, schema, deps.state.sources[modulePath]);
11579
+ if (built.kind !== "ok") {
11580
+ return fromBuildResult(built);
11581
+ }
11582
+ return savePatch(deps, modulePath, built.patch);
11583
+ }), defineTool({
11584
+ name: "empty_at_path",
11585
+ title: "Create an empty value at a path",
11586
+ 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.",
11587
+ inputSchema: z.z.object({
11588
+ moduleFilePath: ModuleFilePathSchema,
11589
+ destinationPath: z.z.array(z.z.string()).describe("Path to create the empty value at.")
11590
+ }),
11591
+ annotations: {
11592
+ idempotentHint: false
11593
+ }
11594
+ }, async ({
11595
+ moduleFilePath,
11596
+ destinationPath
11597
+ }, deps) => {
11598
+ const modulePath = moduleFilePath;
11599
+ const schema = deps.state.serializedSchemas[modulePath];
11600
+ if (!schema) {
11601
+ return err("not-found", `No Val module at ${JSON.stringify(modulePath)}.`);
11602
+ }
11603
+ const built = internal.buildEmptyAtPathPatch({
11604
+ destinationPath
11605
+ }, schema, deps.state.sources[modulePath]);
11606
+ if (built.kind !== "ok") {
11607
+ return fromBuildResult(built);
11608
+ }
11609
+ // "report", not "reject": an empty entry is invalid by construction on
11610
+ // any schema with a required non-empty field, which is most of them.
11611
+ // See OnInvalid in writePath.ts.
11612
+ return savePatch(deps, modulePath, built.patch, "report");
11613
+ }), defineTool({
11614
+ name: "remove_image_gallery_entry",
11615
+ title: "Remove an image gallery entry",
11616
+ description: "Remove one image from an image gallery module by its file path. This deletes the entry and the file it refers to.",
11617
+ inputSchema: z.z.object({
11618
+ moduleFilePath: ModuleFilePathSchema.describe("The gallery module, i.e. one declared with s.images() or s.files()."),
11619
+ filePath: z.z.string().describe('The gallery key to remove, e.g. "/public/val/photo_a1b2c.jpg".')
11620
+ }),
11621
+ // Destructive: it removes content and the underlying file, so a host
11622
+ // that asks for confirmation should ask here.
11623
+ annotations: {
11624
+ destructiveHint: true,
11625
+ idempotentHint: false
11626
+ }
11627
+ }, async ({
11628
+ moduleFilePath,
11629
+ filePath
11630
+ }, deps) => {
11631
+ const modulePath = moduleFilePath;
11632
+ const schema = deps.state.serializedSchemas[modulePath];
11633
+ if (!schema) {
11634
+ return err("not-found", `No Val module at ${JSON.stringify(modulePath)}.`);
11635
+ }
11636
+ const built = internal.buildRemoveImageGalleryEntryPatch({
11637
+ filePath
11638
+ }, schema, deps.state.sources[modulePath]);
11639
+ if (built.kind !== "ok") {
11640
+ return fromBuildResult(built);
11641
+ }
11642
+ return savePatch(deps, modulePath, built.patch);
11643
+ })];
11644
+ }
11645
+
11646
+ /**
11647
+ * Turn a helper's build failure into a tool error.
11648
+ *
11649
+ * `wrong-tool` is worth keeping distinct: the helpers can tell that the caller
11650
+ * reached for the wrong tool and which one it should have used, and passing that
11651
+ * through is what lets a model correct itself in one step instead of retrying
11652
+ * the same call.
11653
+ */
11654
+ function fromBuildResult(built) {
11655
+ if (built.kind === "wrong-tool") {
11656
+ return {
11657
+ status: "error",
11658
+ code: "invalid-args",
11659
+ message: `${built.reason} Use the ${built.suggestedTool} tool instead.`
11660
+ };
11661
+ }
11662
+ return {
11663
+ status: "error",
11664
+ code: "invalid-args",
11665
+ message: built.message
11666
+ };
11667
+ }
11668
+
11669
+ /**
11670
+ * File operations are refused rather than half-supported.
11671
+ *
11672
+ * A `file` op carries binary content that has to be uploaded before the patch
11673
+ * is synced — a two-phase flow this pass does not implement. Letting one through
11674
+ * would store a patch referring to bytes that were never uploaded, which fails
11675
+ * later and a long way from the cause.
11676
+ *
11677
+ * Takes the unparsed patch, so this answer does not depend on the op being
11678
+ * otherwise well formed. All it needs is the caller's own claim about what the
11679
+ * op is.
11680
+ */
11681
+ function rejectFileOps(patch) {
11682
+ const hasFileOp = patch.some(op => typeof op === "object" && op !== null && "op" in op && op.op === "file");
11683
+ if (!hasFileOp) {
11684
+ return null;
11685
+ }
11686
+ return {
11687
+ status: "error",
11688
+ code: "unsupported",
11689
+ message: "This patch contains a file operation. Uploading files is not supported over MCP yet — only text and JSON values can be changed."
11690
+ };
11691
+ }
11692
+
11693
+ /**
11694
+ * How many callers' data layers to keep around in proxy mode.
11695
+ *
11696
+ * Each entry holds one `ValOpsHttp`, and each of those caches the project's
11697
+ * evaluated modules once `initSources` has run — so this bounds memory, not just
11698
+ * entry count. Small on purpose: the cost of a miss is re-evaluating the
11699
+ * modules on the next call, which is what happened on *every* call before this
11700
+ * cache existed.
11701
+ */
11702
+ const MAX_CACHED_OPS = 8;
11703
+
11704
+ /**
11705
+ * Val's server-side tool registry.
11706
+ *
11707
+ * This is the piece Val did not have: the Studio's chat tools are defined *and
11708
+ * executed in the browser*, against its client stores, so nothing here could be
11709
+ * re-exposed. These tools run against {@link ValOps} instead, which is what lets
11710
+ * an MCP server — or a stdio transport, or anything else — drive Val content
11711
+ * without a browser.
11712
+ *
11713
+ * Transport-agnostic on purpose: nothing under `tools/` imports an MCP SDK. A
11714
+ * host adapts {@link ValToolResult} at its own edge.
11715
+ */
11716
+ function createValTools(valModules, options) {
11717
+ const resolveOps = createOpsResolver(valModules, options);
11718
+ const tools = [...readTools(), ...writeTools()];
11719
+ const byName = new Map(tools.map(tool => [tool.name, tool]));
11720
+ return {
11721
+ list() {
11722
+ return tools.map(({
11723
+ handler: _handler,
11724
+ ...definition
11725
+ }) => definition);
11726
+ },
11727
+ listJsonSchema() {
11728
+ return tools.map(({
11729
+ handler: _handler,
11730
+ inputSchema,
11731
+ ...rest
11732
+ }) => ({
11733
+ ...rest,
11734
+ // zod 4 derives this itself, so there is no JSON-Schema-to-zod
11735
+ // converter anywhere in the stack and no second description of the
11736
+ // same input to keep in step.
11737
+ inputSchema: z.z.toJSONSchema(inputSchema, {
11738
+ io: "input"
11739
+ })
11740
+ }));
11741
+ },
11742
+ async call(name, args, ctx) {
11743
+ const tool = byName.get(name);
11744
+ if (!tool) {
11745
+ return {
11746
+ status: "error",
11747
+ code: "unknown-tool",
11748
+ message: `No tool named ${JSON.stringify(name)}. Available: ${tools.map(t => t.name).join(", ")}`
11749
+ };
11750
+ }
11751
+ const parsed = tool.inputSchema.safeParse(args ?? {});
11752
+ if (!parsed.success) {
11753
+ return {
11754
+ status: "error",
11755
+ code: "invalid-args",
11756
+ message: describeZodError(parsed.error)
11757
+ };
11758
+ }
11759
+ const resolved = resolveOps(ctx);
11760
+ if (resolved.status === "error") {
11761
+ return resolved.result;
11762
+ }
11763
+ const ops = resolved.ops;
11764
+ try {
11765
+ const state = await loadState(ops);
11766
+ if (state.status === "error") {
11767
+ return state.result;
11768
+ }
11769
+ const deps = {
11770
+ ops,
11771
+ ctx,
11772
+ state: state.state
11773
+ };
11774
+ return await tool.handler(parsed.data, deps);
11775
+ } catch (error) {
11776
+ // A thrown error here is a bug or an unreachable backend, not something
11777
+ // the model can act on — but it still comes back in-band so the client
11778
+ // sees a tool failure rather than a dead transport.
11779
+ return {
11780
+ status: "error",
11781
+ code: "internal",
11782
+ message: error instanceof Error ? error.message : String(error)
11783
+ };
11784
+ }
11785
+ },
11786
+ async dispose() {
11787
+ // Nothing to release today: ValOps holds no handle that needs closing, and
11788
+ // the fs watcher it can start is owned by the Studio's server. Kept in the
11789
+ // contract so hosts wire up teardown now rather than when it starts to
11790
+ // matter.
11791
+ }
11792
+ };
11793
+ }
11794
+
11795
+ /**
11796
+ * Pick the data layer for a call, which in proxy mode means picking whose
11797
+ * credential the backend will see.
11798
+ *
11799
+ * This is the one place authorization is decided, and it decides it by *not*
11800
+ * deciding: in proxy mode the caller's own personal access token goes to the
11801
+ * backend, which is the only party that can say what that token may do. The app
11802
+ * never inspects it, never caches a verdict about it, and never substitutes its
11803
+ * own API key for a missing one — see `docs/plans/mcp.md` D.2.
11804
+ *
11805
+ * The alternative shape, and the reason this function exists at all, is an
11806
+ * `authenticate()` that checks the PAT once and then acts under the app's key.
11807
+ * That reads as more secure and is strictly less so: the check happens in the
11808
+ * app, so every bug in it becomes full access to every project the app's key
11809
+ * can reach, and the backend's own permission model stops being consulted (D.6).
11810
+ */
11811
+ function createOpsResolver(valModules, options) {
11812
+ if (options.mode === "fs") {
11813
+ // One instance, built once: fs mode is a developer's own working tree, so
11814
+ // there is no credential to vary by and no reason to re-evaluate modules.
11815
+ const ops = createValOps(valModules, options);
11816
+ return ctx => {
11817
+ if (ctx.auth) {
11818
+ // Refused rather than ignored. A host that thinks it is passing a
11819
+ // credential should not silently get local filesystem access instead —
11820
+ // and the difference matters, because fs mode writes straight to disk
11821
+ // with no backend permission check at all.
11822
+ return {
11823
+ status: "error",
11824
+ result: {
11825
+ status: "error",
11826
+ code: "unsupported",
11827
+ message: "This Val project is running in local filesystem mode, where there is nothing to authenticate against. Do not send a credential."
11828
+ }
11829
+ };
11830
+ }
11831
+ return {
11832
+ status: "ok",
11833
+ ops
11834
+ };
11835
+ };
11836
+ }
11837
+
11838
+ // Keyed by a hash of the PAT, so the same caller reuses their own instance and
11839
+ // two callers can never share one. Hashing is not a security boundary — the
11840
+ // instance holds the token regardless — but it keeps credentials out of the
11841
+ // key set, which is the thing that ends up in a heap dump or an error dump.
11842
+ const byPatHash = new Map();
11843
+ return ctx => {
11844
+ if (!ctx.auth) {
11845
+ return {
11846
+ status: "error",
11847
+ result: {
11848
+ status: "error",
11849
+ code: "forbidden",
11850
+ message: "This Val project talks to the Val content backend, so every call needs the caller's own personal access token. Run `val login` to get one."
11851
+ }
11852
+ };
11853
+ }
11854
+ const key = node_crypto.createHash("sha256").update(ctx.auth.pat).digest("hex");
11855
+ const cached = byPatHash.get(key);
11856
+ if (cached) {
11857
+ // Re-inserted so eviction drops the least recently used rather than the
11858
+ // oldest — a long-running caller should not be evicted by a burst of
11859
+ // one-off ones.
11860
+ byPatHash.delete(key);
11861
+ byPatHash.set(key, cached);
11862
+ return {
11863
+ status: "ok",
11864
+ ops: cached
11865
+ };
11866
+ }
11867
+ const ops = createValOps(valModules, options, {
11868
+ pat: ctx.auth.pat
11869
+ });
11870
+ byPatHash.set(key, ops);
11871
+ while (byPatHash.size > MAX_CACHED_OPS) {
11872
+ const oldest = byPatHash.keys().next();
11873
+ if (oldest.done) {
11874
+ break;
11875
+ }
11876
+ byPatHash.delete(oldest.value);
11877
+ }
11878
+ return {
11879
+ status: "ok",
11880
+ ops
11881
+ };
11882
+ };
11883
+ }
11884
+ /**
11885
+ * The content as the caller should see it, loaded once per call.
11886
+ *
11887
+ * Pending patches are applied, because an agent looking at a project mid-edit
11888
+ * should see what the Studio would show rather than the last published state.
11889
+ *
11890
+ * Deliberately not cached across calls. In fs mode a save recomputes the base
11891
+ * sha within the same process, so a cached view would go stale silently — and
11892
+ * the cost of being wrong here is an agent writing a patch against content that
11893
+ * has already moved.
11894
+ */
11895
+ async function loadState(ops) {
11896
+ const patches = await ops.fetchPatches({
11897
+ excludePatchOps: false
11898
+ });
11899
+ // fetchPatches resolves with its failures on the result rather than rejecting,
11900
+ // so not checking these reads as "no pending changes" — which would quietly
11901
+ // hand back published content and let a write be based on it.
11902
+ if (patches.unauthorized) {
11903
+ return {
11904
+ status: "error",
11905
+ result: {
11906
+ status: "error",
11907
+ code: "forbidden",
11908
+ message: "Not authorized to read this project's pending changes. Check that the credential is valid and has access."
11909
+ }
11910
+ };
11911
+ }
11912
+ if (patches.networkError) {
11913
+ return {
11914
+ status: "error",
11915
+ result: {
11916
+ status: "error",
11917
+ code: "internal",
11918
+ message: "Could not reach the Val content backend."
11919
+ }
11920
+ };
11921
+ }
11922
+ if (patches.error) {
11923
+ return {
11924
+ status: "error",
11925
+ result: {
11926
+ status: "error",
11927
+ code: "internal",
11928
+ message: patches.error.message
11929
+ }
11930
+ };
11931
+ }
11932
+ const analysis = ops.analyzePatches(patches.patches);
11933
+ // getSourcesWithPatchesApplied, not getSources(analysis): the latter returns
11934
+ // only the modules that had patches, and validating that subset reports
11935
+ // spurious errors for anything that looks across modules, like keyOf or a
11936
+ // router.
11937
+ const sourcesRes = await ops.getSourcesWithPatchesApplied({
11938
+ ...analysis,
11939
+ ...patches
11940
+ });
11941
+ const [schemas, serializedSchemas] = await Promise.all([ops.getSchemas(), ops.getSerializedSchemas()]);
11942
+ return {
11943
+ status: "ok",
11944
+ state: {
11945
+ schemas,
11946
+ serializedSchemas,
11947
+ sources: sourcesRes.sources,
11948
+ patches,
11949
+ analysis,
11950
+ // Which modules hold a pending patch that would not apply. Carried rather
11951
+ // than discarded because their `sources` silently lack that change: the
11952
+ // content here is not what publishing would produce, so a write against
11953
+ // it would be based on a state that does not exist. See
11954
+ // `unappliedPatchesFor`.
11955
+ unappliedPatches: sourcesRes.errors
11956
+ }
11957
+ };
11958
+ }
11959
+ function describeZodError(error) {
11960
+ return error.issues.map(issue => {
11961
+ const path = issue.path.join(".");
11962
+ return path ? `${path}: ${issue.message}` : issue.message;
11963
+ }).join("; ");
11964
+ }
11965
+
11966
+ const JsFileLookupMapping = [
11967
+ // NOTE: first one matching will be used
11968
+ [".cjs.d.ts", [".esm.js", ".mjs.js"]], [".cjs.js", [".esm.js", ".mjs.js"]], [".cjs", [".mjs"]], [".d.ts", [".js", ".esm.js", ".mjs.js"]]];
11969
+ const MAX_CACHE_SIZE = 100 * 1024 * 1024; // 100 mb
11970
+ const MAX_OBJECT_KEY_SIZE = 2 ** 27; // https://stackoverflow.com/questions/13367391/is-there-a-limit-on-length-of-the-key-string-in-js-object
11971
+
11972
+ class ValModuleLoader {
11973
+ constructor(projectRoot, compilerOptions,
11974
+ // TODO: remove this?
11975
+ sourceFileHandler, host = {
11976
+ ...ts__default["default"].sys,
11977
+ writeFile: (fileName, data, encoding) => {
11978
+ fs__default["default"].mkdirSync(path__namespace["default"].dirname(fileName), {
11979
+ recursive: true
11980
+ });
11981
+ fs__default["default"].writeFileSync(fileName, typeof data === "string" ? data : new Uint8Array(data), encoding);
11982
+ },
11983
+ rmFile: fs__default["default"].rmSync,
11984
+ readBuffer: fileName => {
11985
+ try {
11986
+ return fs__default["default"].readFileSync(fileName);
11987
+ } catch {
11988
+ return undefined;
11989
+ }
11990
+ }
11991
+ }, disableCache = false) {
10726
11992
  this.projectRoot = projectRoot;
10727
11993
  this.compilerOptions = compilerOptions;
10728
11994
  this.sourceFileHandler = sourceFileHandler;
@@ -12408,7 +13674,17 @@ async function findAndEvalValConfigFile(projectRoot) {
12408
13674
  }
12409
13675
 
12410
13676
  /**
12411
- * The Val login device flow, as reusable primitives.
13677
+ * The Val login flow, as reusable primitives.
13678
+ *
13679
+ * This is an RFC 8628 device authorization grant. The shape that matters:
13680
+ * {@link ValDeviceAuthorization.deviceCode} is a secret this process holds and
13681
+ * polls with, while {@link ValDeviceAuthorization.userCode} is the short string
13682
+ * the human reads out of the terminal and types into a browser. Only the device
13683
+ * code can collect a token.
13684
+ *
13685
+ * Keep them apart. Show the user code; never print, log or put the device code
13686
+ * in a URL. An earlier version of this flow used one value for both jobs, which
13687
+ * meant anyone who saw the verification link could collect the token it led to.
12412
13688
  *
12413
13689
  * The CLI wraps these with terminal output, and `@valbuild/language-server`
12414
13690
  * wraps them with LSP `window/showDocument` and progress reporting. Neither the
@@ -12422,6 +13698,21 @@ const DEFAULT_LOGIN_HOST = "https://admin.val.build";
12422
13698
  function defaultHost() {
12423
13699
  return process.env.VAL_BUILD_URL || DEFAULT_LOGIN_HOST;
12424
13700
  }
13701
+
13702
+ /**
13703
+ * What gets shown on the approval screen so the person can tell which terminal
13704
+ * is asking. Self-reported and therefore a hint, not proof — the server treats
13705
+ * it as untrusted display text.
13706
+ */
13707
+ function defaultDeviceName() {
13708
+ try {
13709
+ return `${os__default["default"].hostname()} (${os__default["default"].platform()})`;
13710
+ } catch {
13711
+ // hostname() can throw on locked-down containers. A missing device name is
13712
+ // not worth failing a login over; the server renders "Unknown".
13713
+ return "";
13714
+ }
13715
+ }
12425
13716
  class ValLoginError extends Error {
12426
13717
  constructor(code, message, details) {
12427
13718
  super(message);
@@ -12431,20 +13722,24 @@ class ValLoginError extends Error {
12431
13722
  }
12432
13723
  }
12433
13724
 
12434
- /** A login attempt that is waiting for the user to confirm in a browser. */
13725
+ /** A login attempt that is waiting for the user to approve it in a browser. */
12435
13726
 
12436
13727
  /**
12437
- * Begin a login attempt. The caller is responsible for getting
12438
- * {@link ValLoginSession.url} in front of the user.
13728
+ * Begin a login attempt. The caller is responsible for getting the user code
13729
+ * and verification URL in front of the user.
12439
13730
  */
12440
13731
  async function startValLogin(options = {}) {
12441
13732
  var _response$headers$get;
12442
13733
  const host = options.host ?? defaultHost();
13734
+ const deviceName = options.deviceName ?? defaultDeviceName();
12443
13735
  const response = await fetch(`${host}/api/login`, {
12444
13736
  method: "POST",
12445
13737
  headers: {
12446
13738
  "Content-Type": "application/json"
12447
- }
13739
+ },
13740
+ body: JSON.stringify(deviceName ? {
13741
+ device_name: deviceName
13742
+ } : {})
12448
13743
  });
12449
13744
  if (response.status >= 500) {
12450
13745
  const text = await response.text().catch(() => "");
@@ -12455,42 +13750,63 @@ async function startValLogin(options = {}) {
12455
13750
  throw new ValLoginError("unexpected-content-type", "Unexpected failure while trying to login (content type was not JSON).", text ? `Server response: ${text} (status: ${response.status})` : `Status: ${response.status}`);
12456
13751
  }
12457
13752
  const json = await response.json();
12458
- const nonce = json === null || json === void 0 ? void 0 : json.nonce;
12459
- const url = json === null || json === void 0 ? void 0 : json.url;
12460
- if (typeof nonce !== "string" || typeof url !== "string") {
12461
- throw new ValLoginError("unexpected-response", "Unexpected response from the server.", JSON.stringify(json));
13753
+ const deviceCode = json === null || json === void 0 ? void 0 : json.device_code;
13754
+ const userCode = json === null || json === void 0 ? void 0 : json.user_code;
13755
+ const verificationUri = json === null || json === void 0 ? void 0 : json.verification_uri;
13756
+ if (typeof deviceCode !== "string" || typeof userCode !== "string" || typeof verificationUri !== "string") {
13757
+ throw new ValLoginError("unexpected-response", "Unexpected response from the server. This version of Val may be too old for the login flow on this host — try updating @valbuild/cli.", JSON.stringify(json));
12462
13758
  }
12463
13759
  return {
12464
- nonce,
12465
- url
13760
+ deviceCode,
13761
+ userCode,
13762
+ verificationUri,
13763
+ verificationUriComplete: typeof (json === null || json === void 0 ? void 0 : json.verification_uri_complete) === "string" ? json.verification_uri_complete : verificationUri,
13764
+ expiresInSeconds: typeof (json === null || json === void 0 ? void 0 : json.expires_in) === "number" ? json.expires_in : DEFAULT_LOGIN_EXPIRES_IN_SECONDS,
13765
+ intervalSeconds: typeof (json === null || json === void 0 ? void 0 : json.interval) === "number" ? json.interval : DEFAULT_LOGIN_POLL_INTERVAL_SECONDS
12466
13766
  };
12467
13767
  }
12468
- const DEFAULT_LOGIN_MAX_DURATION = 5 * 60 * 1000; // 5 minutes
12469
- const DEFAULT_LOGIN_POLL_INTERVAL = 1000;
13768
+
13769
+ /** Fallbacks for a server that omits the optional RFC 8628 timing fields. */
13770
+ const DEFAULT_LOGIN_EXPIRES_IN_SECONDS = 600;
13771
+ const DEFAULT_LOGIN_POLL_INTERVAL_SECONDS = 5;
12470
13772
 
12471
13773
  /**
12472
- * Poll until the user confirms the login in their browser.
13774
+ * How much to add to the poll interval when the server answers `slow_down`.
13775
+ * RFC 8628 section 3.5 specifies 5 seconds.
13776
+ */
13777
+ const SLOW_DOWN_INCREMENT_SECONDS = 5;
13778
+
13779
+ /**
13780
+ * Poll until the user approves the login in their browser.
12473
13781
  *
12474
13782
  * Accepts an `AbortSignal` so an editor can cancel the flow when the user
12475
- * dismisses the prompt, instead of leaving a poll loop running for 5 minutes.
13783
+ * dismisses the prompt, instead of leaving a poll loop running to expiry.
12476
13784
  */
12477
- async function awaitValLoginConfirmation(nonce, options = {}) {
13785
+ async function awaitValLoginConfirmation(authorization, options = {}) {
12478
13786
  const host = options.host ?? defaultHost();
12479
- const maxDuration = options.maxDurationMs ?? DEFAULT_LOGIN_MAX_DURATION;
12480
- const pollInterval = options.pollIntervalMs ?? DEFAULT_LOGIN_POLL_INTERVAL;
13787
+ const maxDuration = options.maxDurationMs ?? authorization.expiresInSeconds * 1000;
12481
13788
  const now = options.now ?? (() => Date.now());
13789
+ // Mutable: `slow_down` widens it as we go, and never narrows it again.
13790
+ let intervalMs = authorization.intervalSeconds * 1000;
12482
13791
  const start = now();
12483
13792
  while (now() - start < maxDuration) {
12484
13793
  var _options$signal, _options$signal2;
12485
13794
  if ((_options$signal = options.signal) !== null && _options$signal !== void 0 && _options$signal.aborted) {
12486
13795
  throw new ValLoginError("aborted", "Login was cancelled.");
12487
13796
  }
12488
- await new Promise(resolve => setTimeout(resolve, pollInterval));
13797
+ // Wait first: the user has not had time to approve anything yet.
13798
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
12489
13799
  if ((_options$signal2 = options.signal) !== null && _options$signal2 !== void 0 && _options$signal2.aborted) {
12490
13800
  throw new ValLoginError("aborted", "Login was cancelled.");
12491
13801
  }
12492
- const response = await fetch(`${host}/api/login?token=${nonce}&consume=true`, {
12493
- method: "POST"
13802
+ const response = await fetch(`${host}/api/login`, {
13803
+ method: "POST",
13804
+ headers: {
13805
+ "Content-Type": "application/json"
13806
+ },
13807
+ body: JSON.stringify({
13808
+ device_code: authorization.deviceCode
13809
+ })
12494
13810
  });
12495
13811
  if (response.status >= 500) {
12496
13812
  throw new ValLoginError("server-error", "An error occurred on the server.", `Status: ${response.status}`);
@@ -12508,6 +13824,23 @@ async function awaitValLoginConfirmation(nonce, options = {}) {
12508
13824
  }
12509
13825
  throw new ValLoginError("unexpected-response", "Unexpected response from the server.", JSON.stringify(json));
12510
13826
  }
13827
+ const json = await response.json().catch(() => null);
13828
+ const error = typeof (json === null || json === void 0 ? void 0 : json.error) === "string" ? json.error : null;
13829
+ const description = typeof (json === null || json === void 0 ? void 0 : json.error_description) === "string" ? json.error_description : undefined;
13830
+ if (error === "authorization_pending") {
13831
+ continue;
13832
+ }
13833
+ if (error === "slow_down" || response.status === 429) {
13834
+ intervalMs += SLOW_DOWN_INCREMENT_SECONDS * 1000;
13835
+ continue;
13836
+ }
13837
+ if (error === "access_denied") {
13838
+ throw new ValLoginError("access-denied", "The login was declined in the browser.", description);
13839
+ }
13840
+ if (error === "expired_token") {
13841
+ throw new ValLoginError("expired", "The login code expired before it was approved.", description);
13842
+ }
13843
+ throw new ValLoginError("unexpected-response", "Unexpected response from the server.", JSON.stringify(json));
12511
13844
  }
12512
13845
  throw new ValLoginError("timeout", "Login confirmation timed out.");
12513
13846
  }
@@ -12813,9 +14146,9 @@ Object.defineProperty(exports, 'hasRemoteFileSchema', {
12813
14146
  enumerable: true,
12814
14147
  get: function () { return core.hasRemoteFileSchema; }
12815
14148
  });
14149
+ exports.DEFAULT_LOGIN_EXPIRES_IN_SECONDS = DEFAULT_LOGIN_EXPIRES_IN_SECONDS;
12816
14150
  exports.DEFAULT_LOGIN_HOST = DEFAULT_LOGIN_HOST;
12817
- exports.DEFAULT_LOGIN_MAX_DURATION = DEFAULT_LOGIN_MAX_DURATION;
12818
- exports.DEFAULT_LOGIN_POLL_INTERVAL = DEFAULT_LOGIN_POLL_INTERVAL;
14151
+ exports.DEFAULT_LOGIN_POLL_INTERVAL_SECONDS = DEFAULT_LOGIN_POLL_INTERVAL_SECONDS;
12819
14152
  exports.Service = Service;
12820
14153
  exports.ValFSHost = ValFSHost;
12821
14154
  exports.ValLoginError = ValLoginError;
@@ -12835,7 +14168,9 @@ exports.createModulePathMap = createModulePathMap;
12835
14168
  exports.createService = createService;
12836
14169
  exports.createValApiRouter = createValApiRouter;
12837
14170
  exports.createValModuleFileInspector = createValModuleFileInspector;
14171
+ exports.createValOps = createValOps;
12838
14172
  exports.createValServer = createValServer;
14173
+ exports.createValTools = createValTools;
12839
14174
  exports.currentFixHandlers = currentFixHandlers;
12840
14175
  exports.decodeJwtWithoutVerifying = decodeJwtWithoutVerifying;
12841
14176
  exports.describePatchStoreProblems = describePatchStoreProblems;
@@ -12867,6 +14202,7 @@ exports.handleRemoteFileDownload = handleRemoteFileDownload;
12867
14202
  exports.handleRemoteFileUpload = handleRemoteFileUpload;
12868
14203
  exports.handleRemoteGalleryFileUpload = handleRemoteGalleryFileUpload;
12869
14204
  exports.handleUniqueFolderCheck = handleUniqueFolderCheck;
14205
+ exports.initHandlerOptions = initHandlerOptions;
12870
14206
  exports.loadValModules = loadValModules;
12871
14207
  exports.parsePersonalAccessTokenFile = parsePersonalAccessTokenFile;
12872
14208
  exports.patchSourceFile = patchSourceFile;