@selvajs/selva 4.21.0-beta.16 → 4.21.0-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/build/adapter-node.js +2 -2
  2. package/build/client/_app/immutable/assets/21.VfhYpgTQ.css +1 -0
  3. package/build/client/_app/immutable/assets/21.VfhYpgTQ.css.br +0 -0
  4. package/build/client/_app/immutable/assets/21.VfhYpgTQ.css.gz +0 -0
  5. package/build/client/_app/immutable/assets/baseHDR.Dkr46J8-.hdr +0 -0
  6. package/build/client/_app/immutable/chunks/{BWnVNIyV.js → D2C9ht__.js} +1 -1
  7. package/build/client/_app/immutable/chunks/D2C9ht__.js.br +0 -0
  8. package/build/client/_app/immutable/chunks/{BWnVNIyV.js.gz → D2C9ht__.js.gz} +0 -0
  9. package/build/client/_app/immutable/chunks/DIMAEw3m.js +1 -0
  10. package/build/client/_app/immutable/chunks/DIMAEw3m.js.br +1 -0
  11. package/build/client/_app/immutable/chunks/DIMAEw3m.js.gz +0 -0
  12. package/build/client/_app/immutable/chunks/a5NclWb-.js +2 -0
  13. package/build/client/_app/immutable/chunks/a5NclWb-.js.br +0 -0
  14. package/build/client/_app/immutable/chunks/a5NclWb-.js.gz +0 -0
  15. package/build/client/_app/immutable/entry/{app.Dw0M74ME.js → app.D3YN7-nC.js} +2 -2
  16. package/build/client/_app/immutable/entry/app.D3YN7-nC.js.br +0 -0
  17. package/build/client/_app/immutable/entry/app.D3YN7-nC.js.gz +0 -0
  18. package/build/client/_app/immutable/nodes/{20.B2EnikH5.js → 20.B8bN-AYw.js} +1 -1
  19. package/build/client/_app/immutable/nodes/20.B8bN-AYw.js.br +0 -0
  20. package/build/client/_app/immutable/nodes/20.B8bN-AYw.js.gz +0 -0
  21. package/build/client/_app/immutable/nodes/21.BA-9DMG6.js +1 -0
  22. package/build/client/_app/immutable/nodes/21.BA-9DMG6.js.br +0 -0
  23. package/build/client/_app/immutable/nodes/21.BA-9DMG6.js.gz +0 -0
  24. package/build/client/_app/immutable/nodes/{25.C7VDbaM3.js → 25.DbMk0htM.js} +20 -20
  25. package/build/client/_app/immutable/nodes/25.DbMk0htM.js.br +0 -0
  26. package/build/client/_app/immutable/nodes/25.DbMk0htM.js.gz +0 -0
  27. package/build/client/_app/version.json +1 -1
  28. package/build/client/_app/version.json.br +0 -0
  29. package/build/client/_app/version.json.gz +0 -0
  30. package/build/server/.vite/manifest.json +89 -7
  31. package/build/server/_app/immutable/assets/_page.DowU5FoO.css +1 -0
  32. package/build/server/_app/immutable/assets/baseHDR.Dkr46J8-.hdr +0 -0
  33. package/build/server/chunks/DefinitionCard.js +1 -1
  34. package/build/server/chunks/DefinitionCard.js.map +1 -1
  35. package/build/server/chunks/api.js +1 -1
  36. package/build/server/chunks/baseHDR.js +5 -0
  37. package/build/server/chunks/baseHDR.js.map +1 -0
  38. package/build/server/chunks/capture.js +5 -0
  39. package/build/server/chunks/capture.js.map +1 -0
  40. package/build/server/chunks/diff.js +1 -8
  41. package/build/server/chunks/diff.js.map +1 -1
  42. package/build/server/chunks/functions.js +1 -1
  43. package/build/server/chunks/handlers.js +71 -25
  44. package/build/server/chunks/handlers.js.map +1 -1
  45. package/build/server/chunks/instance.js +5 -5
  46. package/build/server/chunks/instanceAdmins.server.js +1 -1
  47. package/build/server/chunks/internal.js +3 -3
  48. package/build/server/chunks/inventory.js +59 -16
  49. package/build/server/chunks/inventory.js.map +1 -1
  50. package/build/server/chunks/package.js +2 -1
  51. package/build/server/chunks/package.js.map +1 -1
  52. package/build/server/chunks/path.js +7 -0
  53. package/build/server/chunks/path.js.map +1 -0
  54. package/build/server/chunks/presets.server.js +1 -1
  55. package/build/server/chunks/providers.server.js +21 -12
  56. package/build/server/chunks/providers.server.js.map +1 -1
  57. package/build/server/chunks/registry.js +18 -3
  58. package/build/server/chunks/registry.js.map +1 -1
  59. package/build/server/chunks/remote.js +1559 -0
  60. package/build/server/chunks/remote.js.map +1 -0
  61. package/build/server/chunks/rhino3dm.js.map +1 -1
  62. package/build/server/chunks/server-errors.js +19 -1
  63. package/build/server/chunks/server-errors.js.map +1 -1
  64. package/build/server/chunks/server5.js +52 -0
  65. package/build/server/chunks/server5.js.map +1 -0
  66. package/build/server/chunks/solve.js +5 -0
  67. package/build/server/chunks/solve.js.map +1 -0
  68. package/build/server/chunks/stash-instance.js +94 -0
  69. package/build/server/chunks/stash-instance.js.map +1 -0
  70. package/build/server/chunks/sveltekit.js +2 -1
  71. package/build/server/chunks/sveltekit.js.map +1 -1
  72. package/build/server/chunks/types4.js +10 -0
  73. package/build/server/chunks/types4.js.map +1 -0
  74. package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +1 -1
  75. package/build/server/entries/endpoints/api/v1/definitions/_guid_/_server.ts.js +1 -1
  76. package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js +3 -2
  77. package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js.map +1 -1
  78. package/build/server/entries/endpoints/api/v1/definitions/_guid_/publish/_server.ts.js +1 -1
  79. package/build/server/entries/endpoints/api/v1/definitions/_guid_/schema/_server.ts.js +1 -1
  80. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_linkId_/_server.ts.js +1 -1
  81. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_server.ts.js +1 -1
  82. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_server.ts.js +1 -1
  83. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/_server.ts.js +1 -1
  84. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/changes/_server.ts.js +1 -1
  85. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/inventory/_server.ts.js +1 -1
  86. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/schema/_server.ts.js +1 -1
  87. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/scripts/_scriptId_/_server.ts.js +1 -1
  88. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/check/_server.ts.js +1 -1
  89. package/build/server/entries/endpoints/api/v1/definitions/_server.ts.js +1 -1
  90. package/build/server/entries/endpoints/api/v1/me/_server.ts.js +1 -1
  91. package/build/server/entries/endpoints/api/v1/me/starred/_guid_/_server.ts.js +1 -1
  92. package/build/server/entries/endpoints/api/v1/me/token/_server.ts.js +1 -1
  93. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/_server.ts.js +1 -1
  94. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/assets/_kind_/_server.ts.js +1 -1
  95. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_server.ts.js +1 -1
  96. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_userId_/_server.ts.js +1 -1
  97. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_server.ts.js +1 -1
  98. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_tokenId_/_server.ts.js +1 -1
  99. package/build/server/entries/endpoints/api/v1/projects/_id_/reclaim/_server.ts.js +1 -1
  100. package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
  101. package/build/server/entries/endpoints/mcp/_server.ts.js +1085 -91
  102. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  103. package/build/server/entries/endpoints/mcp/files/_token_/_name_/_server.ts.js +18 -0
  104. package/build/server/entries/endpoints/mcp/files/_token_/_name_/_server.ts.js.map +1 -0
  105. package/build/server/entries/hooks.server.js +8 -3
  106. package/build/server/entries/hooks.server.js.map +1 -1
  107. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  108. package/build/server/entries/pages/projects/_page.svelte.js +12 -6
  109. package/build/server/entries/pages/projects/_page.svelte.js.map +1 -1
  110. package/build/server/entries/pages/team/tokens/_page.server.ts.js +1 -1
  111. package/build/server/index.js +1 -1
  112. package/build/server/manifest-full.js +8 -1
  113. package/build/server/manifest.js +8 -1
  114. package/build/server/nodes/20.js +1 -1
  115. package/build/server/nodes/21.js +2 -2
  116. package/build/server/nodes/25.js +1 -1
  117. package/build/server/remote-entry.js +1 -1559
  118. package/build/server/server.js +8 -1
  119. package/package.json +10 -9
  120. package/templates/.env.example +6 -0
  121. package/build/client/_app/immutable/assets/21.DDgTnace.css +0 -1
  122. package/build/client/_app/immutable/assets/21.DDgTnace.css.br +0 -0
  123. package/build/client/_app/immutable/assets/21.DDgTnace.css.gz +0 -0
  124. package/build/client/_app/immutable/chunks/BWnVNIyV.js.br +0 -0
  125. package/build/client/_app/immutable/chunks/Cj8nqfNF.js +0 -1
  126. package/build/client/_app/immutable/chunks/Cj8nqfNF.js.br +0 -1
  127. package/build/client/_app/immutable/chunks/Cj8nqfNF.js.gz +0 -0
  128. package/build/client/_app/immutable/chunks/Cv7GBWJh.js +0 -2
  129. package/build/client/_app/immutable/chunks/Cv7GBWJh.js.br +0 -0
  130. package/build/client/_app/immutable/chunks/Cv7GBWJh.js.gz +0 -0
  131. package/build/client/_app/immutable/entry/app.Dw0M74ME.js.br +0 -0
  132. package/build/client/_app/immutable/entry/app.Dw0M74ME.js.gz +0 -0
  133. package/build/client/_app/immutable/nodes/20.B2EnikH5.js.br +0 -0
  134. package/build/client/_app/immutable/nodes/20.B2EnikH5.js.gz +0 -0
  135. package/build/client/_app/immutable/nodes/21.-ms9uSQh.js +0 -1
  136. package/build/client/_app/immutable/nodes/21.-ms9uSQh.js.br +0 -0
  137. package/build/client/_app/immutable/nodes/21.-ms9uSQh.js.gz +0 -0
  138. package/build/client/_app/immutable/nodes/25.C7VDbaM3.js.br +0 -0
  139. package/build/client/_app/immutable/nodes/25.C7VDbaM3.js.gz +0 -0
  140. package/build/server/_app/immutable/assets/_page.l97MEw0G.css +0 -1
  141. package/build/server/remote-entry.js.map +0 -1
@@ -2,13 +2,19 @@ import { f as getLogger } from "../../../chunks/providers.server.js";
2
2
  import { n as env } from "../../../chunks/previous-key.js";
3
3
  import { H as apiScopeActionCovers } from "../../../chunks/access.js";
4
4
  import { n as ApiScopeActionSchema, o as parseApiScope } from "../../../chunks/types.js";
