@engenty/wizards-runtime 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +50 -3
  2. package/apps/runtime/dist/app.js +9 -2
  3. package/apps/runtime/dist/broker/call.js +2 -0
  4. package/apps/runtime/dist/broker/host.js +1 -0
  5. package/apps/runtime/dist/broker/rwx.js +38 -4
  6. package/apps/runtime/dist/db/client.js +12 -1
  7. package/apps/runtime/dist/db/migrations/tenant/0040_rwx_elements.sql +21 -0
  8. package/apps/runtime/dist/db/migrations/tenant/0041_broker_log_client.sql +1 -0
  9. package/apps/runtime/dist/db/migrations/tenant/meta/0040_snapshot.json +5153 -0
  10. package/apps/runtime/dist/db/migrations/tenant/meta/0041_snapshot.json +5160 -0
  11. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +14 -0
  12. package/apps/runtime/dist/db/schema.js +2 -0
  13. package/apps/runtime/dist/docs/dev/api.md +24 -2
  14. package/apps/runtime/dist/docs/dev/architecture.md +13 -2
  15. package/apps/runtime/dist/elements/caller.js +45 -0
  16. package/apps/runtime/dist/elements/catalogue.js +14 -0
  17. package/apps/runtime/dist/elements/connections.js +60 -0
  18. package/apps/runtime/dist/elements/gate.js +81 -0
  19. package/apps/runtime/dist/elements/knowledge.js +139 -0
  20. package/apps/runtime/dist/elements/outside.js +103 -0
  21. package/apps/runtime/dist/elements/specs.js +102 -0
  22. package/apps/runtime/dist/elements/wizards.js +59 -0
  23. package/apps/runtime/dist/env.js +5 -2
  24. package/apps/runtime/dist/health.js +50 -1
  25. package/apps/runtime/dist/mcp/elements.js +88 -0
  26. package/apps/runtime/dist/mcp/handler.js +2 -0
  27. package/apps/runtime/dist/mcp/scopes.js +5 -0
  28. package/apps/runtime/dist/prompts/authoring.md +2 -2
  29. package/apps/runtime/dist/prompts/tools.md +3 -0
  30. package/apps/runtime/dist/routes/api.js +2 -2
  31. package/apps/runtime/dist/routes/elements.js +76 -0
  32. package/apps/runtime/dist/services/work-ai.js +27 -19
  33. package/apps/runtime/dist/services/work-connections.js +2 -2
  34. package/apps/runtime/dist/tools/index.js +5 -4
  35. package/apps/runtime/dist/tools/skills.js +80 -54
  36. package/apps/runtime/dist/tools/space.js +8 -152
  37. package/apps/web/dist/assets/{AboutDialog-SpDcn8VZ.js → AboutDialog-DaWEIHFN.js} +1 -1
  38. package/apps/web/dist/assets/{CapabilitiesPage-Bgnm_3dk.js → CapabilitiesPage-Dt91U_sK.js} +2 -2
  39. package/apps/web/dist/assets/{ChangelogDialog-DAnjV6cZ.js → ChangelogDialog-Do7pwmFv.js} +1 -1
  40. package/apps/web/dist/assets/{CodeEditor-nxoOt8ge.js → CodeEditor-Cdox-51M.js} +1 -1
  41. package/apps/web/dist/assets/{EditorPage-B98C-9Nv.js → EditorPage-DS_a5K3s.js} +1 -1
  42. package/apps/web/dist/assets/{FlowPreview-aMfwcPul.js → FlowPreview-BPS86xzA.js} +1 -1
  43. package/apps/web/dist/assets/{LangSwitch-DpD0inR4.js → LangSwitch-BRHbi_Sd.js} +1 -1
  44. package/apps/web/dist/assets/{Marketplace-CpzD9pNQ.js → Marketplace-CS7JTgiv.js} +2 -2
  45. package/apps/web/dist/assets/{NewWizardChannels-D8IYLg_S.js → NewWizardChannels-D-OLsex6.js} +1 -1
  46. package/apps/web/dist/assets/{NewWizardPage-DlBt0Mfq.js → NewWizardPage-BM_pkk41.js} +1 -1
  47. package/apps/web/dist/assets/{OnboardingPage-ztHT01ah.js → OnboardingPage-Cpn5pubC.js} +1 -1
  48. package/apps/web/dist/assets/{PreviewPane-DC1kAi3x.js → PreviewPane-BOk1-yO4.js} +1 -1
  49. package/apps/web/dist/assets/{PublicRunner-D6lKP0j8.js → PublicRunner-CgzMZb0r.js} +1 -1
  50. package/apps/web/dist/assets/{ReadOnly-DFsuKPCw.js → ReadOnly-8DEx-ly3.js} +1 -1
  51. package/apps/web/dist/assets/{SettingsPage-DkHeCO2c.js → SettingsPage-CcrknFcI.js} +2 -2
  52. package/apps/web/dist/assets/{SetupPage-DZ8xRkfS.js → SetupPage-D5nzjgPU.js} +1 -1
  53. package/apps/web/dist/assets/{SharePage-494ZPsjQ.js → SharePage-PKHX8a8a.js} +1 -1
  54. package/apps/web/dist/assets/{SkillEditor-CqQMg2MC.js → SkillEditor-BsXTqNli.js} +1 -1
  55. package/apps/web/dist/assets/{Skills-CnhpgoOA.js → Skills-C_X1ZsKg.js} +1 -1
  56. package/apps/web/dist/assets/{SpacePage-CWlU_BZP.js → SpacePage-wZGqUoSQ.js} +2 -2
  57. package/apps/web/dist/assets/{UpdateCheck-BKNkNJyG.js → UpdateCheck-D6x7MqEl.js} +2 -2
  58. package/apps/web/dist/assets/changelog-M-eOBqgu.js +1 -0
  59. package/apps/web/dist/assets/{circle-alert-C8Ma-bPY.js → circle-alert-DJbCyxcg.js} +1 -1
  60. package/apps/web/dist/assets/{circle-check-Bu9Z3mlJ.js → circle-check-jqtsKi_b.js} +1 -1
  61. package/apps/web/dist/assets/{code-editor-CfTGqOpp.js → code-editor-BpCEnf8H.js} +2 -2
  62. package/apps/web/dist/assets/{code-xml-B4kLFZSj.js → code-xml-q88cSTV8.js} +1 -1
  63. package/apps/web/dist/assets/{connection-sign-in-Cngd_QDO.js → connection-sign-in-UJ6xk-TD.js} +1 -1
  64. package/apps/web/dist/assets/{eye-BpoKpIdt.js → eye-CgkvVlba.js} +1 -1
  65. package/apps/web/dist/assets/{host-C0WQlRKB.js → host-Bd_bon_c.js} +7 -7
  66. package/apps/web/dist/assets/{i18n-BJ7Ld6O6.js → i18n-0fUKyVRE.js} +1 -1
  67. package/apps/web/dist/assets/{index-ClVtdDUZ.js → index-DOgwxnto.js} +3 -3
  68. package/apps/web/dist/assets/{phone-Ctvf-Am-.js → phone-CjPvZ0nk.js} +1 -1
  69. package/apps/web/dist/assets/{read-aloud-Da_RSm2S.js → read-aloud-CLXo_asN.js} +1 -1
  70. package/apps/web/dist/assets/{runners-CyIvJIHr.js → runners-BoPaPsjN.js} +1 -1
  71. package/apps/web/dist/assets/{scroll-text-ChrjRu9Y.js → scroll-text-2BhJO_W7.js} +1 -1
  72. package/apps/web/dist/assets/{session-SXPtTWRK.js → session-CpYa5hwd.js} +1 -1
  73. package/apps/web/dist/assets/{theme-BCau3f6O.js → theme-Bj3wNQR0.js} +1 -1
  74. package/apps/web/dist/assets/{ui-Uqnx1UpK.js → ui-CktezodE.js} +1 -1
  75. package/apps/web/dist/assets/{upload-BchUnQGV.js → upload-CHGCFVZK.js} +1 -1
  76. package/apps/web/dist/assets/{useMutation-DEkZhp5c.js → useMutation-7_FOHoEl.js} +1 -1
  77. package/apps/web/dist/assets/{volume-2-CU_oy81Z.js → volume-2-Bw5KASy8.js} +1 -1
  78. package/apps/web/dist/index.html +13 -13
  79. package/apps/web/dist/mcp/flow.html +1 -1
  80. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +3 -0
  81. package/node_modules/@engenty/wizards-shared/dist/run.js +6 -0
  82. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +1 -1
  83. package/node_modules/@engenty/wizards-shared/dist/rwx.js +3 -0
  84. package/package.json +1 -1
  85. package/plugin/.claude-plugin/plugin.json +1 -1
  86. package/plugin/README.md +3 -0
  87. package/plugin/plugin.json +1 -1
  88. package/plugin/skills/work-in-space/SKILL.md +16 -0
  89. package/apps/web/dist/assets/changelog-BhMZS-rs.js +0 -1
