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

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 (31) hide show
  1. package/build/adapter-node.js +2 -2
  2. package/build/client/_app/version.json +1 -1
  3. package/build/client/_app/version.json.br +0 -0
  4. package/build/client/_app/version.json.gz +0 -0
  5. package/build/server/.vite/manifest.json +8 -34
  6. package/build/server/chunks/baseHDR.js +2 -2
  7. package/build/server/chunks/baseHDR.js.map +1 -1
  8. package/build/server/chunks/capture.js +1 -1
  9. package/build/server/chunks/functions.js +1 -1
  10. package/build/server/chunks/grasshopper.js +23 -1
  11. package/build/server/chunks/grasshopper.js.map +1 -1
  12. package/build/server/chunks/instance.js +5 -5
  13. package/build/server/chunks/internal.js +3 -3
  14. package/build/server/chunks/package.js +1 -1
  15. package/build/server/chunks/package.js.map +1 -1
  16. package/build/server/chunks/rhino3dm.js.map +1 -1
  17. package/build/server/chunks/server-errors.js +1 -19
  18. package/build/server/chunks/server-errors.js.map +1 -1
  19. package/build/server/chunks/solve.js +1 -1
  20. package/build/server/entries/endpoints/mcp/_server.ts.js +227 -42
  21. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  22. package/build/server/index.js +1 -1
  23. package/build/server/remote-entry.js +1559 -1
  24. package/build/server/remote-entry.js.map +1 -0
  25. package/package.json +4 -4
  26. package/build/client/_app/immutable/assets/baseHDR.Dkr46J8-.hdr +0 -0
  27. package/build/server/_app/immutable/assets/baseHDR.Dkr46J8-.hdr +0 -0
  28. package/build/server/chunks/remote.js +0 -1559
  29. package/build/server/chunks/remote.js.map +0 -1
  30. package/build/server/chunks/server5.js +0 -52
  31. package/build/server/chunks/server5.js.map +0 -1
@@ -21179,14 +21179,19 @@ async function capture(response, options) {
21179
21179
  });
21180
21180
  await page.setContent(html, { waitUntil: "load" });
21181
21181
  const hdr = options.hdr ? await options.hdr() : void 0;