5
+ import { i as inventoryWarningText, r as inventoryDiffToMarkdown } from "../../../chunks/inventory.js";
5
6
  import { r as GuidSchema } from "../../../chunks/schemas.js";
6
- import { n as getInputItems } from "../../../chunks/traversal.js";
7
+ import { q as ProjectVisibilitySchema } from "../../../chunks/api.js";
8
+ import { r as getLayoutItems, t as getGroups } from "../../../chunks/traversal.js";
9
+ import { n as schemaDiffToMarkdown } from "../../../chunks/diff.js";
7
10
  import { s as resourceMetadataUrl } from "../../../chunks/oauth.js";
8
11
  import { i as oauthServer } from "../../../chunks/server2.js";
9
12
  import { t as publicUrl } from "../../../chunks/origin.js";
10
13
  import { t as buildOpenApiDocument } from "../../../chunks/openapi.js";
14
+ import { t as MCP_FILES_PREFIX } from "../../../chunks/path.js";
15
+ import { i as jsonBytes, r as fromJsonBytes, t as mcpStash } from "../../../chunks/stash-instance.js";
11
16
  import { z } from "zod";
17
+ import { readFile } from "node:fs/promises";
12
18
  import * as z$1 from "zod/v4";
13
19
  import process$1 from "node:process";
14
20
  // ../../node_modules/.pnpm/@modelcontextprotocol+server@2.4.0/node_modules/@modelcontextprotocol/server/dist/chunk-vYduTEsO.mjs
@@ -20356,7 +20362,8 @@ function createApiClient(index, options, allowed) {
20356
20362
  Authorization: `Bearer ${options.apiKey}`,
20357
20363
  Accept: "application/json"
20358
20364
  };
20359
- if (args.body !== void 0) headers["Content-Type"] = "application/json";
20365
+ const form = args.body instanceof FormData;
20366
+ if (args.body !== void 0 && !form) headers["Content-Type"] = "application/json";
20360
20367
  if (op.idempotent) headers["Idempotency-Key"] = crypto.randomUUID();
20361
20368
  const timeoutMs = args.timeoutMs ?? (op.scope === "solve" || op.longRunning ? options.solveTimeoutMs ?? 3e5 : options.timeoutMs ?? 3e4);
20362
20369
  const canRetryNetwork = op.idempotent || op.method === "GET";
@@ -20372,7 +20379,7 @@ function createApiClient(index, options, allowed) {
20372
20379
  method: op.method,
20373
20380
  headers,
20374
20381
  credentials: "omit",
20375
- body: args.body === void 0 ? void 0 : JSON.stringify(args.body),
20382
+ body: args.body === void 0 ? void 0 : form ? args.body : JSON.stringify(args.body),
20376
20383
  signal
20377
20384
  });
20378
20385
  } catch (err) {
@@ -20392,7 +20399,7 @@ function createApiClient(index, options, allowed) {
20392
20399
  }
20393
20400
  if (!res.ok) throw await toError(operationId, res);
20394
20401
  tally.status = res.status;
20395
- return readBody(res);
20402
+ return readBody(res, args.bytes);
20396
20403
  }
20397
20404
  }
20398
20405
  return { call };
@@ -20413,14 +20420,21 @@ function queryString(query) {
20413
20420
  const s = search.toString();
20414
20421
  return s ? `?${s}` : "";
20415
20422
  }