@@ -0,0 +1,59 @@
1
+ import { createTool } from "@mastra/core/tools";
2
+ import { readableIds } from "../broker/rwx.js";
3
+ import { runReport, startRun } from "../services/runs.js";
4
+ import { listWizards } from "../services/wizards.js";
5
+ import { attempt } from "../tools/shared.js";
6
+ import { elementCall } from "./gate.js";
7
+ import { ELEMENT_SPECS } from "./specs.js";
8
+ /**
9
+ * The space's published wizards as tools of the catalogue: list them (`r` on each) and run one
10
+ * (`x`) as the person calling, who answers its pages as anyone running it does. Only a signed-in
11
+ * person runs a wizard this way: a guest reaches a wizard by its link, Goose and a run's step do
12
+ * not start runs.
13
+ */
14
+ /** Whether the caller is a person who may start runs. */
15
+ const runsAs = (caller) => (caller.who.kind === "person" || caller.who.kind === "admin") && caller.who.id
16
+ ? caller.who.id
17
+ : null;
18
+ export async function wizardTools(caller) {
19
+ const userId = runsAs(caller);
20
+ if (!userId) {
21
+ return {};
22
+ }
23
+ const spaceId = caller.space.id;
24
+ return {
25
+ wizard_list: createTool({
26
+ id: "wizard_list",
27
+ description: ELEMENT_SPECS.wizard_list.description(),
28
+ inputSchema: ELEMENT_SPECS.wizard_list.input,
29
+ execute: (input) => attempt(() => elementCall(caller, { action: "wizard_list", about: "wizards", perm: "r", input }, async () => {
30
+ const published = (await listWizards(userId, spaceId)).filter((w) => w.published);
31
+ const ok = new Set(await readableIds(spaceId, caller.subjects, "wizard", published.map((w) => w.id)));
32
+ return {
33
+ wizards: published
34
+ .filter((w) => ok.has(w.id))
35
+ .map((w) => ({ id: w.id, title: w.title, description: w.description ?? "" })),
36
+ };
37
+ })),
38
+ }),
39
+ wizard_run: createTool({
40
+ id: "wizard_run",
41
+ description: ELEMENT_SPECS.wizard_run.description(),
42
+ inputSchema: ELEMENT_SPECS.wizard_run.input,
43
+ execute: (input) => attempt(() => elementCall(caller, {
44
+ action: "wizard_run",
45
+ resource: { kind: "wizard", id: input.wizardId },
46
+ perm: "x",
47
+ input,
48
+ }, async () => {
49
+ const published = (await listWizards(userId, spaceId)).find((w) => w.id === input.wizardId && w.published);
50
+ if (!published) {
51
+ throw new Error(`No published wizard "${input.wizardId}" in this space.`);
52
+ }
53
+ const { runId, refused } = await startRun(userId, input.wizardId, input.answers);
54
+ const report = await runReport(userId, runId, input.waitSeconds);
55
+ return { ...report, ...(refused ? { refusedAnswers: refused } : {}) };
56
+ })),
57
+ }),
58
+ };
59
+ }
@@ -53,7 +53,7 @@ const port = num("API_PORT", 24368);
53
53
  /** From source the Vite dev server on :5181 serves the pages; built, this server does. */