21182
- return await page.evaluate((req) => globalThis.selvaCapture(req), {
21182
+ const { pngs, drawn } = await page.evaluate((req) => globalThis.selvaCapture(req), {
21183
21183
  response,
21184
- view: options.view ?? "iso",
21184
+ views: options.views?.length ? options.views : [options.view ?? "iso"],
21185
21185
  grid: options.grid ?? true,
21186
21186
  look: options.look,
21187
21187
  background: options.background,
21188
21188
  hdr
21189
21189
  });
21190
+ return {
21191
+ png: pngs[0] ?? "",
21192
+ pngs,
21193
+ drawn
21194
+ };
21190
21195
  } finally {
21191
21196
  options.signal?.removeEventListener("abort", closePage);
21192
21197
  await page.close().catch(() => {});
@@ -21261,7 +21266,10 @@ function inputLine({ input, item, label }, labelOf) {
21261
21266
  if (item?.widgetType === "text" && item.config?.maxLength) parts.push(`, at most ${item.config.maxLength} characters`);
21262
21267
  if (item?.widgetType === "checkbox" && item.config?.displayAs === "button") parts.push(", a button: true runs it once");
21263
21268
  const options = optionsOf(item);
21264
- if (options) parts.push(`, one of: ${Object.keys(options).map((k) => `"${k}"`).join(", ")}`);
21269
+ if (item?.widgetType === "dynamicValueList") {
21270
+ const defaults = Object.keys(options ?? {});
21271
+ parts.push(", options computed by the solve from other inputs: selva_solve lists the current ones" + (defaults.length ? ` (defaults: ${defaults.map((k) => `"${k}"`).join(", ")})` : ""));
21272
+ } else if (options) parts.push(`, one of: ${Object.keys(options).map((k) => `"${k}"`).join(", ")}`);
21265
21273
  if (input.default !== void 0) parts.push(`, default ${JSON.stringify(input.default)}`);
21266
21274
  const condition = conditionText(item?.visibilityCondition, labelOf);
21267
21275
  if (condition) parts.push(`, ${condition}`);
@@ -21347,7 +21355,7 @@ function resolveValues(described, given) {
21347
21355
  * them, holding `given` where the model set it and the default otherwise. Geometry, files,
21348
21356
  * colours and lists stay as the definition has them.
21349
21357
  */
21350
- function viewInputs(schema, given) {
21358
+ function viewInputs(schema, given, solved = /* @__PURE__ */ new Map()) {
21351
21359
  const inputs = [];
21352
21360
  for (const d of describeInputs(schema)) {
21353
21361
  const { input, item, label } = d;
@@ -21355,10 +21363,12 @@ function viewInputs(schema, given) {
21355
21363
  if (item?.visible === false) continue;
21356
21364
  const value = given[label] ?? given[input.nickname] ?? given[input.id] ?? input.default;
21357
21365
  const description = item?.description || input.description || void 0;
21358
- const options = optionsOf(item);
21366
+ const computed = solved.get(input.id);
21367
+ const options = computed ?? optionsOf(item);
21359
21368
  if (options) {
21360
21369
  const names = Object.keys(options);
21361
- const name = names.find((n) => n === value) ?? names.find((n) => options[n] === value);
21370
+ const same = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
21371
+ const name = names.find((n) => same(n, value) || same(options[n], value)) ?? (computed ? names[0] : void 0);
21362
21372
  inputs.push({
21363
21373
  name: label,
21364
21374
  kind: "choice",
@@ -21397,6 +21407,144 @@ function viewInputs(schema, given) {
21397
21407
  }
21398
21408
  return inputs;
21399
21409
  }
21410
+ // src/lib/server/mcp/readable-outputs.ts
21411
+ /** Past this many entries a list or table shows its head. */
21412
+ var MAX_ENTRIES = 50;
21413
+ var isValueListType = (type) => type.endsWith(".DynamicValueListGoo");
21414
+ var isChartType = (type) => /(^|\.)PlotlyFigure$/.test(type);
21415
+ /** Compute may quote a goo's JSON once more. */
21416
+ function decode(data) {
21417
+ let value = data;
21418
+ for (let i = 0; i < 2 && typeof value === "string"; i++) try {
21419
+ value = JSON.parse(value);
21420
+ } catch {
21421
+ return;
21422
+ }
21423
+ return value;
21424
+ }
21425
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
21426
+ /**
21427
+ * Each input's options as this solve computed them, name to value, keyed by input id. Only plain
21428
+ * lists: an Options Table narrows by the picks on screen, which a static form can't follow.
21429
+ */
21430
+ function solvedOptions(schema, trees) {
21431
+ const found = /* @__PURE__ */ new Map();
21432
+ for (const tree of trees) {
21433
+ const schemaTarget = schema.outputs.find((o) => o.nickname === tree.ParamName)?.targetInputId;
21434
+ for (const item of Object.values(tree.InnerTree ?? {}).flat()) {
21435
+ if (!isValueListType(item.type)) continue;
21436
+ const payload = decode(item.data);
21437
+ if (!isRecord(payload) || !isRecord(payload.options)) continue;
21438
+ const target = typeof payload.targetInputId === "string" ? payload.targetInputId : schemaTarget;
21439
+ const options = Object.entries(payload.options).filter((e) => typeof e[1] === "string");
21440
+ if (target && options.length) found.set(target, Object.fromEntries(options));
21441
+ }
21442
+ }
21443
+ return found;
21444
+ }
21445
+ function head(list) {
21446
+ return {
21447
+ shown: list.slice(0, MAX_ENTRIES),
21448
+ more: Math.max(0, list.length - MAX_ENTRIES)
21449
+ };
21450
+ }
21451
+ var quoted = (names) => names.map((n) => JSON.stringify(n)).join(", ");
21452
+ var andMore = (more) => more ? `, and ${more} more` : "";
21453
+ /**
21454
+ * The options a Dynamic Value List output computed, by the label of the input they fill, and an
21455
+ * Options Table's valid combinations. These change with other inputs, so the form's own list is
21456
+ * only the author's defaults.
21457
+ */
21458
+ function readValueLists(schema, paramName, items) {
21459
+ const labels = new Map(describeInputs(schema).map((d) => [d.input.id, d.label]));
21460
+ const schemaTarget = schema.outputs.find((o) => o.nickname === paramName)?.targetInputId;
21461
+ const labelOf = (id) => labels.get(id) ?? id;
21462
+ const parts = [];
21463
+ const options = {};
21464
+ const combinations = [];
21465
+ for (const item of items) {
21466
+ const payload = decode(item.data);
21467
+ if (!isRecord(payload)) continue;
21468
+ const target = typeof payload.targetInputId === "string" ? payload.targetInputId : schemaTarget;
21469
+ const names = isRecord(payload.options) ? Object.keys(payload.options) : [];
21470
+ if (target && names.length) {
21471
+ const label = labelOf(target);
21472
+ const { shown, more } = head(names);
21473
+ options[label] = shown;
21474
+ parts.push(`options for "${label}": ${quoted(shown)}${andMore(more)}`);
21475
+ }
21476
+ const table = payload.pickTable;
21477
+ if (isRecord(table) && Array.isArray(table.inputs) && Array.isArray(table.rows)) {
21478
+ const columns = [...Array.isArray(table.by) ? table.by : [], ...table.inputs].map((id) => labelOf(String(id)));
21479
+ const rows = table.rows.filter(Array.isArray).map((r) => r.map(String));
21480
+ const { shown, more } = head(rows);
21481
+ combinations.push({
21482
+ inputs: columns,
21483
+ rows: shown,
21484
+ count: rows.length
21485
+ });
21486
+ parts.push(`valid combinations of ${quoted(columns)}: ` + shown.map((r) => `[${quoted(r)}]`).join(", ") + andMore(more));
21487
+ }
21488
+ }
21489
+ if (!parts.length) return void 0;
21490
+ return {
21491
+ text: parts.join("; "),
21492
+ structured: {
21493
+ ...Object.keys(options).length && { options },
21494
+ ...combinations.length && { combinations }
21495
+ }
21496
+ };
21497
+ }
21498
+ /** A trace's data as label/value pairs: pie labels, else x against y (or y against x for horizontal bars). */
21499
+ function pointsOf(trace) {
21500
+ const list = (key) => Array.isArray(trace[key]) ? trace[key] : void 0;
21501
+ if (list("labels") && list("values")) return [list("labels"), list("values")];
21502
+ const x = list("x");
21503
+ const y = list("y");
21504
+ if (x && y) return trace.orientation === "h" ? [y, x] : [x, y];
21505
+ if (y) return [y.map((_, i) => i), y];
21506
+ if (x) return [x.map((_, i) => i), x];
21507
+ }
21508
+ /** A Plotly figure's title and each trace's data. */
21509
+ function readCharts(items) {
21510
+ const parts = [];
21511
+ const charts = [];
21512
+ for (const item of items) {
21513
+ const figure = decode(item.data);
21514
+ if (!isRecord(figure) || !Array.isArray(figure.data)) continue;
21515
+ const rawTitle = (isRecord(figure.layout) ? figure.layout : {}).title;
21516
+ const title = typeof rawTitle === "string" ? rawTitle : isRecord(rawTitle) && typeof rawTitle.text === "string" ? rawTitle.text : void 0;
21517
+ const series = [];
21518
+ const traces = [];
21519
+ for (const trace of figure.data.filter(isRecord)) {
21520
+ const pairs = pointsOf(trace);
21521
+ if (!pairs) continue;
21522
+ const [labels, values] = pairs;
21523
+ const all = labels.map((l, i) => [String(l), values[i]]);
21524
+ const { shown, more } = head(all);
21525
+ const name = typeof trace.name === "string" && trace.name ? trace.name : void 0;
21526
+ const type = typeof trace.type === "string" ? trace.type : "scatter";
21527
+ series.push({
21528
+ name,
21529
+ type,
21530
+ points: shown,
21531
+ count: all.length
21532
+ });
21533
+ traces.push(`${name ? `"${name}" ` : ""}(${type}): ` + shown.map(([l, v]) => `${l} = ${JSON.stringify(v)}`).join(", ") + andMore(more));
21534
+ }
21535
+ charts.push({
21536
+ ...title && { title },
21537
+ series
21538
+ });
21539
+ const body = traces.length ? traces.join("; ") : "no data";
21540
+ parts.push(title ? `chart "${title}": ${body}` : body);
21541
+ }
21542
+ if (!charts.length) return void 0;
21543
+ return {
21544
+ text: parts.join(" | "),
21545
+ structured: { charts }
21546
+ };
21547
+ }
21400
21548
  // src/lib/server/mcp/lookup.ts
21401
21549
  var NAME_LOOKUP_PAGES = 5;
21402
21550
  var definitionArg = z.string().describe("A guid from selva_list_definitions, or the exact display name.");
@@ -21578,6 +21726,12 @@ async function summarizeSolve(res, schema, options) {
21578
21726
  lines.push(`${tree.ParamName}: ${JSON.stringify(value)}`);
21579
21727
  continue;
21580
21728
  }
21729
+ const read = items.every((i) => isValueListType(i.type)) ? readValueLists(schema, tree.ParamName, items) : items.every((i) => isChartType(i.type)) ? readCharts(items) : void 0;
21730
+ if (items.length && read) {
21731
+ structured[tree.ParamName] = read.structured;
21732
+ lines.push(`${tree.ParamName}: ${read.text}`);
21733
+ continue;
21734
+ }
21581
21735
  const counts = /* @__PURE__ */ new Map();
21582
21736
  for (const i of items) {
21583
21737
  const name = i.type.split(".").pop() ?? i.type;
@@ -21633,18 +21787,13 @@ function selvaViews() {
21633
21787
  prefersBorder: true
21634
21788
  })];
21635
21789
  }
21636
- var hdr;
21637
21790
  /**
21638
21791
  * 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.
21792
+ * from Selva's origin, which the server may not be able to reach from inside. Inlined at build
21793
+ * time, not read with `$app/server`'s `read`: a lazily imported asset never reaches the
21794
+ * production manifest, so `read` fails there and only there.
21640
21795
  */
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
- }
21796
+ var captureHdr = () => import("../../../chunks/baseHDR.js").then((m) => m.default);
21648
21797
  // src/lib/server/mcp/tools.ts
21649
21798
  /**
21650
21799
  * Selva's MCP tools: find a definition, read its form, solve it, read back numbers and files,
@@ -21777,6 +21926,16 @@ var CAPTURE_VIEWS = [
21777
21926
  "right",
21778
21927
  "bottom"
21779
21928
  ];
21929
+ var PREVIEW_LOOKS = [
21930
+ "technical",
21931
+ "studio",
21932
+ "showcase",
21933
+ "arctic",
21934
+ "xray",
21935
+ "lineart",
21936
+ "wireframe",
21937
+ "night"
21938
+ ];
21780
21939
  var DEFAULT_BACKGROUND = "#E6E6E6";
21781
21940
  var ListOutput = z.object({
21782
21941
  items: z.array(z.record(z.string(), z.unknown())),
@@ -21788,6 +21947,8 @@ var SolveOutput = z.object({
21788
21947
  errors: z.array(z.string()),
21789
21948
  warnings: z.array(z.string()),
21790
21949
  link: z.string(),
21950
+ /** For selva_capture_preview, which renders it without solving again. */
21951
+ solveId: z.string().optional(),
21791
21952
  response: z.unknown().optional()
21792
21953
  });
21793
21954
  var PublishOutput = z.object({
@@ -22052,16 +22213,24 @@ function selvaTools(origin, options) {
22052
22213
  link: pageOf(guid),
22053
22214
  stash
22054
22215
  });
22216
+ const solveId = await stash.put({
22217
+ kind: "solve",
22218
+ name: schema.name,
22219
+ contentType: "application/json",
22220
+ data: jsonBytes(res)
22221
+ });
22222
+ const text = `${summary.text}\nSolve id ${solveId}: selva_capture_preview draws it without solving again, for an hour.`;
22223
+ const structured = {
22224
+ ...summary.structured,
22225
+ solveId
22226
+ };
22055
22227
  const meta = apps ? { [SOLVE_VIEW_KEY]: {
22056
22228
  title: schema.name,
22229
+ look: schema.viewerOptions?.look,
22230
+ background: schema.viewerOptions?.backgroundColor ?? DEFAULT_BACKGROUND,
22057
22231
  load: {
22058
22232
  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
- }) }
22233
+ arguments: { token: solveId }
22065
22234
  },
22066
22235
  form: {
22067
22236
  tool: "selva_solve",
@@ -22070,11 +22239,12 @@ function selvaTools(origin, options) {
22070
22239
  ...version && { version }
22071
22240
  },
22072
22241
  valuesKey: "values",
22073
- inputs: viewInputs(schema, values)
22242
+ inputs: viewInputs(schema, values, solvedOptions(schema, res.values ?? []))
22074
22243
  }
22075
22244
  } } : void 0;
22076
22245
  if (detail !== "full") return {
22077
- ...summary,
22246
+ text,
22247
+ structured,
22078
22248
  meta
22079
22249
  };
22080
22250
  const response = {
@@ -22082,9 +22252,9 @@ function selvaTools(origin, options) {
22082
22252
  values: res.values?.filter((t) => !isPlumbing(t))
22083
22253
  };
22084
22254
  return {
22085
- ...summary,
22255
+ text,
22086
22256
  structured: {
22087
- ...summary.structured,
22257
+ ...structured,
22088
22258
  response
22089
22259
  },
22090
22260
  meta
@@ -22113,27 +22283,38 @@ function selvaTools(origin, options) {
22113
22283
  tool({
22114
22284
  name: "selva_capture_preview",
22115
22285
  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.",
22286
+ description: "Draws a solve in Selva's own 3D viewer and returns a picture per view, with the look and background the definition opens in unless `look` says otherwise. Pass `solve`, the solve id selva_solve returned, to draw that result without solving again; otherwise it solves `values` first and spends compute like selva_solve. Extra views cost no compute. Each picture is kept for an hour under a preview id: pass one to selva_set_cover_image to make it the cover.",
22117
22287
  input: z.object({
22118
22288
  definition: definitionArg,
22289
+ solve: z.string().optional().describe("A solve id from selva_solve. When given, `values` is ignored."),
22119
22290
  values: valuesArg,
22120
22291
  version: versionArg,
22121
- view: z.enum(CAPTURE_VIEWS).default("iso").describe("Camera direction."),
22292
+ views: z.array(z.enum(CAPTURE_VIEWS)).min(1).max(4).default(["iso"]).describe("Camera directions, a picture each."),
22293
+ look: z.enum(PREVIEW_LOOKS).optional().describe("The viewer look. Default: the definition's own. `night` lights lamps."),
22122
22294
  width: z.number().int().min(256).max(2048).default(1200),
22123
22295
  height: z.number().int().min(256).max(2048).default(800),
22124
22296
  grid: z.boolean().default(false).describe("Draw the viewer's ground grid.")
22125
22297
  }),
22126
22298
  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);
22299
+ async run(api, args, { signal }) {
22300
+ const { definition, solve, values, version, views, look, width, height, grid } = args;
22301
+ let schema;
22302
+ let res;
22303
+ if (solve) {
22304
+ const guid = await resolveDefinition(api, definition, signal);
22305
+ const held = await stash.get(solve, "solve");
22306
+ if (!held) throw new Error("That solve id has expired or is unknown. Leave `solve` out to solve `values` again.");
22307
+ ({schema} = await schemaFor(api, guid, version, signal));
22308
+ res = fromJsonBytes(held.data);
22309
+ } else ({schema, res} = await runSolve(api, definition, values, version, signal));
22129
22310
  let capture;
22130
22311
  try {
22131
22312
  capture = await captureSolve(res, {
22132
- view,
22313
+ views,
22133
22314
  width,
22134
22315
  height,
22135
22316
  grid,
22136
- look: schema.viewerOptions?.look,
22317
+ look: look ?? schema.viewerOptions?.look,
22137
22318
  background: schema.viewerOptions?.backgroundColor ?? DEFAULT_BACKGROUND,
22138
22319
  hdr: captureHdr,
22139
22320
  html: captureHtml,
@@ -22141,22 +22322,26 @@ function selvaTools(origin, options) {
22141
22322
  signal
22142
22323
  });
22143
22324
  } catch (err) {
22144
- if (err instanceof CaptureUnavailableError) throw new Error(`${err.message} An operator sets this up; the solve itself worked.`, { cause: err });
22325
+ if (err instanceof CaptureUnavailableError) throw new Error(`${err.message} An operator sets this up. The solve itself worked: selva_solve still returns its numbers.`, { cause: err });
22145
22326
  throw err;
22146
22327
  }
22147
22328
  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
- });
22329
+ const lines = [`${schema.name}, ${width}×${height}${look ? `, ${look} look` : ""}.`];
22330
+ for (const [i, png] of capture.pngs.entries()) {
22331
+ const previewId = await stash.put({
22332
+ kind: "preview",
22333
+ name: `${schema.name}.png`,
22334
+ contentType: "image/png",
22335
+ data: new Uint8Array(Buffer.from(png, "base64"))
22336
+ });
22337
+ lines.push(`${views[i]} view: preview id ${previewId}.`);
22338
+ }
22154
22339
  return {
22155
- text: `${schema.name}, ${view} view, ${width}×${height}. Preview id ${previewId}.`,
22156
- images: [{
22157
- data: capture.png,
22340
+ text: lines.join("\n"),
22341
+ images: capture.pngs.map((data) => ({
22342
+ data,
22158
22343
  mimeType: "image/png"
22159
- }]
22344
+ }))
22160
22345
  };
22161
22346
  }
22162
22347
  }),