20416
- async function readBody(res) {
20423
+ async function readBody(res, keepBytes = false) {
20417
20424
  if (res.status === 204) return void 0;
20418
20425
  const type = res.headers.get("Content-Type") ?? "";
20419
20426
  if (type.includes("json")) return res.json();
20427
+ const data = new Uint8Array(await res.arrayBuffer());
20428
+ if (keepBytes) return {
20429
+ binary: true,
20430
+ contentType: type,
20431
+ bytes: data.byteLength,
20432
+ data
20433
+ };
20420
20434
  return {
20421
20435
  binary: true,
20422
20436
  contentType: type,
20423
- bytes: (await res.arrayBuffer()).byteLength
20437
+ bytes: data.byteLength
20424
20438
  };
20425
20439
  }
20426
20440
  async function toError(operationId, res, retryAfter) {
@@ -20452,6 +20466,27 @@ function errorText(err) {
20452
20466
  // ../mcp/src/app.ts
20453
20467
  /** The MIME type a client renders as an MCP App view rather than reading as text. */
20454
20468
  var MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
20469
+ /** The `extensions` key under which a client declares that it renders MCP App views. */
20470
+ var MCP_APP_EXTENSION = "io.modelcontextprotocol/ui";
20471
+ /** A view for tools to name in `ui.resourceUri`. It reads no `/api/v1`; its tools do. */
20472
+ function appResource(options) {
20473
+ const { uri, name, description, html, csp, prefersBorder } = options;
20474
+ const ui = {
20475
+ ...csp && { csp },
20476
+ ...prefersBorder !== void 0 && { prefersBorder }
20477
+ };
20478
+ return {
20479
+ uri,
20480
+ name,
20481
+ description,
20482
+ mimeType: MCP_APP_MIME_TYPE,
20483
+ ...Object.keys(ui).length > 0 && { meta: { ui } },
20484
+ calls: [],
20485
+ read: async () => html()
20486
+ };
20487
+ }
20488
+ /** Where a solve view reads its data in a tool result's `_meta`. */
20489
+ var SOLVE_VIEW_KEY = "selva/solve-view";
20455
20490
  // ../mcp/src/spec.ts
20456
20491
  var METHODS = /* @__PURE__ */ new Set([
20457
20492
  "get",
@@ -20658,6 +20693,11 @@ var TOOLS_LIST_CACHE = {
20658
20693
  ttlMs: 3e5,
20659
20694
  cacheScope: "private"
20660
20695
  };
20696
+ function rendersApps(capabilities) {
20697
+ if (!capabilities) return true;
20698
+ const { extensions } = capabilities;
20699
+ return !!extensions?.[MCP_APP_EXTENSION]?.mimeTypes?.includes(MCP_APP_MIME_TYPE);
20700
+ }
20661
20701
  function createMcpServer(options) {
20662
20702
  const spec = indexOperations(options.openapi);
20663
20703
  const tools = resolveTools(options.tools, spec);
@@ -20759,7 +20799,8 @@ function createMcpServer(options) {
20759
20799
  const args = resolved.input.parse(req.params.arguments ?? {});
20760
20800
  const out = await resolved.def.run(api, args, {
20761
20801
  signal: ctx.mcpReq.signal,
20762
- spec
20802
+ spec,
20803
+ apps: rendersApps(server.getClientCapabilities())
20763
20804
  });
20764
20805
  result = toResult(typeof out === "string" ? { text: out } : out, !!resolved.output);
20765
20806
  return result;
@@ -21057,39 +21098,109 @@ function describe(err, hint) {
21057
21098
  ].join("\n");
21058
21099
  return err instanceof Error ? err.message : String(err);
21059
21100
  }
21101
+ // ../mcp/src/views.ts
21102
+ var SOLVE_VIEW_URI = "ui://selva/solve.html";
21060
21103
  new URL("../dist/views/solve.html", import.meta.url);
21061
- // src/lib/server/mcp/tools.ts
21104
+ // ../mcp/src/capture.ts
21105
+ /** Thrown when no browser can be launched; its message says how to install one. */
21106
+ var CaptureUnavailableError = class extends Error {
21107
+ name = "CaptureUnavailableError";
21108
+ };
21109
+ var CAPTURE_FILE = new URL("../dist/views/capture.html", import.meta.url);
21110
+ var ARGS = [
21111
+ "--use-angle=swiftshader",
21112
+ "--enable-unsafe-swiftshader",
21113
+ "--ignore-gpu-blocklist"
21114
+ ];
21115
+ var IDLE_CLOSE_MS = 12e4;
21116
+ var browser;
21117
+ var idle;
21118
+ var queue = Promise.resolve();
21119
+ async function launch(executablePath, timeout) {
21120
+ const name = "playwright-core";
21121
+ let chromium;
21122
+ try {
21123
+ ({chromium} = await import(
21124
+ /* @vite-ignore */
21125
+ name
21126
+ ));
21127
+ } catch {
21128
+ throw new CaptureUnavailableError("Rendering needs the `playwright-core` package on the server, which is not installed.");
21129
+ }
21130
+ try {
21131
+ const launched = await chromium.launch({
21132
+ executablePath,
21133
+ args: ARGS,
21134
+ timeout
21135
+ });
21136
+ launched.on("disconnected", () => browser = void 0);
21137
+ return launched;
21138
+ } catch (err) {
21139
+ throw new CaptureUnavailableError(`No browser to render with: ${err instanceof Error ? err.message.split("\n")[0] : String(err)}. Install one on the server with \`npx playwright install --with-deps chromium\`, or point the server at an existing Chromium.`);
21140
+ }
21141
+ }
21062
21142
  /**
21063
- * Selva's MCP tools: find a definition, read its inputs, solve it, read back numbers,
21064
- * publish a version. No deletes, share links, tokens or admin.
21143
+ * Draws a Rhino.Compute response in Selva's viewer, in a headless Chromium, and returns a PNG.
21144
+ * Needs `playwright-core` and a Chromium on the machine; throws {@link CaptureUnavailableError}
21145
+ * without them.
21065
21146
  */
21066
- var NAME_LOOKUP_PAGES = 5;
21067
- var definitionArg = z.string().describe("A guid from selva_list_definitions, or the exact display name.");
21068
- async function resolveDefinition(api, definition, signal) {
21069
- const guid = GuidSchema.safeParse(definition);
21070
- if (guid.success) return guid.data;
21071
- const wanted = definition.trim().toLowerCase();
21072
- const matches = [];
21073
- let cursor;
21074
- for (let page = 0; page < NAME_LOOKUP_PAGES; page++) {
21075
- const res = await api.call("getDefinitions", {
21076
- query: {
21077
- limit: 100,
21078
- cursor
21079
- },
21080
- signal
21147
+ function captureSolve(response, options = {}) {
21148
+ const { signal } = options;
21149
+ const run = queue.then(() => {
21150
+ signal?.throwIfAborted();
21151
+ return capture(response, options);
21152
+ });
21153
+ queue = run.catch(() => {});
21154
+ if (!signal) return run;
21155
+ return new Promise((resolve, reject) => {
21156
+ const onAbort = () => reject(signal.reason);
21157
+ if (signal.aborted) return onAbort();
21158
+ signal.addEventListener("abort", onAbort, { once: true });
21159
+ run.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
21160
+ });
21161
+ }
21162
+ async function capture(response, options) {
21163
+ const timeout = options.timeoutMs ?? 6e4;
21164
+ clearTimeout(idle);
21165
+ browser ??= launch(options.executablePath, timeout).catch((err) => {
21166
+ browser = void 0;
21167
+ throw err;
21168
+ });
21169
+ const html = await (options.html ?? (() => readFile(CAPTURE_FILE, "utf8")))();
21170
+ const page = await (await browser).newPage({ deviceScaleFactor: 1 });
21171
+ const closePage = () => void page.close().catch(() => {});
21172
+ options.signal?.addEventListener("abort", closePage, { once: true });
21173
+ try {
21174
+ options.signal?.throwIfAborted();
21175
+ page.setDefaultTimeout(timeout);
21176
+ await page.setViewportSize({
21177
+ width: options.width ?? 1200,
21178
+ height: options.height ?? 800
21081
21179
  });
21082
- matches.push(...res.items.filter((d) => d.displayName.trim().toLowerCase() === wanted));
21083
- cursor = res.nextCursor;
21084
- if (!cursor) break;
21180
+ await page.setContent(html, { waitUntil: "load" });
21181
+ const hdr = options.hdr ? await options.hdr() : void 0;
21182
+ return await page.evaluate((req) => globalThis.selvaCapture(req), {
21183
+ response,
21184
+ view: options.view ?? "iso",
21185
+ grid: options.grid ?? true,
21186
+ look: options.look,
21187
+ background: options.background,
21188
+ hdr
21189
+ });
21190
+ } finally {
21191
+ options.signal?.removeEventListener("abort", closePage);
21192
+ await page.close().catch(() => {});
21193
+ idle = setTimeout(() => {
21194
+ const open = browser;
21195
+ browser = void 0;
21196
+ open?.then((b) => b.close()).catch(() => {});
21197
+ }, IDLE_CLOSE_MS);
21198
+ idle.unref?.();
21085
21199
  }
21086
- if (matches.length === 1) return matches[0].guid;
21087
- if (!matches.length) throw new Error(`No definition is named "${definition}". Call selva_list_definitions and pass a guid.`);
21088
- const lines = matches.map((d) => `- ${d.displayName} (guid ${d.guid})`);
21089
- throw new Error([`${matches.length} definitions are named "${definition}"; pass one guid:`, ...lines].join("\n"));
21090
21200
  }
21201
+ // src/lib/server/mcp/form.ts
21091
21202
  function describeInputs(schema) {
21092
- const items = getInputItems(schema);
21203
+ const items = getLayoutItems(schema).filter((i) => i.type === "input");
21093
21204
  return schema.inputs.map((input) => {
21094
21205
  const item = items.find((i) => i.paramId === input.id);
21095
21206
  return {
@@ -21104,7 +21215,40 @@ function optionsOf(item) {
21104
21215
  if (item.widgetType === "dropdown") return item.config?.options;
21105
21216
  if (item.widgetType === "dynamicValueList") return item.config?.defaultOptions;
21106
21217
  }
21107
- function inputLine({ input, item, label }) {
21218
+ function unitOf(item) {
21219
+ return item?.widgetType === "number" ? item.config?.unit || void 0 : void 0;
21220
+ }
21221
+ var OPERATORS = {
21222
+ equals: "is",
21223
+ notEquals: "is not",
21224
+ greaterThan: ">",
21225
+ lessThan: "<",
21226
+ greaterThanOrEqual: "≥",
21227
+ lessThanOrEqual: "≤",
21228
+ in: "is one of",
21229
+ notIn: "is none of",
21230
+ between: "is between",
21231
+ matches: "matches",
21232
+ contains: "contains",
21233
+ containsAny: "contains any of",
21234
+ isEmpty: "is empty",
21235
+ isNotEmpty: "is not empty"
21236
+ };
21237
+ /** "shown only when "Shape" is "Round"", in the labels the model sees. */
21238
+ function conditionText(condition, labelOf) {
21239
+ if (!condition?.rules?.length) return void 0;
21240
+ const joined = condition.rules.map((r) => {
21241
+ const operator = OPERATORS[r.operator] ?? r.operator;
21242
+ const value = r.values ?? r.value;
21243
+ const shown = value === void 0 ? "" : ` ${JSON.stringify(value)}`;
21244
+ return `"${labelOf(r.paramId)}" ${operator}${shown}`;
21245
+ }).join(condition.mode === "any" ? " or " : " and ");
21246
+ const action = condition.action ?? "show";
21247
+ if (action === "hide") return `hidden when ${joined}`;
21248
+ if (action === "disable") return `disabled when ${joined}`;
21249
+ return `shown only when ${joined}`;
21250
+ }
21251
+ function inputLine({ input, item, label }, labelOf) {
21108
21252
  const parts = [`- "${label}" (id ${input.id}): ${input.paramType}`];
21109
21253
  if (input.inputStructure && input.inputStructure !== "item") parts.push(`, ${input.inputStructure} of them`);
21110
21254
  if (item?.widgetType === "number") {
@@ -21112,25 +21256,84 @@ function inputLine({ input, item, label }) {
21112
21256
  if (minimum !== void 0 || maximum !== void 0) parts.push(`, ${minimum ?? "…"} to ${maximum ?? "…"}`);
21113
21257
  if (stepSize !== void 0) parts.push(`, step ${stepSize}`);
21114
21258
  }
21259
+ const unit = unitOf(item);
21260
+ if (unit) parts.push(`, in ${unit}`);
21261
+ if (item?.widgetType === "text" && item.config?.maxLength) parts.push(`, at most ${item.config.maxLength} characters`);
21262
+ if (item?.widgetType === "checkbox" && item.config?.displayAs === "button") parts.push(", a button: true runs it once");
21115
21263
  const options = optionsOf(item);
21116
21264
  if (options) parts.push(`, one of: ${Object.keys(options).map((k) => `"${k}"`).join(", ")}`);
21117
21265
  if (input.default !== void 0) parts.push(`, default ${JSON.stringify(input.default)}`);
21266
+ const condition = conditionText(item?.visibilityCondition, labelOf);
21267
+ if (condition) parts.push(`, ${condition}`);
21268
+ if (item?.visible === false) parts.push(", hidden in the form");
21118
21269
  const description = item?.description || input.description;
21119
21270
  if (description) parts.push(`. ${description}`);
21120
21271
  return parts.join("");
21121
21272
  }
21273
+ function outputLine(schema, item, id) {
21274
+ const output = schema.outputs.find((o) => o.id === id);
21275
+ if (!output) return null;
21276
+ const label = item && "displayName" in item && item.displayName || output.nickname;
21277
+ const name = label === output.nickname ? `"${label}"` : `"${output.nickname}" (shown as ${label})`;
21278
+ const description = item && "description" in item && item.description || output.description;
21279
+ return `- ${name}: ${output.type}${description ? `. ${description}` : ""}`;
21280
+ }
21281
+ /**
21282
+ * Inputs and outputs under their form groups, each group with its description, so the model
21283
+ * reads them as a person filling the form would.
21284
+ */
21285
+ function formText(schema) {
21286
+ const described = describeInputs(schema);
21287
+ const labelOf = (id) => described.find((d) => d.input.id === id)?.label ?? id;
21288
+ const lines = [];
21289
+ const placedInputs = /* @__PURE__ */ new Set();
21290
+ const placedOutputs = /* @__PURE__ */ new Set();
21291
+ const groupBlock = (group) => {
21292
+ const inputs = [];
21293
+ const outputs = [];
21294
+ for (const item of group.items ?? []) if (item.type === "input" && item.paramId) {
21295
+ const d = described.find((x) => x.input.id === item.paramId);
21296
+ if (!d) continue;
21297
+ placedInputs.add(d.input.id);
21298
+ inputs.push(inputLine(d, labelOf));
21299
+ } else if (item.type === "output" && item.paramId) {
21300
+ const line = outputLine(schema, item, item.paramId);
21301
+ if (!line) continue;
21302
+ placedOutputs.add(item.paramId);
21303
+ outputs.push(line);
21304
+ }
21305
+ if (!inputs.length && !outputs.length) return;
21306
+ const condition = conditionText(group.visibilityCondition, labelOf);
21307
+ lines.push("", `## ${group.label || "Untitled group"}${condition ? ` (${condition})` : ""}`);
21308
+ if (group.description) lines.push(group.description);
21309
+ if (inputs.length) lines.push("Inputs:", ...inputs);
21310
+ if (outputs.length) lines.push("Outputs:", ...outputs);
21311
+ };
21312
+ for (const group of getGroups(schema)) groupBlock(group);
21313
+ const looseInputs = described.filter((d) => !placedInputs.has(d.input.id));
21314
+ if (looseInputs.length) lines.push("", "## Not on the form", "Inputs:", ...looseInputs.map((d) => inputLine(d, labelOf)));
21315
+ const looseOutputs = schema.outputs.filter((o) => !placedOutputs.has(o.id)).map((o) => outputLine(schema, void 0, o.id));
21316
+ if (looseOutputs.length) lines.push("", "Other outputs:", ...looseOutputs);
21317
+ return lines;
21318
+ }
21122
21319
  /** Values keyed by what the model saw: label, nickname or id. Dropdown labels become their values. */
21123
21320
  function resolveValues(described, given) {
21124
21321
  const values = {};
21125
21322
  const unknown = [];
21126
21323
  for (const [key, value] of Object.entries(given)) {
21127
- const match = described.find((d) => d.input.id === key || d.label === key || d.input.nickname === key);
21324
+ const byId = described.find((d) => d.input.id === key);
21325
+ const byName = described.filter((d) => d.label === key || d.input.nickname === key);
21326
+ if (!byId && byName.length > 1) {
21327
+ const ids = byName.map((d) => d.input.id).join(", ");
21328
+ throw new Error(`"${key}" names more than one input; pass one of their ids: ${ids}.`);
21329
+ }
21330
+ const match = byId ?? byName[0];
21128
21331
  if (!match) {
21129
21332
  unknown.push(key);
21130
21333
  continue;
21131
21334
  }
21132
21335
  const options = optionsOf(match.item);
21133
- const pick = (v) => typeof v === "string" && options?.[v] !== void 0 ? options[v] : v;
21336
+ const pick = (v) => typeof v === "string" && options && Object.hasOwn(options, v) && options[v] !== void 0 ? options[v] : v;
21134
21337
  values[match.input.id] = Array.isArray(value) ? value.map(pick) : pick(value);
21135
21338
  }
21136
21339
  if (unknown.length) {
@@ -21139,6 +21342,147 @@ function resolveValues(described, given) {
21139
21342
  }
21140
21343
  return values;
21141
21344
  }
21345
+ /**
21346
+ * One control per single-value input the view can edit, keyed by label as `selva_solve` takes
21347
+ * them, holding `given` where the model set it and the default otherwise. Geometry, files,
21348
+ * colours and lists stay as the definition has them.
21349
+ */
21350
+ function viewInputs(schema, given) {
21351
+ const inputs = [];
21352
+ for (const d of describeInputs(schema)) {
21353
+ const { input, item, label } = d;
21354
+ if (input.inputStructure && input.inputStructure !== "item") continue;
21355
+ if (item?.visible === false) continue;
21356
+ const value = given[label] ?? given[input.nickname] ?? given[input.id] ?? input.default;
21357
+ const description = item?.description || input.description || void 0;
21358
+ const options = optionsOf(item);
21359
+ if (options) {
21360
+ const names = Object.keys(options);
21361
+ const name = names.find((n) => n === value) ?? names.find((n) => options[n] === value);
21362
+ inputs.push({
21363
+ name: label,
21364
+ kind: "choice",
21365
+ options: names,
21366
+ value: name,
21367
+ description
21368
+ });
21369
+ continue;
21370
+ }
21371
+ if (input.paramType === "number" || input.paramType === "integer") {
21372
+ const config = item?.widgetType === "number" ? item.config : void 0;
21373
+ inputs.push({
21374
+ name: label,
21375
+ kind: "number",
21376
+ value,
21377
+ min: config?.minimum,
21378
+ max: config?.maximum,
21379
+ step: config?.stepSize ?? (input.paramType === "integer" ? 1 : void 0),
21380
+ unit: config?.unit || void 0,
21381
+ description
21382
+ });
21383
+ } else if (input.paramType === "boolean") {
21384
+ if (item?.widgetType === "checkbox" && item.config?.displayAs === "button") continue;
21385
+ inputs.push({
21386
+ name: label,
21387
+ kind: "boolean",
21388
+ value: value === true,
21389
+ description
21390
+ });
21391
+ } else if (input.paramType === "text") inputs.push({
21392
+ name: label,
21393
+ kind: "text",
21394
+ value,
21395
+ description
21396
+ });
21397
+ }
21398
+ return inputs;
21399
+ }
21400
+ // src/lib/server/mcp/lookup.ts
21401
+ var NAME_LOOKUP_PAGES = 5;
21402
+ var definitionArg = z.string().describe("A guid from selva_list_definitions, or the exact display name.");
21403
+ var projectArg = z.string().describe("A project id from selva_list_projects, or the exact project name.");
21404
+ var versionArg = z.string().optional().describe("`live` (the default), `draft` for the newest upload that is not live yet, or a version id from selva_list_versions.");
21405
+ async function findByName(api, operationId, signal, matches) {
21406
+ const found = [];
21407
+ let cursor;
21408
+ for (let page = 0; page < NAME_LOOKUP_PAGES; page++) {
21409
+ const res = await api.call(operationId, {
21410
+ query: {
21411
+ limit: 100,
21412
+ cursor
21413
+ },
21414
+ signal
21415
+ });
21416
+ found.push(...res.items.filter(matches));
21417
+ cursor = res.nextCursor;
21418
+ if (!cursor) break;
21419
+ }
21420
+ return found;
21421
+ }
21422
+ async function resolveDefinition(api, definition, signal) {
21423
+ const guid = GuidSchema.safeParse(definition);
21424
+ if (guid.success) return guid.data;
21425
+ const wanted = definition.trim().toLowerCase();
21426
+ const matches = await findByName(api, "getDefinitions", signal, (d) => d.displayName.trim().toLowerCase() === wanted);
21427
+ if (matches.length === 1) return matches[0].guid;
21428
+ if (!matches.length) throw new Error(`No definition is named "${definition}". Call selva_list_definitions and pass a guid.`);
21429
+ const lines = matches.map((d) => `- ${d.displayName} (guid ${d.guid})`);
21430
+ throw new Error([`${matches.length} definitions are named "${definition}"; pass one guid:`, ...lines].join("\n"));
21431
+ }
21432
+ async function resolveProject(api, project, signal) {
21433
+ const wanted = project.trim().toLowerCase();
21434
+ const matches = await findByName(api, "getProjects", signal, (p) => p.id.toLowerCase() === wanted || p.name.trim().toLowerCase() === wanted);
21435
+ const byId = matches.find((p) => p.id.toLowerCase() === wanted);
21436
+ if (byId) return byId;
21437
+ if (matches.length === 1) return matches[0];
21438
+ if (!matches.length) throw new Error(`No project is named "${project}". Call selva_list_projects and pass an id.`);
21439
+ const lines = matches.map((p) => `- ${p.name} (id ${p.id})`);
21440
+ throw new Error([`${matches.length} projects are named "${project}"; pass one id:`, ...lines].join("\n"));
21441
+ }
21442
+ function getRecord(api, guid, signal) {
21443
+ return api.call("getDefinitionsByGuid", {
21444
+ params: { guid },
21445
+ signal
21446
+ });
21447
+ }
21448
+ /** `live` and `draft` by the record's pointers; anything else is taken as a version id. */
21449
+ function pickVersion(record, version = "live") {
21450
+ if (version === "live") {
21451
+ if (!record.liveVersion) throw new Error(`${record.displayName} has no live version. Pass version: 'draft' to use the newest upload.`);
21452
+ return record.liveVersion;
21453
+ }
21454
+ if (version === "draft") {
21455
+ const draft = record.draftVersion ?? record.liveVersion;
21456
+ if (!draft) throw new Error(`${record.displayName} has no uploaded version.`);
21457
+ return draft;
21458
+ }
21459
+ return [record.liveVersion, record.draftVersion].find((v) => v?.id === version) ?? {
21460
+ id: version,
21461
+ versionNumber: 0
21462
+ };
21463
+ }
21464
+ function versionLabel(record, v) {
21465
+ const number = v.versionNumber ? `version ${v.versionNumber}` : `version ${v.id}`;
21466
+ if (v.id === record.liveVersion?.id) return `${number} (live)`;
21467
+ if (v.id === record.draftVersion?.id) return `${number} (uploaded, not live)`;
21468
+ return number;
21469
+ }
21470
+ /**
21471
+ * `status` only says whether the library lists the definition; what solves is the live version.
21472
+ * A fresh upload is both live and `draft`, so models read `draft` as "can't run" unless told.
21473
+ */
21474
+ function channelText(r) {
21475
+ const parts = [r.liveVersion ? `Version ${r.liveVersion.versionNumber} is live: solves run it.` : "No version is live; only `version: draft` solves it."];
21476
+ if (r.draftVersion && r.draftVersion.id !== r.liveVersion?.id) parts.push(`Version ${r.draftVersion.versionNumber} is uploaded but not live: solve it with \`version: 'draft'\`, make it live with selva_publish_definition.`);
21477
+ parts.push(listedText(r.status));
21478
+ return parts.join(" ");
21479
+ }
21480
+ function listedText(status) {
21481
+ if (status === "published") return "The library lists it.";
21482
+ if (status === "archived") return "It is archived: the library hides it.";
21483
+ return "The library does not list it until it is published; that does not stop solves.";
21484
+ }
21485
+ // src/lib/server/mcp/solve-output.ts
21142
21486
  var MAX_SCALARS = 50;
21143
21487
  var SCALAR = /^System\.(Double|Single|Int16|Int32|Int64|Decimal|String|Boolean)$/;
21144
21488
  var MESH = "Rhino.Geometry.Mesh";
@@ -21175,19 +21519,42 @@ async function meshVertexCount(items) {
21175
21519
  }
21176
21520
  return total;
21177
21521
  }
21178
- /** `name.ext` per file item; the payload keys are PascalCase or camelCase depending on the serializer. */
21179
- function fileNames(items) {
21180
- return items.filter((i) => i.type === FILE).map((i) => {
21181
- const f = parseItem(i.data);
21182
- const name = f?.FileName ?? f?.fileName;
21183
- const ext = f?.FileType ?? f?.fileType;
21184
- return typeof name === "string" ? name + (typeof ext === "string" ? ext : "") : "unnamed";
21185
- });
21522
+ /** Each file item, held for download; the payload keys are PascalCase or camelCase depending on the serializer. */
21523
+ async function fileLinks(items, origin, stash) {
21524
+ const links = [];
21525
+ for (const i of items.filter((x) => x.type === FILE)) {
21526
+ const f = parseItem(i.data) ?? {};
21527
+ const field = (pascal) => f[pascal] ?? f[pascal[0].toLowerCase() + pascal.slice(1)];
21528
+ const base = field("FileName");
21529
+ const ext = field("FileType");
21530
+ const name = (typeof base === "string" && base ? base : "unnamed") + (typeof ext === "string" ? ext : "");
21531
+ const raw = field("Data");
21532
+ const text = typeof raw === "string" ? raw : "";
21533
+ const data = field("IsBase64Encoded") === true ? Buffer.from(text, "base64") : Buffer.from(text, "utf8");
21534
+ const token = await stash.put({
21535
+ kind: "file",
21536
+ name,
21537
+ contentType: "application/octet-stream",
21538
+ data: new Uint8Array(data)
21539
+ });
21540
+ links.push({
21541
+ name,
21542
+ bytes: data.byteLength,
21543
+ url: `${origin}${MCP_FILES_PREFIX}${token}/${encodeURIComponent(name)}`
21544
+ });
21545
+ }
21546
+ return links;
21547
+ }
21548
+ function sizeText(bytes) {
21549
+ if (bytes < 1024) return `${bytes} B`;
21550
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
21551
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
21186
21552
  }
21187
- async function summarizeSolve(res, schema, link) {
21553
+ async function summarizeSolve(res, schema, options) {
21188
21554
  const lines = [];
21189
21555
  const structured = {};
21190
21556
  const declared = new Map(schema.outputs.map((o) => [o.nickname, o.type]));
21557
+ let anyFiles = false;
21191
21558
  for (const tree of res.values ?? []) {
21192
21559
  if (isPlumbing(tree)) continue;
21193
21560
  const items = Object.values(tree.InnerTree ?? {}).flat();
@@ -21217,10 +21584,11 @@ async function summarizeSolve(res, schema, link) {
21217
21584
  counts.set(name, (counts.get(name) ?? 0) + 1);
21218
21585
  }
21219
21586
  const vertices = await meshVertexCount(items);
21220
- const files = fileNames(items);
21587
+ const files = await fileLinks(items, options.origin, options.stash);
21588
+ anyFiles ||= files.length > 0;
21221
21589
  const parts = [...counts].map(([type, n]) => `${n} ${type}`);
21222
21590
  if (vertices !== null) parts.push(`${vertices.toLocaleString("en-US")} vertices`);
21223
- if (files.length) parts.push(`files: ${files.join(", ")}`);
21591
+ if (files.length) parts.push(`files: ${files.map((f) => `${f.name} (${sizeText(f.bytes)}) ${f.url}`).join(", ")}`);
21224
21592
  structured[tree.ParamName] = {
21225
21593
  geometry: Object.fromEntries(counts),
21226
21594
  ...vertices !== null && { vertices },
@@ -21229,17 +21597,19 @@ async function summarizeSolve(res, schema, link) {
21229
21597
  lines.push(`${tree.ParamName}: ${items.length ? parts.join(", ") : "empty"}`);
21230
21598
  }
21231
21599
  if (!lines.length) lines.push("The solve returned no outputs.");
21600
+ if (anyFiles) lines.push("File links download the file and expire within the hour.");
21232
21601
  if (res.selva?.outcome) lines.push(`Outcome: ${JSON.stringify(res.selva.outcome)}`);
21233
21602
  for (const e of res.errors ?? []) lines.push(`Error: ${e}`);
21234
21603
  for (const w of res.warnings ?? []) lines.push(`Warning: ${w}`);
21235
- lines.push(`Geometry and file contents are not shown here; view them at ${link}`);
21604
+ if (res.errors?.length) lines.push("To find out whether the Compute server lacks a plugin or component this definition needs, call selva_check_definition.");
21605
+ lines.push(`View the geometry at ${options.link}`);
21236
21606
  return {
21237
21607
  text: lines.join("\n"),
21238
21608
  structured: {
21239
21609
  outputs: structured,
21240
21610
  errors: res.errors ?? [],
21241
21611
  warnings: res.warnings ?? [],
21242
- link
21612
+ link: options.link
21243
21613
  }
21244
21614
  };
21245
21615
  }
@@ -21250,6 +21620,164 @@ function parseItem(data) {
21250
21620
  return data;
21251
21621
  }
21252
21622
  }
21623
+ // src/lib/server/mcp/views.ts
21624
+ var solveHtml = () => import("../../../chunks/solve.js").then((m) => m.default);
21625
+ /** The page `selva_capture_preview` renders in, for `captureSolve`. */
21626
+ var captureHtml = () => import("../../../chunks/capture.js").then((m) => m.default);
21627
+ function selvaViews() {
21628
+ return [appResource({
21629
+ uri: SOLVE_VIEW_URI,
21630
+ name: "Solve in 3D",
21631
+ description: "The geometry of a solve, to orbit and zoom.",
21632
+ html: solveHtml,
21633
+ prefersBorder: true
21634
+ })];
21635
+ }
21636
+ var hdr;
21637
+ /**
21638
+ * The environment Selva's viewer lights with, as a `data:` URL: the capture page loads nothing
21639
+ * from Selva's origin, which the server may not be able to reach from inside.
21640
+ */
21641
+ function captureHdr() {
21642
+ hdr ??= Promise.all([import("../../../chunks/server5.js"), import("../../../chunks/baseHDR.js")]).then(async ([{ read }, { default: url }]) => {
21643
+ return `data:application/octet-stream;base64,${Buffer.from(await read(url).arrayBuffer()).toString("base64")}`;
21644
+ });
21645
+ hdr.catch(() => hdr = void 0);
21646
+ return hdr;
21647
+ }
21648
+ // src/lib/server/mcp/tools.ts
21649
+ /**
21650
+ * Selva's MCP tools: find a definition, read its form, solve it, read back numbers and files,
21651
+ * render it, check what it needs from Compute, upload and compare versions, edit its details and
21652
+ * cover, publish a version, and list or create projects. No deletes, share links, tokens or admin.
21653
+ */
21654
+ var valuesArg = z.record(z.string(), z.unknown()).default({}).describe("Input values keyed by the names selva_describe_definition lists. Dropdowns take an option name.");
21655
+ async function schemaFor(api, guid, version, signal) {
21656
+ if (!version || version === "live") return { schema: await api.call("getDefinitionsByGuidSchema", {
21657
+ params: { guid },
21658
+ signal
21659
+ }) };
21660
+ const record = await getRecord(api, guid, signal);
21661
+ const picked = pickVersion(record, version);
21662
+ return {
21663
+ schema: await api.call("getDefinitionsByGuidVersionsByVersionIdSchema", {
21664
+ params: {
21665
+ guid,
21666
+ versionId: picked.id
21667
+ },
21668
+ signal
21669
+ }),
21670
+ versionId: picked.id,
21671
+ record
21672
+ };
21673
+ }
21674
+ async function runSolve(api, definition, values, version, signal) {
21675
+ const guid = await resolveDefinition(api, definition, signal);
21676
+ const { schema, versionId } = await schemaFor(api, guid, version, signal);
21677
+ return {
21678
+ guid,
21679
+ schema,
21680
+ res: await api.call("postDefinitionsByGuidSolve", {
21681
+ params: { guid },
21682
+ body: {
21683
+ inputs: schema.inputs,
21684
+ values: resolveValues(describeInputs(schema), values),
21685
+ ...versionId && { versionId }
21686
+ },
21687
+ signal
21688
+ })
21689
+ };
21690
+ }
21691
+ var SOLVE_CALLS = [
21692
+ "getDefinitions",
21693
+ "getDefinitionsByGuid",
21694
+ "getDefinitionsByGuidSchema",
21695
+ "getDefinitionsByGuidVersionsByVersionIdSchema",
21696
+ "postDefinitionsByGuidSolve"
21697
+ ];
21698
+ function inventoryText(report) {
21699
+ const lines = [];
21700
+ if (report.extractedWith) lines.push(`Read on the Compute server by Selva ${report.extractedWith}, when the version was uploaded or last rechecked.`);
21701
+ const plugins = report.plugins ?? [];
21702
+ if (plugins.length) {
21703
+ lines.push("", "Plugins (saved with → on the server):");
21704
+ for (const p of plugins) {
21705
+ const server = p.serverVersion ?? "not installed";
21706
+ const flag = p.serverVersion === null ? " MISSING" : p.serverVersion !== p.version ? " differs" : "";
21707
+ lines.push(`- ${p.name}: ${p.version} → ${server}${flag}`);
21708
+ }
21709
+ } else if (report.plugins) lines.push("", "Plugins: none beyond Grasshopper and Rhino.");
21710
+ lines.push("");
21711
+ if (report.warnings.length) lines.push("Problems:", ...report.warnings.map((w) => `- ${inventoryWarningText(w)}`));
21712
+ else lines.push("No problems: every plugin and component it uses loaded on the Compute server.");
21713
+ return lines;
21714
+ }
21715
+ var InventoryOutput = z.object({
21716
+ versionId: z.string(),
21717
+ versionNumber: z.number(),
21718
+ plugins: z.array(z.object({
21719
+ name: z.string(),
21720
+ version: z.string(),
21721
+ serverVersion: z.string().nullable()
21722
+ })),
21723
+ warnings: z.array(z.record(z.string(), z.unknown())),
21724
+ extractedWith: z.string().optional()
21725
+ });
21726
+ function inventoryStructured(version, report) {
21727
+ return {
21728
+ versionId: version.id,
21729
+ versionNumber: version.versionNumber,
21730
+ plugins: report.plugins ?? [],
21731
+ warnings: report.warnings,
21732
+ ...report.extractedWith && { extractedWith: report.extractedWith }
21733
+ };
21734
+ }
21735
+ /** What a new file changes against the version it follows, form first. */
21736
+ function changesText(changes, inventory, baseLabel) {
21737
+ const lines = [];
21738
+ if (!baseLabel) lines.push("Nothing to compare with: it is the first version.");
21739
+ else if (!changes) lines.push(`The form can't be compared with ${baseLabel}: it predates cached schemas.`);
21740
+ else if (changes.identical) lines.push(`The form is the same as in ${baseLabel}.`);
21741
+ else lines.push(`Against ${baseLabel}:`, schemaDiffToMarkdown(changes));
21742
+ const inside = inventory?.diff ? inventoryDiffToMarkdown(inventory.diff) : "";
21743
+ if (inside) lines.push("", "### Inside the definition", inside);
21744
+ return lines;
21745
+ }
21746
+ var fileArgs = {
21747
+ file: z.string().describe("The .gh or .ghx file, base64, no `data:` prefix."),
21748
+ fileName: z.string().regex(/\.ghx?$/i, "must end in .gh or .ghx").describe("The file name, e.g. \"shelf.gh\".")
21749
+ };
21750
+ var acceptArg = z.boolean().default(false).describe("Upload even though the Compute server lacks a plugin or component it needs. Solves will miss outputs until it is installed.");
21751
+ function ghFile(file, fileName) {
21752
+ return new File([Buffer.from(file, "base64")], fileName, { type: "application/octet-stream" });
21753
+ }
21754
+ var COVER_TYPES = [
21755
+ "image/png",
21756
+ "image/jpeg",
21757
+ "image/webp",
21758
+ "image/gif"
21759
+ ];
21760
+ async function readCover(api, guid, signal) {
21761
+ const image = await api.call("getDefinitionsByGuidImage", {
21762
+ params: { guid },
21763
+ bytes: true,
21764
+ signal
21765
+ });
21766
+ return {
21767
+ data: Buffer.from(image.data).toString("base64"),
21768
+ mimeType: image.contentType.split(";")[0] || "image/webp"
21769
+ };
21770
+ }
21771
+ var CAPTURE_VIEWS = [
21772
+ "iso",
21773
+ "top",
21774
+ "front",
21775
+ "back",
21776
+ "left",
21777
+ "right",
21778
+ "bottom"
21779
+ ];
21780
+ var DEFAULT_BACKGROUND = "#E6E6E6";
21253
21781
  var ListOutput = z.object({
21254
21782
  items: z.array(z.record(z.string(), z.unknown())),
21255
21783
  nextCursor: z.string().optional()
@@ -21268,78 +21796,287 @@ var PublishOutput = z.object({
21268
21796
  versionNumber: z.number(),
21269
21797
  link: z.string()
21270
21798
  });
21271
- function selvaTools(origin) {
21799
+ function selvaTools(origin, options) {
21800
+ const { stash } = options;
21801
+ const pageOf = (guid) => `${origin}/library/${encodeURIComponent(guid)}`;
21272
21802
  return [
21273
21803
  fromOperation("getProjects", {
21274
21804
  name: "selva_list_projects",
21275
21805
  title: "List projects",
21276
- description: "Projects the key can see. Use a project id to narrow selva_list_definitions. Pages with `cursor`.",
21806
+ description: "Projects the key can see. Use a project id to narrow selva_list_definitions, or as the destination of selva_update_definition or selva_create_definition. Pages with `cursor`.",
21277
21807
  output: ListOutput,
21278
21808
  shape: (body) => {
21279
21809
  const page = body;
21280
- return listOutput(page.items, (p) => `- ${p.name} (id ${p.id})`, page.nextCursor);
21810
+ return listOutput(page.items, (p) => `- ${p.name} (id ${p.id}${p.visibility ? `, ${p.visibility}` : ""})`, page.nextCursor);
21811
+ }
21812
+ }),
21813
+ tool({
21814
+ name: "selva_list_project_members",
21815
+ title: "List project members",
21816
+ description: "A project's members: display name, user id and role. Needs the right to manage its members.",
21817
+ input: z.object({ project: projectArg }),
21818
+ calls: ["getProjects", "getProjectsByIdMembers"],
21819
+ async run(api, { project }, { signal }) {
21820
+ const p = await resolveProject(api, project, signal);
21821
+ const members = [];
21822
+ let cursor;
21823
+ do {
21824
+ const page = await api.call("getProjectsByIdMembers", {
21825
+ params: { id: p.id },
21826
+ query: {
21827
+ limit: 100,
21828
+ cursor
21829
+ },
21830
+ signal
21831
+ });
21832
+ members.push(...page.items);
21833
+ cursor = page.nextCursor;
21834
+ } while (cursor);
21835
+ const lines = members.map((m) => `- ${m.displayName ? `${m.displayName} (${m.userId})` : m.userId}: ${m.role}` + (m.joinedAt ? `, since ${m.joinedAt.slice(0, 10)}` : ""));
21836
+ return [`# ${p.name}`, ...lines.length ? lines : ["No members."]].join("\n");
21837
+ }
21838
+ }),
21839
+ tool({
21840
+ name: "selva_create_project",
21841
+ title: "Create a project",
21842
+ description: "Creates a project the key’s owner owns. Private unless `visibility` says otherwise. Move definitions into it with selva_update_definition.",
21843
+ input: z.object({
21844
+ name: z.string().min(1).max(128),
21845
+ description: z.string().max(2e3).optional(),
21846
+ visibility: ProjectVisibilitySchema.default("private")
21847
+ }),
21848
+ calls: ["postProjects"],
21849
+ async run(api, body, { signal }) {
21850
+ const project = await api.call("postProjects", {
21851
+ body,
21852
+ signal
21853
+ });
21854
+ return `Created ${project.name} (id ${project.id}, ${project.visibility ?? body.visibility}).`;
21281
21855
  }
21282
21856
  }),
21283
21857
  fromOperation("getDefinitions", {
21284
21858
  name: "selva_list_definitions",
21285
21859
  title: "List definitions",
21286
- description: "Grasshopper definitions the key can see, newest changes first. Filter by `projectId`. Only definitions with a live version can be solved; each line says which. `status` is not that: a fresh upload has a live version but reads `draft`, so don't filter on it to find solvable ones. Then call selva_describe_definition with a guid.",
21860
+ description: "Grasshopper definitions the key can see, newest changes first. Filter by `projectId`. Each line says whether it can be solved (it has a live version) and whether the library lists it. Then call selva_describe_definition with a guid.",
21287
21861
  output: ListOutput,
21862
+ omit: ["status"],
21288
21863
  shape: (body) => {
21289
21864
  const page = body;
21290
- return listOutput(page.items, (d) => `- ${d.displayName} (guid ${d.guid}, ${d.liveVersionId ? "solvable" : "no live version, cannot be solved"})` + (d.description ? `: ${d.description}` : ""), page.nextCursor);
21865
+ return listOutput(page.items.map(({ status, ...d }) => ({
21866
+ ...d,
21867
+ solvable: !!d.liveVersionId,
21868
+ listedInLibrary: status === "published"
21869
+ })), (d) => `- ${d.displayName} (guid ${d.guid}, ${d.solvable ? "solvable" : "no live version, cannot be solved"}${d.listedInLibrary ? "" : ", not listed in the library"})` + (d.description ? `: ${d.description}` : ""), page.nextCursor);
21291
21870
  }
21292
21871
  }),
21293
21872
  tool({
21294
21873
  name: "selva_describe_definition",
21295
21874
  title: "Describe a definition",
21296
- description: "A published definition's inputs (name, type, range, options, default) and outputs. Call before selva_solve; pass inputs to it by the quoted name.",
21875
+ description: "A definition's form as its users see it: groups with their descriptions, then each input (name, type, range, unit, options, default, when it shows, description) and output. Also which version is live. Call before selva_solve; pass inputs to it by the quoted name. `version` reads an upload that is not live yet.",
21876
+ input: z.object({
21877
+ definition: definitionArg,
21878
+ version: versionArg
21879
+ }),
21880
+ calls: [
21881
+ "getDefinitions",
21882
+ "getDefinitionsByGuid",
21883
+ "getDefinitionsByGuidSchema",
21884
+ "getDefinitionsByGuidVersionsByVersionIdSchema"
21885
+ ],
21886
+ async run(api, { definition, version }, { signal }) {
21887
+ const guid = await resolveDefinition(api, definition, signal);
21888
+ const record = await getRecord(api, guid, signal);
21889
+ if (!record.liveVersion && (!version || version === "live")) return `# ${record.displayName}\n${channelText(record)}`;
21890
+ const picked = pickVersion(record, version);
21891
+ const schema = await (picked.id === record.liveVersion?.id ? api.call("getDefinitionsByGuidSchema", {
21892
+ params: { guid },
21893
+ signal
21894
+ }) : api.call("getDefinitionsByGuidVersionsByVersionIdSchema", {
21895
+ params: {
21896
+ guid,
21897
+ versionId: picked.id
21898
+ },
21899
+ signal
21900
+ }));
21901
+ const lines = [`# ${schema.name || record.displayName}`, channelText(record)];
21902
+ if (picked.id !== record.liveVersion?.id) lines.push(`This is ${versionLabel(record, picked)}.`);
21903
+ if (schema.description) lines.push("", schema.description);
21904
+ lines.push(...formText(schema));
21905
+ return lines.join("\n");
21906
+ }
21907
+ }),
21908
+ tool({
21909
+ name: "selva_list_versions",
21910
+ title: "List versions",
21911
+ description: "A definition's versions, newest first: number, id, upload date, change note, which is live, and whether the server lacked something it needs. Pass an id to selva_solve, selva_compare_versions or selva_publish_definition (to roll back).",
21297
21912
  input: z.object({ definition: definitionArg }),
21298
- calls: ["getDefinitions", "getDefinitionsByGuidSchema"],
21913
+ calls: [
21914
+ "getDefinitions",
21915
+ "getDefinitionsByGuid",
21916
+ "getDefinitionsByGuidVersions"
21917
+ ],
21299
21918
  async run(api, { definition }, { signal }) {
21300
21919
  const guid = await resolveDefinition(api, definition, signal);
21301
- const schema = await api.call("getDefinitionsByGuidSchema", {
21920
+ const record = await getRecord(api, guid, signal);
21921
+ const page = await api.call("getDefinitionsByGuidVersions", {
21302
21922
  params: { guid },
21923
+ query: { limit: 50 },
21303
21924
  signal
21304
21925
  });
21305
- const lines = [`# ${schema.name}`];
21306
- if (schema.description) lines.push(schema.description);
21307
- lines.push("", "Inputs:", ...describeInputs(schema).map(inputLine));
21308
- lines.push("", "Outputs:", ...schema.outputs.map((o) => `- "${o.nickname}": ${o.type}`));
21309
- return lines.join("\n");
21926
+ const lines = page.items.map((v) => {
21927
+ const marks = [v.id === record.liveVersion?.id && "live", v.id === record.draftVersion?.id && v.id !== record.liveVersion?.id && "newest upload"].filter(Boolean);
21928
+ const needs = [...v.inventorySummary?.missingPlugins ?? [], ...v.inventorySummary?.unloadedComponents ?? []];
21929
+ return `- version ${v.versionNumber} (id ${v.id}` + (v.uploadedAt ? `, ${v.uploadedAt.slice(0, 10)}` : "") + (marks.length ? `, ${marks.join(", ")}` : "") + (needs.length ? `, server lacks ${needs.join(", ")}` : "") + ")" + (v.changeNote ? `: ${v.changeNote.split("\n")[0]}` : "");
21930
+ });
21931
+ if (page.nextCursor) lines.push("Older versions are not shown.");
21932
+ return [`# ${record.displayName}`, ...lines.length ? lines : ["No versions."]].join("\n");
21310
21933
  }
21311
21934
  }),
21312
21935
  tool({
21313
- name: "selva_solve",
21314
- title: "Solve a definition",
21315
- description: "Runs the live version of a definition on Rhino Compute and returns its number and text outputs, with a one-line summary of each geometry output. Spends compute; can take minutes. Inputs left out keep their defaults. Call selva_describe_definition first. `detail: 'full'` adds the raw solve response with geometry and file contents; it can be very large.",
21936
+ name: "selva_compare_versions",
21937
+ title: "Compare versions",
21938
+ description: "What a version changed in the form (inputs, outputs, settings, with which changes break saved values) and, for editors, inside the file (plugins, components, values, scripts). Against the version before it, or `against`.",
21316
21939
  input: z.object({
21317
21940
  definition: definitionArg,
21318
- values: z.record(z.string(), z.unknown()).default({}).describe("Input values keyed by the names selva_describe_definition lists. Dropdowns take an option name."),
21319
- detail: z.enum(["summary", "full"]).default("summary")
21941
+ version: versionArg,
21942
+ against: z.string().optional().describe("A version id to compare with.")
21320
21943
  }),
21321
- output: SolveOutput,
21322
21944
  calls: [
21323
21945
  "getDefinitions",
21324
- "getDefinitionsByGuidSchema",
21325
- "postDefinitionsByGuidSolve"
21946
+ "getDefinitionsByGuid",
21947
+ "getDefinitionsByGuidVersionsByVersionIdChanges"
21326
21948
  ],
21327
- async run(api, { definition, values, detail }, { signal }) {
21949
+ async run(api, { definition, version, against }, { signal }) {
21328
21950
  const guid = await resolveDefinition(api, definition, signal);
21329
- const schema = await api.call("getDefinitionsByGuidSchema", {
21330
- params: { guid },
21951
+ const record = await getRecord(api, guid, signal);
21952
+ const picked = pickVersion(record, version ?? "draft");
21953
+ const res = await api.call("getDefinitionsByGuidVersionsByVersionIdChanges", {
21954
+ params: {
21955
+ guid,
21956
+ versionId: picked.id
21957
+ },
21958
+ query: { against },
21331
21959
  signal
21332
21960
  });
21333
- const res = await api.call("postDefinitionsByGuidSolve", {
21334
- params: { guid },
21335
- body: {
21336
- inputs: schema.inputs,
21337
- values: resolveValues(describeInputs(schema), values)
21961
+ return [`# ${record.displayName}, ${versionLabel(record, picked)}`, ...changesText(res.changes, res.inventory, res.base ? `version ${res.base.versionNumber}` : null)].join("\n");
21962
+ }
21963
+ }),
21964
+ tool({
21965
+ name: "selva_check_definition",
21966
+ title: "Check what a definition needs",
21967
+ description: "Lists the plugins a definition was saved with beside the versions its Compute server has loaded, and the problems that follow: a missing plugin, a component the installed release lacks, obsolete components, secrets left in the file. Call it when a solve fails or misses outputs. Editors only.",
21968
+ input: z.object({
21969
+ definition: definitionArg,
21970
+ version: versionArg
21971
+ }),
21972
+ output: InventoryOutput,
21973
+ calls: [
21974
+ "getDefinitions",
21975
+ "getDefinitionsByGuid",
21976
+ "getDefinitionsByGuidVersionsByVersionIdChanges"
21977
+ ],
21978
+ async run(api, { definition, version }, { signal }) {
21979
+ const guid = await resolveDefinition(api, definition, signal);
21980
+ const record = await getRecord(api, guid, signal);
21981
+ const picked = pickVersion(record, version ?? (record.liveVersion ? "live" : "draft"));
21982
+ const changes = await api.call("getDefinitionsByGuidVersionsByVersionIdChanges", {
21983
+ params: {
21984
+ guid,
21985
+ versionId: picked.id
21986
+ },
21987
+ signal
21988
+ });
21989
+ const head = `# ${record.displayName}, ${versionLabel(record, picked)}`;
21990
+ if (changes.inventory === void 0) throw new Error(`${head}\nOnly people who can upload to this definition see what is inside it.`);
21991
+ if (changes.inventory === null) throw new Error(`${head}\nThis version has no inventory: it was uploaded before Selva read them, or by a server whose Selva plugin can't. selva_recheck_definition reads it now.`);
21992
+ const report = changes.inventory;
21993
+ return {
21994
+ text: [
21995
+ head,
21996
+ ...inventoryText(report),
21997
+ "",
21998
+ "Installed or updated a plugin since? selva_recheck_definition reads it again."
21999
+ ].join("\n"),
22000
+ structured: inventoryStructured(picked, report)
22001
+ };
22002
+ }
22003
+ }),
22004
+ tool({
22005
+ name: "selva_recheck_definition",
22006
+ title: "Recheck a definition against Compute",
22007
+ description: "Reads a version's file again on its Compute server and stores what it finds, then reports it like selva_check_definition. Use after a plugin was installed or updated.",
22008
+ input: z.object({
22009
+ definition: definitionArg,
22010
+ version: versionArg
22011
+ }),
22012
+ output: InventoryOutput,
22013
+ calls: [
22014
+ "getDefinitions",
22015
+ "getDefinitionsByGuid",
22016
+ "postDefinitionsByGuidVersionsByVersionIdInventory"
22017
+ ],
22018
+ async run(api, { definition, version }, { signal }) {
22019
+ const guid = await resolveDefinition(api, definition, signal);
22020
+ const record = await getRecord(api, guid, signal);
22021
+ const picked = pickVersion(record, version ?? (record.liveVersion ? "live" : "draft"));
22022
+ const report = await api.call("postDefinitionsByGuidVersionsByVersionIdInventory", {
22023
+ params: {
22024
+ guid,
22025
+ versionId: picked.id
21338
22026
  },
21339
22027
  signal
21340
22028
  });
21341
- const summary = await summarizeSolve(res, schema, `${origin}/library/${encodeURIComponent(guid)}`);
21342
- if (detail !== "full") return summary;
22029
+ return {
22030
+ text: [`# ${record.displayName}, ${versionLabel(record, picked)}`, ...inventoryText(report)].join("\n"),
22031
+ structured: inventoryStructured(picked, report)
22032
+ };
22033
+ }
22034
+ }),
22035
+ tool({
22036
+ name: "selva_solve",
22037
+ title: "Solve a definition",
22038
+ description: "Runs a definition on Rhino Compute and returns its number and text outputs, a one-line summary of each geometry output, and a download link per output file. Spends compute; can take minutes. Inputs left out keep their defaults. Call selva_describe_definition first. The live version by default; `version: 'draft'` tries an upload before it is published. When it reports errors, selva_check_definition says whether the server lacks a plugin or component. `detail: 'full'` adds the raw solve response with geometry; it can be very large.",
22039
+ input: z.object({
22040
+ definition: definitionArg,
22041
+ values: valuesArg,
22042
+ version: versionArg,
22043
+ detail: z.enum(["summary", "full"]).default("summary")
22044
+ }),
22045
+ output: SolveOutput,
22046
+ calls: SOLVE_CALLS,
22047
+ ui: { resourceUri: SOLVE_VIEW_URI },
22048
+ async run(api, { definition, values, version, detail }, { signal, apps }) {
22049
+ const { guid, schema, res } = await runSolve(api, definition, values, version, signal);
22050
+ const summary = await summarizeSolve(res, schema, {
22051
+ origin,
22052
+ link: pageOf(guid),
22053
+ stash
22054
+ });
22055
+ const meta = apps ? { [SOLVE_VIEW_KEY]: {
22056
+ title: schema.name,
22057
+ load: {
22058
+ tool: "selva_solve_geometry",
22059
+ arguments: { token: await stash.put({
22060
+ kind: "solve",
22061
+ name: schema.name,
22062
+ contentType: "application/json",
22063
+ data: jsonBytes(res)
22064
+ }) }
22065
+ },
22066
+ form: {
22067
+ tool: "selva_solve",
22068
+ arguments: {
22069
+ definition: guid,
22070
+ ...version && { version }
22071
+ },
22072
+ valuesKey: "values",
22073
+ inputs: viewInputs(schema, values)
22074
+ }
22075
+ } } : void 0;
22076
+ if (detail !== "full") return {
22077
+ ...summary,
22078
+ meta
22079
+ };
21343
22080
  const response = {
21344
22081
  ...res,
21345
22082
  values: res.values?.filter((t) => !isPlumbing(t))
@@ -21349,17 +22086,273 @@ function selvaTools(origin) {
21349
22086
  structured: {
21350
22087
  ...summary.structured,
21351
22088
  response
21352
- }
22089
+ },
22090
+ meta
22091
+ };
22092
+ }
22093
+ }),
22094
+ tool({
22095
+ name: "selva_solve_geometry",
22096
+ title: "Solve geometry",
22097
+ description: "A solve's geometry, for its 3D view.",
22098
+ input: z.object({ token: z.string() }),
22099
+ calls: ["getMe"],
22100
+ ui: {
22101
+ resourceUri: SOLVE_VIEW_URI,
22102
+ visibility: ["app"]
22103
+ },
22104
+ async run(_api, { token }) {
22105
+ const held = await stash.get(token, "solve");
22106
+ if (!held) throw new Error("This solve’s geometry has expired. Solve again to see it.");
22107
+ return {
22108
+ text: "Geometry.",
22109
+ meta: { [SOLVE_VIEW_KEY]: { response: fromJsonBytes(held.data) } }
22110
+ };
22111
+ }
22112
+ }),
22113
+ tool({
22114
+ name: "selva_capture_preview",
22115
+ title: "Render a preview",
22116
+ description: "Solves a definition and draws the result in Selva's own 3D viewer, with the look and background the definition opens in, then returns the picture. Spends compute like selva_solve. The picture is kept for an hour under a preview id: pass it to selva_set_cover_image to make it the cover.",
22117
+ input: z.object({
22118
+ definition: definitionArg,
22119
+ values: valuesArg,
22120
+ version: versionArg,
22121
+ view: z.enum(CAPTURE_VIEWS).default("iso").describe("Camera direction."),
22122
+ width: z.number().int().min(256).max(2048).default(1200),
22123
+ height: z.number().int().min(256).max(2048).default(800),
22124
+ grid: z.boolean().default(false).describe("Draw the viewer's ground grid.")
22125
+ }),
22126
+ calls: SOLVE_CALLS,
22127
+ async run(api, { definition, values, version, view, width, height, grid }, { signal }) {
22128
+ const { schema, res } = await runSolve(api, definition, values, version, signal);
22129
+ let capture;
22130
+ try {
22131
+ capture = await captureSolve(res, {
22132
+ view,
22133
+ width,
22134
+ height,
22135
+ grid,
22136
+ look: schema.viewerOptions?.look,
22137
+ background: schema.viewerOptions?.backgroundColor ?? DEFAULT_BACKGROUND,
22138
+ hdr: captureHdr,
22139
+ html: captureHtml,
22140
+ executablePath: options.previewBrowser || void 0,
22141
+ signal
22142
+ });
22143
+ } catch (err) {
22144
+ if (err instanceof CaptureUnavailableError) throw new Error(`${err.message} An operator sets this up; the solve itself worked.`, { cause: err });
22145
+ throw err;
22146
+ }
22147
+ if (!capture.drawn) return `${schema.name} solved, but drew nothing: it has no Display output with geometry for these values.`;
22148
+ const previewId = await stash.put({
22149
+ kind: "preview",
22150
+ name: `${schema.name}.png`,
22151
+ contentType: "image/png",
22152
+ data: new Uint8Array(Buffer.from(capture.png, "base64"))
22153
+ });
22154
+ return {
22155
+ text: `${schema.name}, ${view} view, ${width}×${height}. Preview id ${previewId}.`,
22156
+ images: [{
22157
+ data: capture.png,
22158
+ mimeType: "image/png"
22159
+ }]
22160
+ };
22161
+ }
22162
+ }),
22163
+ tool({
22164
+ name: "selva_check_upload",
22165
+ title: "Check a file before uploading it",
22166
+ description: "Dry run of selva_upload_version: reads the file on the Compute server and reports what it would change in the form and inside the file, and whether the server lacks a plugin or component it needs. Uploads nothing.",
22167
+ input: z.object({
22168
+ definition: definitionArg,
22169
+ ...fileArgs
22170
+ }),
22171
+ calls: ["getDefinitions", "postDefinitionsByGuidVersionsCheck"],
22172
+ async run(api, { definition, file, fileName }, { signal }) {
22173
+ const guid = await resolveDefinition(api, definition, signal);
22174
+ const form = new FormData();
22175
+ form.append("file", ghFile(file, fileName));
22176
+ const res = await api.call("postDefinitionsByGuidVersionsCheck", {
22177
+ params: { guid },
22178
+ body: form,
22179
+ signal
22180
+ });
22181
+ return [
22182
+ `# ${res.schema.name}: ${res.schema.inputs} inputs, ${res.schema.outputs} outputs`,
22183
+ ...changesText(res.changes, res.inventory, res.base ? `version ${res.base.versionNumber}` : null),
22184
+ ...res.inventory ? ["", ...inventoryText(res.inventory)] : []
22185
+ ].join("\n");
22186
+ }
22187
+ }),
22188
+ tool({
22189
+ name: "selva_upload_version",
22190
+ title: "Upload a new version",
22191
+ description: "Uploads a .gh or .ghx as the next version of a definition. It is not live until selva_publish_definition; until then solve it with `version: 'draft'`. Refused when the Compute server lacks a plugin or component it needs, unless `acceptMissingPlugins`.",
22192
+ input: z.object({
22193
+ definition: definitionArg,
22194
+ ...fileArgs,
22195
+ changeNote: z.string().max(1e4).optional().describe("Markdown: what changed."),
22196
+ acceptMissingPlugins: acceptArg
22197
+ }),
22198
+ calls: ["getDefinitions", "postDefinitionsByGuidVersions"],
22199
+ async run(api, { definition, file, fileName, changeNote, acceptMissingPlugins }, { signal }) {
22200
+ const guid = await resolveDefinition(api, definition, signal);
22201
+ const form = new FormData();
22202
+ form.append("file", ghFile(file, fileName));
22203
+ if (changeNote) form.append("changeNote", changeNote);
22204
+ if (acceptMissingPlugins) form.append("acceptMissingPlugins", "true");
22205
+ const res = await api.call("postDefinitionsByGuidVersions", {
22206
+ params: { guid },
22207
+ body: form,
22208
+ signal
22209
+ });
22210
+ return [
22211
+ `Uploaded version ${res.version.versionNumber} (id ${res.version.id}). It is not live: solve it with \`version: 'draft'\`, then selva_publish_definition.`,
22212
+ ...changesText(res.changes, res.inventory, res.base ? `version ${res.base.versionNumber}` : null),
22213
+ ...res.inventory?.warnings.length ? [
22214
+ "",
22215
+ "Problems:",
22216
+ ...res.inventory.warnings.map((w) => `- ${inventoryWarningText(w)}`)
22217
+ ] : []
22218
+ ].join("\n");
22219
+ }
22220
+ }),
22221
+ tool({
22222
+ name: "selva_create_definition",
22223
+ title: "Create a definition",
22224
+ description: "Uploads a .gh or .ghx as a new definition in a project. Its first version is live at once, but the library lists it only after selva_publish_definition. Refused when the Compute server lacks a plugin or component it needs, unless `acceptMissingPlugins`.",
22225
+ input: z.object({
22226
+ project: projectArg,
22227
+ ...fileArgs,
22228
+ displayName: z.string().min(1).max(256),
22229
+ description: z.string().max(2e3).optional(),
22230
+ category: z.string().max(128).optional(),
22231
+ tags: z.array(z.string().max(64).regex(/^[^,]*$/, "no commas")).max(20).optional(),
22232
+ acceptMissingPlugins: acceptArg
22233
+ }),
22234
+ calls: ["getProjects", "postDefinitions"],
22235
+ async run(api, args, { signal }) {
22236
+ const project = await resolveProject(api, args.project, signal);
22237
+ const form = new FormData();
22238
+ form.append("file", ghFile(args.file, args.fileName));
22239
+ form.append("projectId", project.id);
22240
+ form.append("displayName", args.displayName);
22241
+ if (args.description) form.append("description", args.description);
22242
+ if (args.category) form.append("category", args.category);
22243
+ if (args.tags?.length) form.append("tags", args.tags.join(","));
22244
+ if (args.acceptMissingPlugins) form.append("acceptMissingPlugins", "true");
22245
+ const res = await api.call("postDefinitions", {
22246
+ body: form,
22247
+ signal
22248
+ });
22249
+ return `Created ${args.displayName} (guid ${res.guid}) in ${project.name}. Version ${res.version.versionNumber} is live; the library lists it after selva_publish_definition. ` + pageOf(res.guid);
22250
+ }
22251
+ }),
22252
+ tool({
22253
+ name: "selva_update_definition",
22254
+ title: "Edit a definition’s details",
22255
+ description: "Changes the name, description, category or tags, or moves the definition to another project. Fields left out stay as they are; null clears one. Does not touch versions: selva_publish_definition makes one live.",
22256
+ input: z.object({
22257
+ definition: definitionArg,
22258
+ displayName: z.string().min(1).max(256).optional(),
22259
+ description: z.string().max(2e3).nullable().optional(),
22260
+ category: z.string().max(128).nullable().optional(),
22261
+ tags: z.array(z.string().max(64)).max(20).nullable().optional(),
22262
+ project: projectArg.optional().describe("Move it into this project.")
22263
+ }),
22264
+ calls: [
22265
+ "getDefinitions",
22266
+ "getProjects",
22267
+ "patchDefinitionsByGuid",
22268
+ "getDefinitionsByGuid"
22269
+ ],
22270
+ async run(api, { definition, project, ...fields }, { signal }) {
22271
+ const guid = await resolveDefinition(api, definition, signal);
22272
+ const patch = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== void 0));
22273
+ let destination;
22274
+ if (project) {
22275
+ destination = await resolveProject(api, project, signal);
22276
+ patch.projectId = destination.id;
22277
+ }
22278
+ if (!Object.keys(patch).length) throw new Error("Nothing to change: pass at least one field.");
22279
+ await api.call("patchDefinitionsByGuid", {
22280
+ params: { guid },
22281
+ body: patch,
22282
+ signal
22283
+ });
22284
+ const r = await getRecord(api, guid, signal);
22285
+ return [
22286
+ `Updated ${r.displayName} (guid ${guid}).`,
22287
+ r.description ? `Description: ${r.description}` : "No description.",
22288
+ `Category: ${r.category || "none"}. Tags: ${r.tags?.length ? r.tags.join(", ") : "none"}.`,
22289
+ destination ? `Now in project ${destination.name}.` : `Project id ${r.projectId}.`,
22290
+ listedText(r.status),
22291
+ pageOf(guid)
22292
+ ].join("\n");
22293
+ }
22294
+ }),
22295
+ tool({
22296
+ name: "selva_get_cover_image",
22297
+ title: "Show the cover image",
22298
+ description: "A definition's cover image, as a picture.",
22299
+ input: z.object({ definition: definitionArg }),
22300
+ calls: ["getDefinitions", "getDefinitionsByGuidImage"],
22301
+ async run(api, { definition }, { signal }) {
22302
+ return {
22303
+ text: "The cover image.",
22304
+ images: [await readCover(api, await resolveDefinition(api, definition, signal), signal)]
22305
+ };
22306
+ }
22307
+ }),
22308
+ tool({
22309
+ name: "selva_set_cover_image",
22310
+ title: "Set the cover image",
22311
+ description: "Replaces a definition's cover image with a preview from selva_capture_preview, or with an image given as base64. Returns the stored cover to check.",
22312
+ input: z.object({
22313
+ definition: definitionArg,
22314
+ previewId: z.string().optional().describe("From selva_capture_preview, within the hour."),
22315
+ image: z.string().optional().describe("Base64 image bytes, no `data:` prefix."),
22316
+ mimeType: z.enum(COVER_TYPES).optional().describe("The type of `image`. Default PNG.")
22317
+ }).refine((a) => !!a.previewId !== !!a.image, { message: "Pass either previewId or image." }),
22318
+ calls: [
22319
+ "getDefinitions",
22320
+ "postDefinitionsByGuidImage",
22321
+ "getDefinitionsByGuidImage"
22322
+ ],
22323
+ async run(api, { definition, previewId, image, mimeType }, { signal }) {
22324
+ const guid = await resolveDefinition(api, definition, signal);
22325
+ let bytes;
22326
+ let type;
22327
+ if (previewId) {
22328
+ const held = await stash.get(previewId, "preview");
22329
+ if (!held) throw new Error("That preview has expired. Call selva_capture_preview again.");
22330
+ bytes = held.data;
22331
+ type = held.contentType;
22332
+ } else {
22333
+ bytes = new Uint8Array(Buffer.from(image, "base64"));
22334
+ type = mimeType ?? "image/png";
22335
+ }
22336
+ const form = new FormData();
22337
+ form.append("image", new Blob([bytes], { type }), `cover.${type.split("/")[1]}`);
22338
+ await api.call("postDefinitionsByGuidImage", {
22339
+ params: { guid },
22340
+ body: form,
22341
+ signal
22342
+ });
22343
+ return {
22344
+ text: `The cover is set. This is what the library now shows: ${pageOf(guid)}`,
22345
+ images: [await readCover(api, guid, signal)]
21353
22346
  };
21354
22347
  }
21355
22348
  }),
21356
22349
  tool({
21357
22350
  name: "selva_publish_definition",
21358
22351
  title: "Publish a definition",
21359
- description: "Makes a version live and marks the definition published, so people running definitions see it. Without `versionId` it publishes the newest unpublished upload, or, when there is none, the version already live (which only changes the status). Changes what everyone runs: confirm with the user first.",
22352
+ description: "Makes a version live and lists the definition in the library. Without `versionId` it publishes the newest upload that is not live, or, when there is none, the version already live (which only lists it). An older version id rolls back. Changes what everyone runs: confirm with the user first.",
21360
22353
  input: z.object({
21361
22354
  definition: definitionArg,
21362
- versionId: z.string().optional().describe("A version id to make live instead, including an older one to roll back to.")
22355
+ versionId: z.string().optional().describe("A version id from selva_list_versions, including an older one to roll back to.")
21363
22356
  }),
21364
22357
  output: PublishOutput,
21365
22358
  calls: [
@@ -21369,10 +22362,7 @@ function selvaTools(origin) {
21369
22362
  ],
21370
22363
  async run(api, { definition, versionId }, { signal }) {
21371
22364
  const guid = await resolveDefinition(api, definition, signal);
21372
- const record = await api.call("getDefinitionsByGuid", {
21373
- params: { guid },
21374
- signal
21375
- });
22365
+ const record = await getRecord(api, guid, signal);
21376
22366
  const target = versionId ?? record.draftVersion?.id ?? record.liveVersion?.id;
21377
22367
  if (!target) throw new Error(`${record.displayName} has no uploaded version to publish.`);
21378
22368
  const { version } = await api.call("postDefinitionsByGuidPublish", {
@@ -21380,9 +22370,9 @@ function selvaTools(origin) {
21380
22370
  body: { versionId: target },
21381
22371
  signal
21382
22372
  });
21383
- const link = `${origin}/library/${encodeURIComponent(guid)}`;
22373
+ const link = pageOf(guid);
21384
22374
  return {
21385
- text: `${record.displayName}: version ${version.versionNumber} is live and the definition is published. ${link}`,
22375
+ text: `${record.displayName}: version ${version.versionNumber} is live and the library lists it. ${link}`,
21386
22376
  structured: {
21387
22377
  guid,
21388
22378
  versionId: version.id,
@@ -21394,7 +22384,7 @@ function selvaTools(origin) {
21394
22384
  })
21395
22385
  ];
21396
22386
  }
21397
- var INSTRUCTIONS = "Selva runs Grasshopper definitions on Rhino Compute. To answer a design question: find a definition (selva_list_definitions), read its inputs (selva_describe_definition), then solve it (selva_solve) and read the numbers back. Solving spends the owner’s compute budget: confirm with the user before a series of solves. Publishing changes what everyone runs: confirm before calling selva_publish_definition.";
22387
+ var INSTRUCTIONS = "Selva runs Grasshopper definitions on Rhino Compute. To answer a design question: find a definition (selva_list_definitions), read its form (selva_describe_definition), then solve it (selva_solve) and read the numbers back. A definition can be solved when it has a live version; whether the library lists it is separate. To change one: check the file (selva_check_upload), upload it (selva_upload_version), try it with `version: 'draft'`, then publish. When a solve fails or misses outputs, selva_check_definition compares what the file needs with what the Compute server has loaded. Solving and rendering (selva_capture_preview) spend the owner’s compute budget: confirm with the user before a series of them. Publishing changes what everyone runs: confirm before calling selva_publish_definition.";
21398
22388
  // src/lib/server/mcp/server.ts
21399
22389
  /** Every action the key's scopes cover, as `scopeAllows` decides at /api/v1. */
21400
22390
  async function grantedActions(api) {
@@ -21437,7 +22427,11 @@ function serverFor(origin) {
21437
22427
  instructions: INSTRUCTIONS,
21438
22428
  baseUrl: origin,
21439
22429
  openapi,
21440
- tools: selvaTools(origin),
22430
+ tools: selvaTools(origin, {
22431
+ stash: mcpStash(),
22432
+ previewBrowser: env.MCP_PREVIEW_BROWSER
22433
+ }),
22434
+ resources: selvaViews(),
21441
22435
  grantedActions,
21442
22436
  allowedOrigins: mcpAllowedOrigins(),
21443
22437
  challenge: challengeFor(origin),