54
54
  const fromSource = import.meta.url.endsWith(".ts");
55
55
  const sandboxImage = str("SANDBOX_IMAGE", "engenty-sandbox:latest");
56
- const ROLES = ["studio", "doors", "web", "runner", "all"];
56
+ const ROLES = ["studio", "doors", "api", "web", "runner", "all"];
57
57
  function role() {
58
58
  const given = str("RUNTIME_ROLE", "all");
59
59
  if (!ROLES.includes(given)) {
@@ -73,7 +73,9 @@ export const env = {
73
73
  /**
74
74
  * What this process does. `studio`: the makers' half (authoring, publishing, sign-in, MCP, the
75
75
  * studio's pages). `doors`: the customers' half (wizard pages, their API, shared results, the
76
- * plugins' public routes). `web`: both halves. `runner`: takes the runs that wait and drives
76
+ * plugins' public routes). `api`: outside clients alone, MCP and `/api/v1`, so they scale and
77
+ * fail apart from the studio (docs/plans/modular.md); `studio` serves them too until the cloud
78
+ * routes them to an `api` process. `web`: both halves. `runner`: takes the runs that wait and drives
77
79
  * them (it serves the routes too, for what the web hands it). `all`: everything in one process
78
80
  * (a runtime that runs alone). docs/plans/runner-process.md.
79
81
  */
@@ -83,6 +85,7 @@ export const env = {
83
85
  studio: ["studio", "web", "runner", "all"].includes(role()),
84
86
  doors: ["doors", "web", "runner", "all"].includes(role()),
85
87
  runner: ["runner", "all"].includes(role()),
88
+ api: ["api", "studio", "web", "runner", "all"].includes(role()),
86
89
  },
87
90
  runner: {
88
91
  /** This runner's name in the control database; a new one each start. */
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { monitorEventLoopDelay } from "node:perf_hooks";
5
5
  import { createClient } from "@libsql/client";
6
6
  import { packageVersion } from "./cli/home.js";
7
- import { openingTenants, probeControl } from "./db/client.js";
7
+ import { failingTenants, knownTenants, openingTenants, probeControl, tenantDb, } from "./db/client.js";
8
8
  import { lineAskedSince } from "./engine/runner.js";
9
9
  import { env } from "./env.js";
10
10
  import { probeObjects } from "./files/objects.js";
@@ -127,6 +127,52 @@ async function tenantsCheck() {
127
127
  await tx.rollback();
128
128
  return undefined;
129
129
  }
130
+ /** How often every tenant database is opened in the background, for `databases`. */
131
+ const SWEEP_MS = 60_000;
132
+ let swept = 0;
133
+ let sweeping = false;
134
+ /**
135
+ * Opens every known tenant database, one after the other, at most once a minute and never twice
136
+ * at once. An open one answers at once; one that fails (a migration, say) is tried again.
137
+ */
138
+ function sweepTenants(now) {
139
+ if (sweeping || now - swept < SWEEP_MS) {
140
+ return;
141
+ }
142
+ sweeping = true;
143
+ swept = now;
144
+ void (async () => {
145
+ try {
146
+ for (const id of await knownTenants()) {
147
+ await tenantDb(id).catch(() => undefined);
148
+ }
149
+ }
150
+ catch {
151
+ // the control database is `control`'s to report
152
+ }
153
+ finally {
154
+ sweeping = false;
155
+ }
156
+ })();
157
+ }
158
+ /**
159
+ * Whether the tenant databases open: every request of a tenant needs its own. The sweep runs
160
+ * behind the check, so the answer is what the last sweep and the requests since found. Some
161
+ * failing is `degraded`, all failing `down`.
162
+ */
163
+ export async function databasesCheck() {
164
+ sweepTenants(Date.now());
165
+ const failing = failingTenants();
166
+ if (!failing.length) {
167
+ return undefined;
168
+ }
169
+ const known = (await knownTenants()).length;
170
+ return {
171
+ status: failing.length >= known ? "down" : "degraded",
172
+ error: `${failing.length} of ${known} tenant databases don't open: ${failing[0].error}`,
173
+ detail: { failing: failing.map((f) => ({ id: f.id, at: new Date(f.at).toISOString() })) },
174
+ };
175
+ }
130
176
  async function lineCheck() {
131
177
  const { runners, oldestWaiting } = await lineState();
132
178
  const now = Date.now();
@@ -193,6 +239,9 @@ function checksOf() {
193
239
  const all = [
194
240
  { name: "control", required: true, run: controlCheck, when: true },
195
241
  { name: "tenants", required: true, run: tenantsCheck, when: true },
242
+ // Not required: a database that doesn't open leaves the others serving; the status page
243
+ // reads this check by name.
244
+ { name: "databases", required: false, run: databasesCheck, when: serves.studio },
196
245
  {
197
246
  name: "objects",
198
247
  required: true,
@@ -0,0 +1,88 @@
1
+ import { z } from "zod";
2
+ import { callOutside, RUN_COMMAND } from "../elements/outside.js";
3
+ import { ELEMENT_SPECS, ELEMENT_TOOL_NAMES } from "../elements/specs.js";
4
+ import { prompt } from "../prompts.js";
5
+ import { listSpaces } from "../services/spaces.js";
6
+ /**
7
+ * The space's elements as MCP tools (docs/plans/modular.md, phase 2): what a Work chat uses,
8
+ * for Claude Code, Codex or any MCP client signed in as a person. Made from the catalogue's specs
9
+ * (elements/specs.ts), one tool each, behind the scope it needs. Each takes the space it works in
10
+ * (`spaceId`, the person's first space when left out), checked against the token on every call
11
+ * (I2); who calls is the token's person, never an argument (I1).
12
+ */
13
+ const spaceId = z
14
+ .string()
15
+ .optional()
16
+ .describe("The space to work in, as list_spaces names it; the first space when left out.");
17
+ const READ_ONLY = new Set([
18
+ "space_search",
19
+ "space_list",
20
+ "page_read",
21
+ "table_read",
22
+ "space_document",
23
+ "skill_list",
24
+ "skill_load",
25
+ "skill_read",
26
+ "connection_list",
27
+ "wizard_list",
28
+ ]);
29
+ function answer(result) {
30
+ const body = result.ok
31
+ ? result.result
32
+ : { error: result.error, ...(result.data ? { data: result.data } : {}) };
33
+ return {
34
+ ...(result.ok ? {} : { isError: true }),
35
+ content: [{ type: "text", text: typeof body === "string" ? body : JSON.stringify(body) }],
36
+ };
37
+ }
38
+ export function registerElementTools(server, who) {
39
+ const outside = {
40
+ userId: who.userId,
41
+ role: who.role,
42
+ client: who.client,
43
+ tenantId: who.tenantId,
44
+ scopes: who.scopes,
45
+ };
46
+ const register = (name, scope, description, input) => {
47
+ if (!who.scopes.includes(scope)) {
48
+ return;
49
+ }
50
+ const withSpace = input.extend({ spaceId });
51
+ server.registerTool(name, {
52
+ title: name.replace(/_/g, " "),
53
+ description,
54
+ inputSchema: withSpace,
55
+ annotations: {
56
+ readOnlyHint: READ_ONLY.has(name),
57
+ // A connection's action may write, send or delete in a connected account.
58
+ destructiveHint: name === "connection_call",
59
+ // Running a wizard or a command reaches past the person's own data.
60
+ openWorldHint: !READ_ONLY.has(name),
61
+ },
62
+ }, (async (args) => {
63
+ const { spaceId: space, ...rest } = args;
64
+ return answer(await callOutside(outside, typeof space === "string" ? space : undefined, name, rest, AbortSignal.timeout(10 * 60_000)));
65
+ }));
66
+ };
67
+ for (const name of ELEMENT_TOOL_NAMES) {
68
+ const spec = ELEMENT_SPECS[name];
69
+ register(name, spec.scope, spec.description(), spec.input);
70
+ }
71
+ register("run_command", RUN_COMMAND.scope, "Runs a shell command in your sandbox for this space, where the skills you loaded put their scripts (skills/<name>/). It keeps its files while you use it.", RUN_COMMAND.input);
72
+ // A client that only uses a space still needs to know which spaces there are.
73
+ if (who.scopes.includes("elements:read") && !who.scopes.includes("wizards:read")) {
74
+ server.registerTool("list_spaces", {
75
+ title: "List spaces",
76
+ description: prompt("mcp", "tool.list_spaces"),
77
+ inputSchema: z.object({}),
78
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
79
+ }, (async () => ({
80
+ content: [
81
+ {
82
+ type: "text",
83
+ text: JSON.stringify((await listSpaces(who.userId)).map((p) => ({ id: p.id, name: p.name }))),
84
+ },
85
+ ],
86
+ })));
87
+ }
88
+ }
@@ -9,6 +9,7 @@ import { asRole } from "../services/access.js";
9
9
  import { tenantStatus } from "../tenants/control.js";
10
10
  import { serverText } from "../texts.js";
11
11
  import { authenticate, principalOf } from "./auth.js";
12
+ import { registerElementTools } from "./elements.js";
12
13
  import { registerFlowApp } from "./flow-app.js";
13
14
  import { appKind, clientNameOf, noteChecked, noteRequest } from "./seen.js";
14
15
  import { registerPrompts, registerTools } from "./tools.js";
@@ -75,6 +76,7 @@ export function mcpHandler() {
75
76
  });
76
77
  const who = principalOf(ctx.authInfo);
77
78
  registerTools(server, who);
79
+ registerElementTools(server, who);
78
80
  registerPrompts(server);
79
81
  registerFlowApp(server);
80
82
  return server;
@@ -9,6 +9,11 @@ export const SCOPES = [
9
9
  "wizards:publish",
10
10
  "runs:test",
11
11
  "runs:read",
12
+ // Using a space's elements (docs/plans/modular.md): reading its data, reading its skills and
13
+ // wizards, running them.
14
+ "data:read",
15
+ "elements:read",
16
+ "elements:run",
12
17
  ];
13
18
  /** The protected resource OAuth tokens are bound to (RFC 8707 / RFC 9728). */
14
19
  export const MCP_RESOURCE = `${env.appUrl}/api/mcp`;
@@ -506,11 +506,11 @@ In a chat, show_view draws the view in the chat for everyone in it. The data is
506
506
  In a chat a view may also:
507
507
  - ask the AI: Button { label, action: "ask", prompt? } — the person who taps it says the prompt (else the label) in the chat, and you answer it
508
508
  - open a file: Button { label, action: "open", target: a file id }
509
- - point to a thing of the space: Ref { title, open, subtitle?, meta? } — open is what search_space gave as "open" ("p:…", "t:…", "f:…"), or "chat:<id>", "wizard:<id>"
509
+ - point to a thing of the space: Ref { title, open, subtitle?, meta? } — open is what space_search gave as "open" ("p:…", "t:…", "f:…"), or "chat:<id>", "wizard:<id>"
510
510
  - ask for answers: one Form { title?, submit, children: [Field ids] } with Field { name, kind, label, required?, options?, value?, placeholder?, help?, multiple? }
511
511
  kind: text, textarea, number, select, multiselect (both need options: [texts]), date, email, url, toggle, color, image (a picture or the camera), file, location (where the person is), audio (a recording), signature
512
512
  value prefills what you already know from the chat; the person still checks it. The answers come back as that person's message; once someone sent them, the form shows them.
513
- A file id is the space's file: what search_space gave after "f:", or a file in a message. Media and files come from the space only, never from an address on the web.
513
+ A file id is the space's file: what space_search gave after "f:", or a file in a message. Media and files come from the space only, never from an address on the web.
514
514
  Never ask for passwords, card numbers or other secrets in a Form.
515
515
  Use a view when rows, figures, a comparison or a few questions answer better than text: write one short sentence around it, not the same content again. For a short answer, write text.
516
516
 
@@ -157,6 +157,9 @@ No file "${path}" in ${skill}. Its files: ${files}.
157
157
  <!-- section: note.skill_folder -->
158
158
  This skill's folder is in the sandbox at ${folder}: its SKILL.md and every file. Run its scripts with run_command from the working directory, e.g. python3 ${folder}/scripts/<file>.py, and install what they import first (pip install, npm install). Write what you make outside ${folder}.
159
159
 
160
+ <!-- section: note.skill_scripts_refused -->
161
+ This skill's scripts may not run for whoever this step works for: the space's rules keep them closed. Follow its instructions without them.
162
+
160
163
  <!-- section: note.skill_folder_failed -->
161
164
  This skill's folder could not be put into the sandbox (${error}): its scripts can't run in this step. Follow its instructions without them.
162
165
 
@@ -42,7 +42,7 @@ const importSchema = z.object({
42
42
  publish: z.boolean().default(false),
43
43
  });
44
44
  /** Runs a call in the caller's tenant, as the caller's role. */
45
- const inTenantAs = async (who, fn) => {
45
+ export const inTenantAs = async (who, fn) => {
46
46
  try {
47
47
  return await withTenant(who.tenantId, () => asRole(who.role, fn));
48
48
  }
@@ -73,7 +73,7 @@ const tooLarge = bodyLimit({
73
73
  * The caller of an API call, signed in like an MCP client (access token or API key), with the
74
74
  * scopes the call needs; or the answer that turns it away.
75
75
  */
76
- async function caller(c, scopes) {
76
+ export async function caller(c, scopes) {
77
77
  const authInfo = await authenticate(c.req.raw);
78
78
  if (authInfo instanceof Response) {
79
79
  return authInfo;
@@ -0,0 +1,76 @@
1
+ import { Hono } from "hono";
2
+ import { z } from "zod";
3
+ import { clientOf } from "../clients.js";
4
+ import { callOutside, RUN_COMMAND } from "../elements/outside.js";
5
+ import { ELEMENT_SPECS, ELEMENT_TOOL_NAMES } from "../elements/specs.js";
6
+ import { caller, inTenantAs } from "./api.js";
7
+ /**
8
+ * The space's elements on the API (docs/plans/modular.md, phase 2): the same calls as the MCP
9
+ * tools, made from the catalogue's specs, for a program with a key or token. `GET` lists the
10
+ * calls the token may make with their inputs as JSON Schema; `POST /:name` makes one, as the
11
+ * token's person, in the space of the path (checked against the token, I2).
12
+ */
13
+ const calls = () => [
14
+ ...ELEMENT_TOOL_NAMES.map((name) => ({
15
+ name,
16
+ scope: ELEMENT_SPECS[name].scope,
17
+ description: ELEMENT_SPECS[name].description(),
18
+ input: ELEMENT_SPECS[name].input,
19
+ })),
20
+ {
21
+ name: "run_command",
22
+ scope: RUN_COMMAND.scope,
23
+ description: "Runs a shell command in the sandbox where loaded skills put their scripts.",
24
+ input: RUN_COMMAND.input,
25
+ },
26
+ ];
27
+ const callBody = z.object({ input: z.record(z.string(), z.unknown()).default({}) });
28
+ export const elementRoutes = new Hono()
29
+ .get("/spaces/:spaceId/elements", async (c) => {
30
+ const who = await caller(c, []);
31
+ if (who instanceof Response) {
32
+ return who;
33
+ }
34
+ return c.json({
35
+ calls: calls()
36
+ .filter((call) => who.scopes.includes(call.scope))
37
+ .map(({ input, ...call }) => ({
38
+ ...call,
39
+ input: z.toJSONSchema(input, { unrepresentable: "any" }),
40
+ })),
41
+ });
42
+ })
43
+ .post("/spaces/:spaceId/elements/:name", async (c) => {
44
+ const who = await caller(c, []);
45
+ if (who instanceof Response) {
46
+ return who;
47
+ }
48
+ const name = c.req.param("name");
49
+ const call = calls().find((k) => k.name === name);
50
+ if (!call) {
51
+ return c.json({ error: `No call ${name}.`, code: "not_found" }, 404);
52
+ }
53
+ if (!who.scopes.includes(call.scope)) {
54
+ return c.json({ error: "This token isn’t allowed to do that.", code: "insufficient_scope" }, 403);
55
+ }
56
+ const body = callBody.safeParse(await c.req.json().catch(() => ({})));
57
+ if (!body.success) {
58
+ return c.json({ error: "Invalid input", code: "invalid", issues: body.error.issues }, 400);
59
+ }
60
+ const result = await inTenantAs(who, () => callOutside({
61
+ userId: who.userId,
62
+ role: who.role,
63
+ client: clientOf(c) ?? who.client,
64
+ tenantId: who.tenantId,
65
+ scopes: who.scopes,
66
+ }, c.req.param("spaceId"), name, body.data.input, c.req.raw.signal)).catch((err) => ({
67
+ ok: false,
68
+ error: String(err?.message ?? err).slice(0, 400),
69
+ status: err?.code === "not_found" ? 404 : 500,
70
+ }));
71
+ if (result.ok) {
72
+ return c.json({ result: result.result });
73
+ }
74
+ const status = "status" in result ? result.status : 403;
75
+ return c.json({ error: result.error, ...("data" in result ? { data: result.data } : {}) }, status);
76
+ });
@@ -4,7 +4,8 @@ import { createTool } from "@mastra/core/tools";
4
4
  import { z } from "zod";
5
5
  import { sortedTools } from "../agents/space-agent.js";
6
6
  import { chatTurnWay } from "../agents/subscription.js";
7
- import { subjectsOfPerson } from "../broker/rwx.js";
7
+ import { personCaller } from "../elements/caller.js";
8
+ import { elementTools } from "../elements/catalogue.js";
8
9
  import { currentFeatures } from "../features.js";
9
10
  import { HarnessModel } from "../harness/index.js";
10
11
  import { managed } from "../manage.js";
@@ -15,11 +16,10 @@ import { sandboxCapabilities, shellToolDescription } from "../sandbox/index.js";
15
16
  import { currentTenant } from "../tenants/tenant.js";
16
17
  import { assistantToolPlugin, assistantToolRisk, assistantToolsOf } from "../tools/plugin.js";
17
18
  import { clip } from "../tools/shared.js";
18
- import { skillsBlock, skillToolsOf } from "../tools/skills.js";
19
+ import { skillsBlock } from "../tools/skills.js";
19
20
  import { roleOf } from "./access.js";
20
21
  import { ClientSteps } from "./client-steps.js";
21
22
  import { activeSkills } from "./skills.js";
22
- import { searchKnowledge } from "./space-index.js";
23
23
  import { holdCall } from "./work-approvals.js";
24
24
  import { workConnectionTools } from "./work-connections.js";
25
25
  import { chatSandbox } from "./work-sandbox.js";
@@ -34,10 +34,12 @@ export const TURN_KEY = "workTurn";
34
34
  export const TURN_MS = 20 * 60_000;
35
35
  /** Steps one turn may take. */
36
36
  export const MAX_STEPS = 16;
37
- const instructionsFor = (space, skills) => [
37
+ const instructionsFor = (space, skills, knowledge) => [
38
38
  `You are the AI of the space "${space}" in engenty wizards. The team of the space talks with you and with each other in this chat.`,
39
39
  'Each message of a person comes as <user name="…">; answer the person who asked you, in their language, and call them by their name only when it helps.',
40
- "Before you answer about the space (its clients, matters, files, data), look it up with search_space; say where you found it. When you can't find it, say so.",
40
+ knowledge
41
+ ? "Before you answer about the space (its clients, matters, files, data), look it up with space_search; say where you found it. When you can't find it, say so."
42
+ : "The space has no knowledge yet: say so when you're asked about its clients, matters, files or data.",
41
43
  "Write short, plain answers. Use lists or a table where they help. Rows, figures, a comparison or a few questions to the team can be a view instead: show_view.",
42
44
  skills,
43
45
  ]
@@ -127,22 +129,24 @@ async function toolsFor(resolved, space, userId, signal, choice = {}, chatId = n
127
129
  chatId: chatId ?? approved?.chatId ?? null,
128
130
  byAdmin: approved?.byAdmin,
129
131
  });
130
- const skills = await spaceSkills(space.id);
131
- // The turn reads as the person who asked: what they may not read, the AI does not find.
132
- const who = subjectsOfPerson(userId, await roleOf(userId));
132
+ // The turn reads as the person who asked: what they may not read, the AI does not find. Its
133
+ // Knowledge and skills come from the tool catalogue (elements/), as a step's and Goose's do.
134
+ const caller = personCaller({
135
+ space,
136
+ userId,
137
+ role: await roleOf(userId),
138
+ signal,
139
+ chatId: chatId ?? approved?.chatId ?? null,
140
+ sandbox: sandbox.skill,
141
+ });
133
142
  const tools = {
134
- search_space: createTool({
135
- id: "search_space",
136
- description: "Searches the space's knowledge: its documents, pages, tables and the sources its plugins bring. Returns the best matches with where they are.",
137
- inputSchema: z.object({ query: z.string().min(2).max(300) }),
138
- execute: async ({ query }) => {
139
- const found = await searchKnowledge(space.id, query, { limit: 8, signal, who });
140
- return { hits: found.hits };
141
- },
142
- }),
143
+ ...(await elementTools(caller, {
144
+ knowledge: true,
145
+ skills: await spaceSkills(space.id),
146
+ wizards: true,
147
+ })),
143
148
  show_view: showView(),
144
149
  ...sandbox.tools,
145
- ...(skills ? skillToolsOf(skills, () => { }, sandbox.skill) : {}),
146
150
  ...connections.tools,
147
151
  ...(await assistantToolsOf({
148
152
  tenantId: currentTenant(),
@@ -237,7 +241,11 @@ export async function workTurn(turn, signal, steps, choice = {}) {
237
241
  const block = skills
238
242
  ? skillsBlock(skills, { tools: true, sandbox: sandboxCapabilities() !== null })
239
243
  : "";
240
- return { resolved, tools, instructions: instructionsFor(turn.space.name, block) };
244
+ return {
245
+ resolved,
246
+ tools,
247
+ instructions: instructionsFor(turn.space.name, block, "space_search" in tools),
248
+ };
241
249
  }
242
250
  export function lazyTurn(turn, choice = {}) {
243
251
  const controller = new AbortController();
@@ -15,7 +15,7 @@ import { holdCall } from "./work-approvals.js";
15
15
  * again, for the space's admins under the bell; an admin's yes runs it.
16
16
  */
17
17
  /** Who a chat's turn calls as: the person, an admin where their role in the organization says so. */
18
- async function chatWho(userId) {
18
+ export async function chatWho(userId) {
19
19
  const role = await roleOf(userId);
20
20
  return { kind: isAdminRole(role) ? "admin" : "person", id: userId };
21
21
  }
@@ -23,7 +23,7 @@ async function chatWho(userId) {
23
23
  * The connections of the space this person reaches in a chat: those open to their role, and of
24
24
  * the ones in which each person signs in, only those they signed in to.
25
25
  */
26
- async function chatConnectionTools(spaceId, userId, who) {
26
+ export async function chatConnectionTools(spaceId, userId, who) {
27
27
  const rows = await listSpaceConnections(spaceId);
28
28
  const own = rows.some((r) => r.signIn === "person")
29
29
  ? new Set((await db.query.spaceConnectionSignIn.findMany({
@@ -4,6 +4,8 @@ import { createTool } from "@mastra/core/tools";
4
4
  import { z } from "zod";
5
5
  import { brokerHost, reachesOutside, whereOf, whoOf } from "../broker/index.js";
6
6
  import { documentMime, parseDocument } from "../documents/parse.js";
7
+ import { stepCaller } from "../elements/caller.js";
8
+ import { elementTools } from "../elements/catalogue.js";
7
9
  import { generateImageMedia } from "../media/generate.js";
8
10
  import { markMedia } from "../media/marking.js";
9
11
  import { gatewayTools, isHarnessVendor, searchAllowed } from "../models.js";
@@ -20,8 +22,7 @@ import { assertPublicUrl, safeFetch } from "./net-guard.js";
20
22
  import { pageTools } from "./pages.js";
21
23
  import { pluginTools, spaceContextOf } from "./plugin.js";
22
24
  import { clip, FileKeeper } from "./shared.js";
23
- import { skillTools } from "./skills.js";
24
- import { spaceTools } from "./space.js";
25
+ import { skillsOf } from "./skills.js";
25
26
  import { storeTools } from "./store.js";
26
27
  // A request to a host is a send to that host; the broker holds a guest's run to the hosts in its grant.
27
28
  reachesOutside("http_request", { connection: "host", action: "http_request", kind: "send" });
@@ -172,10 +173,10 @@ export async function buildStepTools(step, ctx, resolved, uploads) {
172
173
  if (!idle) {
173
174
  Object.assign(tools, storeTools(ctx, uploads, files));
174
175
  }
175
- Object.assign(tools, await spaceTools(ctx));
176
176
  // The run's sandbox: a guest's run has none unless SANDBOX_GUESTS says so (engine/resources.ts).
177
177
  const sandbox = allowed.has("sandbox") ? ctx.resources.sandboxCapabilities() : null;
178
- Object.assign(tools, await skillTools(ctx, sandbox ? { handle: () => ctx.resources.sandboxHandle(), workdir: sandbox.workdir } : null));
178
+ // The space's Knowledge and skills, from the tool catalogue (elements/), for the run's holder.
179
+ Object.assign(tools, await elementTools(stepCaller(ctx, sandbox ? { handle: () => ctx.resources.sandboxHandle(), workdir: sandbox.workdir } : null), { knowledge: true, skills: await skillsOf(ctx) }));
179
180
  Object.assign(tools, mailTools(step, ctx, files));
180
181
  Object.assign(tools, await connectorTools(step, ctx, files));
181
182
  Object.assign(tools, await pluginTools(step, ctx));