@engenty/wizards-runtime 0.12.1 → 0.13.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 (129) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +42 -5
  2. package/apps/runtime/dist/app.js +15 -4
  3. package/apps/runtime/dist/credits/estimate.js +3 -3
  4. package/apps/runtime/dist/db/live-triggers.js +13 -3
  5. package/apps/runtime/dist/db/migrations/tenant/0027_space_skill.sql +48 -0
  6. package/apps/runtime/dist/db/migrations/tenant/meta/0027_snapshot.json +4120 -0
  7. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +7 -0
  8. package/apps/runtime/dist/db/schema.js +31 -0
  9. package/apps/runtime/dist/docs/dev/skills.md +116 -0
  10. package/apps/runtime/dist/docs/dev/wizard-format/agent-steps.md +20 -2
  11. package/apps/runtime/dist/docs/user-guide/models.md +105 -30
  12. package/apps/runtime/dist/docs/user-guide/skills.md +85 -0
  13. package/apps/runtime/dist/docs/user-guide/together.md +15 -2
  14. package/apps/runtime/dist/engine/decide.js +1 -1
  15. package/apps/runtime/dist/engine/requirements.js +139 -11
  16. package/apps/runtime/dist/engine/runner.js +47 -5
  17. package/apps/runtime/dist/engine/steps.js +23 -6
  18. package/apps/runtime/dist/engine/template.js +17 -0
  19. package/apps/runtime/dist/harness/model.js +4 -0
  20. package/apps/runtime/dist/link-preview.js +9 -0
  21. package/apps/runtime/dist/live/views.js +2 -0
  22. package/apps/runtime/dist/manage.js +25 -0
  23. package/apps/runtime/dist/mcp/handler.js +55 -1
  24. package/apps/runtime/dist/mcp/seen.js +47 -0
  25. package/apps/runtime/dist/models.js +206 -11
  26. package/apps/runtime/dist/motion-graphics/step.js +2 -2
  27. package/apps/runtime/dist/prompts/goose.md +15 -7
  28. package/apps/runtime/dist/prompts/safety.md +18 -0
  29. package/apps/runtime/dist/prompts/step.md +20 -2
  30. package/apps/runtime/dist/prompts/tools.md +33 -0
  31. package/apps/runtime/dist/routes/marketplace.js +3 -3
  32. package/apps/runtime/dist/routes/runs.js +5 -0
  33. package/apps/runtime/dist/routes/skills.js +84 -0
  34. package/apps/runtime/dist/routes/studio.js +103 -4
  35. package/apps/runtime/dist/safety.js +60 -18
  36. package/apps/runtime/dist/services/manage-reports.js +3 -0
  37. package/apps/runtime/dist/services/marketplace.js +7 -31
  38. package/apps/runtime/dist/services/pages.js +6 -2
  39. package/apps/runtime/dist/services/shares.js +5 -0
  40. package/apps/runtime/dist/services/skills-registry.js +209 -0
  41. package/apps/runtime/dist/services/skills.js +478 -0
  42. package/apps/runtime/dist/services/spaces.js +15 -1
  43. package/apps/runtime/dist/sync/records.js +81 -1
  44. package/apps/runtime/dist/texts.js +45 -0
  45. package/apps/runtime/dist/tools/index.js +7 -4
  46. package/apps/runtime/dist/tools/net-guard.js +8 -4
  47. package/apps/runtime/dist/tools/skills.js +197 -0
  48. package/apps/web/dist/assets/AboutDialog-B-JxkELB.js +1 -0
  49. package/apps/web/dist/assets/{ChangelogDialog-BWaEdlt3.js → ChangelogDialog-SwyId00t.js} +1 -1
  50. package/apps/web/dist/assets/CodeEditor-BwZsk5Al.js +2 -0
  51. package/apps/web/dist/assets/EditorPage-DQ_2FOzI.js +3 -0
  52. package/apps/web/dist/assets/{FlowPreview-DXpzFBRj.js → FlowPreview-DtSpjVTl.js} +1 -1
  53. package/apps/web/dist/assets/Marketplace-DoH4YO3D.js +2 -0
  54. package/apps/web/dist/assets/{NewWizardChannels-B5wuTm7J.js → NewWizardChannels-Tgoexgj4.js} +1 -1
  55. package/apps/web/dist/assets/NewWizardPage-B24AF482.js +7 -0
  56. package/apps/web/dist/assets/OnboardingPage-BEvq4slJ.js +1 -0
  57. package/apps/web/dist/assets/PreviewPane-B_v7Y8R7.js +10 -0
  58. package/apps/web/dist/assets/ProjectPage-ClRuhFJo.js +10 -0
  59. package/apps/web/dist/assets/PublicRunner-MicrpVsv.js +1 -0
  60. package/apps/web/dist/assets/{ReadOnly-Cap_e5ke.js → ReadOnly-BXjv-MSv.js} +1 -1
  61. package/apps/web/dist/assets/SettingsPage-DY8O1r43.js +2 -0
  62. package/apps/web/dist/assets/SetupPage-BOVkVpMu.js +1 -0
  63. package/apps/web/dist/assets/{SharePage-DEeVGatD.js → SharePage-DXGzJSnR.js} +1 -1
  64. package/apps/web/dist/assets/SkillEditor-BzzTDeaU.js +1 -0
  65. package/apps/web/dist/assets/changelog-BLdS-0Bj.js +1 -0
  66. package/apps/web/dist/assets/code-xml-TwKzzMtA.js +1 -0
  67. package/apps/web/dist/assets/{dist-BwhPmMDu.js → dist-BdDd1FxP.js} +1 -1
  68. package/apps/web/dist/assets/dist-EBVTpvRr.js +10 -0
  69. package/apps/web/dist/assets/dist-GlRRx9Xl.js +1 -0
  70. package/apps/web/dist/assets/dist-H1UN89OA.js +1 -0
  71. package/apps/web/dist/assets/eye-Brd-xPUJ.js +1 -0
  72. package/apps/web/dist/assets/i18n-8-Sw11tB.js +55 -0
  73. package/apps/web/dist/assets/index-OsdQFHmh.js +49 -0
  74. package/apps/web/dist/assets/index-QPipX5Fi.css +1 -0
  75. package/apps/web/dist/assets/json-CEsfHdlZ.js +1 -0
  76. package/apps/web/dist/assets/{lock-D-CjMpqn.js → lock-C0uxcOlq.js} +1 -1
  77. package/apps/web/dist/assets/markdown-5-I9_izp.js +29 -0
  78. package/apps/web/dist/assets/{oss-credits-CUpVhKSr.js → oss-credits-DpRWUPjD.js} +1 -1
  79. package/apps/web/dist/assets/{phone-CXSrxw3H.js → phone-DhkHteoJ.js} +1 -1
  80. package/apps/web/dist/assets/{runners-D71NjXtA.js → runners-G-XYaDgR.js} +1 -1
  81. package/apps/web/dist/assets/{session-B2LtqeDq.js → session-BWI-KENJ.js} +1 -1
  82. package/apps/web/dist/assets/theme-D7krsx0_.js +11 -0
  83. package/apps/web/dist/assets/ui-DSXG3f49.js +83 -0
  84. package/apps/web/dist/assets/{upload-hLkuT3Q6.js → upload-BYZTwJTD.js} +1 -1
  85. package/apps/web/dist/assets/{useMutation-C3XBoSVf.js → useMutation-D0QP_k2-.js} +1 -1
  86. package/apps/web/dist/assets/{volume-2-DIxdTlaA.js → volume-2-CVHoxdGM.js} +1 -1
  87. package/apps/web/dist/index.html +9 -8
  88. package/apps/web/dist/mcp/flow.html +66 -66
  89. package/node_modules/@engenty/wizards/dist/plugin/studio.d.ts +3 -2
  90. package/node_modules/@engenty/wizards-shared/dist/assistant.d.ts +1 -0
  91. package/node_modules/@engenty/wizards-shared/dist/assistant.js +5 -0
  92. package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +107 -0
  93. package/node_modules/@engenty/wizards-shared/dist/definition.js +67 -4
  94. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +18 -0
  95. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +18 -0
  96. package/node_modules/@engenty/wizards-shared/dist/live.d.ts +1 -1
  97. package/node_modules/@engenty/wizards-shared/dist/marketplace.d.ts +0 -5
  98. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +62 -0
  99. package/node_modules/@engenty/wizards-shared/dist/run.js +52 -0
  100. package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +165 -0
  101. package/node_modules/@engenty/wizards-shared/dist/skills.js +346 -0
  102. package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +4 -2
  103. package/node_modules/@engenty/wizards-shared/dist/sync.js +2 -1
  104. package/node_modules/@engenty/wizards-shared/dist/tiers.d.ts +195 -0
  105. package/node_modules/@engenty/wizards-shared/dist/tiers.js +98 -0
  106. package/package.json +7 -7
  107. package/plugin/.claude-plugin/plugin.json +1 -1
  108. package/plugin/plugin.json +1 -1
  109. package/apps/web/dist/assets/AboutDialog-uGYGy2R2.js +0 -1
  110. package/apps/web/dist/assets/CodeEditor-B5hV1IvK.js +0 -2
  111. package/apps/web/dist/assets/EditorPage-j9BOx5-V.js +0 -3
  112. package/apps/web/dist/assets/Marketplace-DSo6uZF6.js +0 -2
  113. package/apps/web/dist/assets/NewWizardPage-Ci1ZsTJk.js +0 -7
  114. package/apps/web/dist/assets/OnboardingPage-QkdluEZk.js +0 -1
  115. package/apps/web/dist/assets/PreviewPane-swAH89un.js +0 -10
  116. package/apps/web/dist/assets/ProjectPage-Djv5EOYU.js +0 -1
  117. package/apps/web/dist/assets/PublicRunner-Bt8gMxit.js +0 -1
  118. package/apps/web/dist/assets/SettingsPage-C2rmXm_Q.js +0 -2
  119. package/apps/web/dist/assets/SetupPage-CbqGgFPZ.js +0 -1
  120. package/apps/web/dist/assets/changelog-DAY6ZEyy.js +0 -1
  121. package/apps/web/dist/assets/dist-DVpDdhG9.js +0 -1
  122. package/apps/web/dist/assets/dist-DzdNG7Sf.js +0 -10
  123. package/apps/web/dist/assets/i18n-B3J2ypKu.js +0 -55
  124. package/apps/web/dist/assets/index-Dxwbli0m.css +0 -1
  125. package/apps/web/dist/assets/index-WY5lJ_-h.js +0 -49
  126. package/apps/web/dist/assets/json-D2GVvTXK.js +0 -1
  127. package/apps/web/dist/assets/markdown-DwdMW7q0.js +0 -29
  128. package/apps/web/dist/assets/theme-Dab079EV.js +0 -11
  129. package/apps/web/dist/assets/ui-DQX_CQ7c.js +0 -83
@@ -7,6 +7,7 @@ import { PRESENCE_KINDS } from "@engenty/wizards-shared/live";
7
7
  import { PROJECT_FILE_KINDS } from "@engenty/wizards-shared/projects";
8
8
  import { CLASS_NAMES, isCreditsRef, modelLabel } from "@engenty/wizards-shared/providers";
9
9
  import { note } from "@engenty/wizards-shared/run";
10
+ import { MAX_MASK_LABEL_CHARS, MAX_MASK_LABELS, modelPolicySchema, } from "@engenty/wizards-shared/tiers";
10
11
  import { PACKAGE_EXTENSION, PACKAGE_MAX_BYTES, PACKAGE_MIME, } from "@engenty/wizards-shared/wizard-package";
11
12
  import { generateText } from "ai";
12
13
  import { Hono } from "hono";
@@ -34,8 +35,8 @@ import { detectHarness, detectHarnesses, HARNESS_IDS, harness, installSpec, } fr
34
35
  import { closeTerminal, openTerminal, resizeTerminal, subscribeTerminal, writeTerminal, } from "../harness/terminal.js";
35
36
  import { connectorsView, filesView, spacesView, translationsView, wizardsView, wizardView, } from "../live/views.js";
36
37
  import { downloadLocalModel, localModels, removeLocalModel, startLocalOllama, } from "../local-models.js";
37
- import { installMail, managed, renameTenant, saveOrganizationProfile, tenantInfo, tenantMembers, userInfo, } from "../manage.js";
38
- import { seenApps } from "../mcp/seen.js";
38
+ import { installMail, ManageError, managed, renameTenant, saveModelPolicy, saveModelTier, saveOrganizationProfile, tenantInfo, tenantMembers, tryMasking, userInfo, } from "../manage.js";
39
+ import { checkedApps, seenApps } from "../mcp/seen.js";
39
40
  import { generateImageMedia, generateSpeechMedia, generateVideoMedia } from "../media/generate.js";
40
41
  import { transcribeAudio } from "../media/transcribe.js";
41
42
  import { errorText, saidOf } from "../model-errors.js";
@@ -125,6 +126,8 @@ const localModelName = z
125
126
  .min(1)
126
127
  .max(120)
127
128
  .regex(/^[\w.:/-]+$/);
129
+ /** The Manage-App's masking errors, passed on as it sends them: 502 labels, 503 the detector. */
130
+ const MASKING_CODES = new Set(["labels_unavailable", "masking_unavailable"]);
128
131
  const modelsInput = z.object({
129
132
  source: z.enum([...HARNESS_IDS, "account", "own"]).optional(),
130
133
  bindings: z.partialRecord(z.enum(MODEL_CLASSES), z.string().max(160)).optional(),
@@ -140,6 +143,11 @@ const modelsInput = z.object({
140
143
  function mayChangeModels(user) {
141
144
  return !managed || user.role === "owner" || user.role === "admin";
142
145
  }
146
+ /** The model settings for the person who asks: the key hints only for those who change the keys. */
147
+ async function settingsFor(c) {
148
+ const settings = await modelSettings(requestLang(c));
149
+ return mayChangeModels(c.get("user")) ? settings : { ...settings, keyHints: {} };
150
+ }
143
151
  /** A binding the cloud can run: a provider's model or the credits, no client, no local model. */
144
152
  function cloudBinding(ref) {
145
153
  return (isCreditsRef(ref) || /^(openai|anthropic|google|fal|elevenlabs|replicate|gateway):/.test(ref));
@@ -540,6 +548,7 @@ export const studio = new Hono()
540
548
  writable,
541
549
  message,
542
550
  extra: body.extra,
551
+ model: body.model,
543
552
  page,
544
553
  browserTools: body.tools,
545
554
  lang: body.lang,
@@ -1415,6 +1424,15 @@ export const studio = new Hono()
1415
1424
  })
1416
1425
  // What each AI client did with the MCP server since the start: the test on "Integrate".
1417
1426
  .get("/integrations/seen", (c) => c.json(seenApps(c.get("user").tenantId)))
1427
+ // The apps members used on the spaces, allowed or refused by the organization's model policy.
1428
+ // Who used which app is for the organization's owners and admins.
1429
+ .get("/model-policy/apps", (c) => {
1430
+ const user = c.get("user");
1431
+ if (!mayChangeModels(user)) {
1432
+ return c.json({ error: say(c, "onlyOrganizationAdminsChange"), code: "forbidden" }, 403);
1433
+ }
1434
+ return c.json({ apps: checkedApps(user.tenantId) });
1435
+ })
1418
1436
  .get("/local/models", (c) => (managed ? c.notFound() : c.json(localModelSettings())))
1419
1437
  .put("/local/models", async (c) => {
1420
1438
  if (managed) {
@@ -1425,7 +1443,7 @@ export const studio = new Hono()
1425
1443
  })
1426
1444
  // --- models: where each class runs, own API keys, the credits behind them -----------------
1427
1445
  // Alone for this machine; on a Manage-App's runtime for the organization, whose admins change it.
1428
- .get("/models", async (c) => c.json(await modelSettings(requestLang(c))))
1446
+ .get("/models", async (c) => c.json(await settingsFor(c)))
1429
1447
  .put("/models", async (c) => {
1430
1448
  if (!mayChangeModels(c.get("user"))) {
1431
1449
  return c.json({
@@ -1467,6 +1485,10 @@ export const studio = new Hono()
1467
1485
  code: "plan",
1468
1486
  }, 403);
1469
1487
  }
1488
+ // The organization's admins may allow no own keys at all.
1489
+ if (feature("modelTiers", info.features) && info.modelPolicy?.ownKeys === false) {
1490
+ return c.json({ error: say(c, "ownKeysNotInPolicy"), code: "tier" }, 403);
1491
+ }
1470
1492
  }
1471
1493
  const blocked = input.bindings ? blockedBinding(input.bindings) : null;
1472
1494
  if (blocked) {
@@ -1485,7 +1507,84 @@ export const studio = new Hono()
1485
1507
  if (((await embeddingModel().catch(() => null))?.ref ?? null) !== embeddedBy) {
1486
1508
  void reindexAll().catch((err) => console.error("[models] reindex failed", err));
1487
1509
  }
1488
- return c.json(await modelSettings(requestLang(c)));
1510
+ return c.json(await settingsFor(c));
1511
+ })
1512
+ // The organization's model policy (way A/B/C, the lists, where models may run), saved at the
1513
+ // Manage-App by its admins. Behind `modelTiers`.
1514
+ .put("/model-policy", async (c) => {
1515
+ const user = c.get("user");
1516
+ if (!managed || !mayChangeModels(user)) {
1517
+ return c.json({ error: say(c, "onlyOrganizationAdminsChange"), code: "forbidden" }, 403);
1518
+ }
1519
+ const info = await tenantInfo(user.tenantId).catch(() => null);
1520
+ if (!info) {
1521
+ return c.json({ error: say(c, "planUnavailable"), code: "manage_unavailable" }, 503);
1522
+ }
1523
+ if (!feature("modelTiers", info.features) || !info.tier) {
1524
+ return c.notFound();
1525
+ }
1526
+ // The Manage-App checks the policy against the plan and the tier, and keeps what its way uses.
1527
+ const policy = modelPolicySchema.parse(await c.req.json());
1528
+ try {
1529
+ await saveModelPolicy(user.tenantId, user.id, policy);
1530
+ }
1531
+ catch (err) {
1532
+ if (err instanceof ManageError && (err.status < 500 || MASKING_CODES.has(err.code))) {
1533
+ return c.json({ error: err.message, code: err.code }, err.status);
1534
+ }
1535
+ throw err;
1536
+ }
1537
+ return c.json(await settingsFor(c));
1538
+ })
1539
+ // The organization's tier, picked by its admins among those the plan offers. Behind `modelTiers`.
1540
+ .put("/model-tier", async (c) => {
1541
+ const user = c.get("user");
1542
+ if (!managed || !mayChangeModels(user)) {
1543
+ return c.json({ error: say(c, "onlyOrganizationAdminsChange"), code: "forbidden" }, 403);
1544
+ }
1545
+ const info = await tenantInfo(user.tenantId).catch(() => null);
1546
+ if (!info) {
1547
+ return c.json({ error: say(c, "planUnavailable"), code: "manage_unavailable" }, 503);
1548
+ }
1549
+ if (!feature("modelTiers", info.features) || !info.tier) {
1550
+ return c.notFound();
1551
+ }
1552
+ const { tier } = z.object({ tier: z.string().min(1).max(40) }).parse(await c.req.json());
1553
+ try {
1554
+ await saveModelTier(user.tenantId, user.id, tier);
1555
+ }
1556
+ catch (err) {
1557
+ if (err instanceof ManageError && err.status < 500) {
1558
+ return c.json({ error: err.message, code: err.code }, err.status);
1559
+ }
1560
+ throw err;
1561
+ }
1562
+ return c.json(await settingsFor(c));
1563
+ })
1564
+ // "Try a sentence" under the masking instructions: what a model would see of it.
1565
+ .post("/model-policy/try", async (c) => {
1566
+ const user = c.get("user");
1567
+ if (!managed || !mayChangeModels(user)) {
1568
+ return c.json({ error: say(c, "onlyOrganizationAdminsChange"), code: "forbidden" }, 403);
1569
+ }
1570
+ const { text, maskLabels } = z
1571
+ .object({
1572
+ text: z.string().trim().min(1).max(2000),
1573
+ maskLabels: z
1574
+ .array(z.string().trim().min(1).max(MAX_MASK_LABEL_CHARS))
1575
+ .max(MAX_MASK_LABELS)
1576
+ .optional(),
1577
+ })
1578
+ .parse(await c.req.json());
1579
+ try {
1580
+ return c.json(await tryMasking(user.tenantId, user.id, text, maskLabels));
1581
+ }
1582
+ catch (err) {
1583
+ if (err instanceof ManageError && (err.status < 500 || MASKING_CODES.has(err.code))) {
1584
+ return c.json({ error: err.message, code: err.code }, err.status);
1585
+ }
1586
+ throw err;
1587
+ }
1489
1588
  })
1490
1589
  // Ollama on this computer: its models, what each can do, the ones to download, the downloads.
1491
1590
  .get("/models/local", async (c) => {
@@ -1,7 +1,24 @@
1
1
  import { note } from "@engenty/wizards-shared/run";
2
2
  import { decide } from "./engine/decide.js";
3
+ import { managed, tenantInfo } from "./manage.js";
3
4
  import { NotedError } from "./model-errors.js";
4
5
  import { prompt } from "./prompts.js";
6
+ import { currentTenant } from "./tenants/tenant.js";
7
+ /**
8
+ * A run of someone without an account: a guest on a public wizard. What it makes is checked
9
+ * against the rules before it is kept, and stays private (docs/plans/guest-content-guards.md).
10
+ */
11
+ export const guestRun = (run) => run.mode === "live" && !run.userId;
12
+ /**
13
+ * Whether what this tenant's guests make is checked: the Manage-App's abuse checks can switch it
14
+ * off; a runtime without one, or one that cannot reach it, checks.
15
+ */
16
+ export async function guestChecksOn() {
17
+ if (!managed)
18
+ return true;
19
+ const info = await tenantInfo(currentTenant()).catch(() => null);
20
+ return info?.checks?.guests !== false;
21
+ }
5
22
  /** A request the content rules stop. */
6
23
  export class ContentBlockedError extends NotedError {
7
24
  kind;
@@ -14,32 +31,57 @@ export class ContentBlockedError extends NotedError {
14
31
  export function contentPolicy() {
15
32
  return prompt("safety", "policy");
16
33
  }
17
- /** Throws ContentBlockedError when the request breaks a content rule. */
18
- export async function checkContent(input) {
19
- let breaks;
34
+ /**
35
+ * Asks the decision model the questions about a text; the first one answered yes (or not at all)
36
+ * names what stops it. Throws ContentBlockedError then, NotedError when no check could run.
37
+ */
38
+ async function ask(state, questions, meta) {
39
+ let stopped;
20
40
  try {
21
41
  const decision = await decide({
22
- state: { kind: input.kind, request: input.text },
23
- questions: {
24
- breaks: {
25
- type: "noul",
26
- instructions: prompt("safety", "check", { policy: contentPolicy() }),
27
- },
28
- },
29
- call: input.call,
30
- signal: input.signal,
42
+ state,
43
+ questions: Object.fromEntries(Object.entries(questions).map(([kind, instructions]) => [
44
+ kind,
45
+ { type: "noul", instructions: instructions ?? "" },
46
+ ])),
47
+ call: meta.call,
48
+ signal: meta.signal,
31
49
  });
32
- const answer = decision.answers.breaks;
33
50
  // No usable answer counts as a yes: nothing is made unchecked.
34
- breaks = answer?.type === "noul" ? answer.noul >= 0.5 : true;
51
+ stopped = Object.keys(questions).find((kind) => {
52
+ const answer = decision.answers[kind];
53
+ return answer?.type === "noul" ? answer.noul >= 0.5 : true;
54
+ });
35
55
  }
36
56
  catch (err) {
37
- if (input.signal?.aborted)
57
+ if (meta.signal?.aborted)
38
58
  throw err;
39
59
  throw new NotedError(note("contentCheckFailed", { detail: err.message || String(err) }));
40
60
  }
41
- if (breaks) {
42
- console.warn(`[safety] ${input.kind} stopped`);
43
- throw new ContentBlockedError(input.kind);
61
+ if (stopped) {
62
+ console.warn(`[safety] ${stopped} stopped`);
63
+ throw new ContentBlockedError(stopped);
44
64
  }
45
65
  }
66
+ /** Throws ContentBlockedError when an image, video or speech request breaks a content rule. */
67
+ export async function checkContent(input) {
68
+ await ask({ kind: input.kind, request: input.text }, { [input.kind]: prompt("safety", "check", { policy: contentPolicy() }) }, input);
69
+ }
70
+ /** Throws ContentBlockedError when what an AI step wrote for a guest breaks a content rule. */
71
+ export async function checkGuestText(input) {
72
+ if (!input.text.trim())
73
+ return;
74
+ await ask({ text: input.text.slice(0, 20_000) }, { text: prompt("safety", "check_text", { policy: contentPolicy() }) }, input);
75
+ }
76
+ /**
77
+ * Throws ContentBlockedError when a guest's answers ask for what the rules forbid (`input`) or
78
+ * try to change what the AI is told to do (`injection`). One call for both.
79
+ */
80
+ export async function checkGuestInput(input) {
81
+ if (!input.text.trim())
82
+ return;
83
+ await ask({ answers: input.text.slice(0, 20_000) }, {
84
+ input: prompt("safety", "check_input.rules", { policy: contentPolicy() }),
85
+ injection: prompt("safety", "check_input.override"),
86
+ }, input);
87
+ }
@@ -163,6 +163,7 @@ export function reportRun(runId, status) {
163
163
  cursor: true,
164
164
  error: true,
165
165
  definition: true,
166
+ state: true,
166
167
  createdAt: true,
167
168
  },
168
169
  });
@@ -183,6 +184,8 @@ export function reportRun(runId, status) {
183
184
  ? { step: { id: step.id, title: (step.title ?? step.id).slice(0, 160), kind: step.type } }
184
185
  : {}),
185
186
  ...(state === "failed" && run.error ? { error: run.error.slice(0, 2000) } : {}),
187
+ // What the content rules stopped: an image, a guest's text, their input, an override.
188
+ ...(state === "failed" && run.state.blocked ? { blocked: run.state.blocked } : {}),
186
189
  });
187
190
  })().catch((err) => {
188
191
  console.warn(`[reports] run ${runId}:`, err.message);
@@ -10,7 +10,7 @@ import { formulaEstimate } from "../credits/estimate.js";
10
10
  import { control, controlDb, db, schema, withTenant } from "../db/client.js";
11
11
  import { missingCapabilities, optionalCapabilities, stepsWithoutModel, } from "../engine/requirements.js";
12
12
  import { env } from "../env.js";
13
- import { managed, tenantInfo } from "../manage.js";
13
+ import { managed } from "../manage.js";
14
14
  import { classCatalog, imageCostUsd, tokenCostUsd, videoCostUsd, WEB_SEARCH_COST_USD, } from "../models.js";
15
15
  import { pluginIdsOf, pluginStartersOf } from "../plugins/registry.js";
16
16
  import { readSetting, writeSetting } from "../settings.js";
@@ -219,37 +219,13 @@ async function keptOptional(ids, lang, unavailable) {
219
219
  }
220
220
  return out;
221
221
  }
222
- /** The team's level: the Manage-App's word on a managed runtime; elsewhere every level is open. */
223
- async function teamLevel() {
224
- if (!managed) {
225
- return null;
222
+ /** The featured entries first, under "Recommended"; a search keeps its order. */
223
+ export function featuredFirst(page, opts) {
224
+ if (opts.q?.trim()) {
225
+ return page;
226
226
  }
227
- const info = await tenantInfo(currentTenant()).catch(() => null);
228
- return info?.level ?? null;
229
- }
230
- /**
231
- * The catalog as the team's level leaves it (docs/plans/wizards-admin.md in the Manage
232
- * repository): a template above the level is not shown, the featured ones come first – those of
233
- * the team's own level before the rest – and the answer says the level.
234
- */
235
- export async function byLevel(page, opts) {
236
- const level = await teamLevel();
237
- const top = level?.level ?? Number.POSITIVE_INFINITY;
238
- const shown = page.entries.filter((e) => (e.level ?? 1) <= top);
239
- // A search keeps its order: the words found what fits best.
240
- const rank = (e) => e.featured ? ((e.level ?? 1) === level?.level ? 0 : 1) : 2;
241
- const entries = opts.q?.trim()
242
- ? shown
243
- : shown
244
- .map((e, i) => ({ e, i }))
245
- .sort((a, b) => rank(a.e) - rank(b.e) || a.i - b.i)
246
- .map((x) => x.e);
247
- return {
248
- ...page,
249
- entries,
250
- total: Math.max(0, page.total - (page.entries.length - shown.length)),
251
- level,
252
- };
227
+ const entries = [...page.entries].sort((a, b) => Number(!!b.featured) - Number(!!a.featured));
228
+ return { ...page, entries };
253
229
  }
254
230
  /**
255
231
  * Searches the tenant's plugins' starters and the marketplace, in that order: a page holds the
@@ -7,6 +7,7 @@ import { db, schema } from "../db/client.js";
7
7
  import { env } from "../env.js";
8
8
  import { feature } from "../features.js";
9
9
  import { managed, putPages, tenantInfo } from "../manage.js";
10
+ import { guestRun } from "../safety.js";
10
11
  import { currentTenant } from "../tenants/tenant.js";
11
12
  import { mainLogoId } from "./brand.js";
12
13
  /** About how many rows the teaser's step list has. */
@@ -168,10 +169,13 @@ export async function pageOrganization() {
168
169
  const example = exampleToken
169
170
  ? await db.query.run.findFirst({
170
171
  where: and(eq(schema.run.wizardId, w.id), eq(schema.run.shareToken, exampleToken)),
171
- columns: { status: true, expiresAt: true },
172
+ columns: { status: true, expiresAt: true, mode: true, userId: true },
172
173
  })
173
174
  : null;
174
- const shown = example?.status === "done" && !(example.expiresAt && example.expiresAt < new Date());
175
+ // A guest's result is never shown on a public page: only a run a member started.
176
+ const shown = example?.status === "done" &&
177
+ !guestRun(example) &&
178
+ !(example.expiresAt && example.expiresAt < new Date());
175
179
  const slug = kept[w.id] ?? wizardSlug(def.title, taken);
176
180
  if (!kept[w.id]) {
177
181
  made[w.id] = slug;
@@ -6,6 +6,7 @@ import { availableFormats } from "../engine/runner.js";
6
6
  import { env } from "../env.js";
7
7
  import { inlineAssetRefs, loadAsset, loadAssetText, removeAssetFiles, saveAsset, } from "../files/storage.js";
8
8
  import { htmlToPng } from "../render/convert.js";
9
+ import { guestRun } from "../safety.js";
9
10
  import { dropLinks, dropRuns, putLink } from "../tenants/control.js";
10
11
  import { brandView } from "./brand.js";
11
12
  import { ServiceError } from "./errors.js";
@@ -85,6 +86,10 @@ export async function shareView(run) {
85
86
  * a widget's poster, or a document's first screen. Rendered once and kept.
86
87
  */
87
88
  export async function shareImage(run) {
89
+ // A guest's result stays private: link previews get no picture of it.
90
+ if (guestRun(run)) {
91
+ return null;
92
+ }
88
93
  const view = await shareView(run);
89
94
  for (const { output } of view.shown) {
90
95
  const assets = output?.assets ?? [];
@@ -0,0 +1,209 @@
1
+ import { byteLength, officialSkill, SKILL_REF, } from "@engenty/wizards-shared/skills";
2
+ import { and, eq, isNotNull } from "drizzle-orm";
3
+ import { z } from "zod";
4
+ import { db, schema } from "../db/client.js";
5
+ import { requireWritableProject } from "./access.js";
6
+ import { notFound, ServiceError } from "./errors.js";
7
+ import { ownedProject } from "./projects.js";
8
+ import { asText, blobBytes, checkAlways, checkContent, contentHash, contentOf, insertSkill, keepBlobs, requireSkills, skillBytes, skillRow, } from "./skills.js";
9
+ /**
10
+ * skills.sh, the open directory of skills (docs/plans/skills.md): its search, and a skill read
11
+ * whole from its registry address `/r/<owner>/<repo>/<skill>`, which hands out the `SKILL.md`
12
+ * and the text files of the skill's folder (not fonts or images). A skill added is a copy: it
13
+ * changes only when someone takes an update, and its scripts stay off until someone switches
14
+ * them on.
15
+ */
16
+ const BASE = (process.env.SKILLS_REGISTRY_URL ?? "https://skills.sh").replace(/\/+$/, "");
17
+ /** What a registry answer may weigh: a skill of 1 MB with its JSON around it. */
18
+ const MAX_ANSWER = 5_000_000;
19
+ const down = () => new ServiceError("refused", { server: "skillsRegistryDown" });
20
+ async function getJson(path, signal) {
21
+ let res;
22
+ try {
23
+ res = await fetch(`${BASE}${path}`, {
24
+ redirect: "follow",
25
+ headers: { accept: "application/json", "user-agent": "engenty-wizards" },
26
+ signal: AbortSignal.any([AbortSignal.timeout(15_000), ...(signal ? [signal] : [])]),
27
+ });
28
+ }
29
+ catch {
30
+ throw down();
31
+ }
32
+ if (res.status === 404) {
33
+ return null;
34
+ }
35
+ if (!res.ok) {
36
+ throw down();
37
+ }
38
+ const text = await res.text();
39
+ if (text.length > MAX_ANSWER) {
40
+ throw down();
41
+ }
42
+ try {
43
+ return JSON.parse(text);
44
+ }
45
+ catch {
46
+ throw down();
47
+ }
48
+ }
49
+ const searchAnswer = z.object({
50
+ skills: z
51
+ .array(z.object({
52
+ id: z.string(),
53
+ source: z.string(),
54
+ skillId: z.string().optional(),
55
+ name: z.string(),
56
+ installs: z.number().optional(),
57
+ }))
58
+ .default([]),
59
+ });
60
+ /** Skills on skills.sh for a few words, the space's own marked as added. */
61
+ export async function searchSkills(userId, projectId, query) {
62
+ await requireSkills();
63
+ const project = await ownedProject(userId, projectId);
64
+ const q = query.trim();
65
+ if (q.length < 2) {
66
+ return { hits: [] };
67
+ }
68
+ const answer = searchAnswer.safeParse(await getJson(`/api/search?q=${encodeURIComponent(q.slice(0, 100))}&limit=40`));
69
+ if (!answer.success) {
70
+ throw down();
71
+ }
72
+ const added = new Set((await db
73
+ .select({ origin: schema.spaceSkill.origin })
74
+ .from(schema.spaceSkill)
75
+ .where(and(eq(schema.spaceSkill.projectId, project.id), isNotNull(schema.spaceSkill.origin)))).map((r) => r.origin));
76
+ const hits = answer.data.skills
77
+ .filter((s) => SKILL_REF.test(s.id))
78
+ .map((s) => ({
79
+ ref: s.id,
80
+ name: s.name,
81
+ source: s.source,
82
+ installs: s.installs ?? 0,
83
+ official: officialSkill(s.id),
84
+ added: added.has(s.id),
85
+ }));
86
+ return { hits };
87
+ }
88
+ const registryItem = z.object({
89
+ name: z.string().optional(),
90
+ description: z.string().optional(),
91
+ files: z
92
+ .array(z.object({ path: z.string(), content: z.string().nullish() }))
93
+ .max(2000)
94
+ .default([]),
95
+ });
96
+ /** A skill of skills.sh read whole: its content as the space would keep it, and what was left out. */
97
+ export async function readRegistrySkill(ref) {
98
+ if (!SKILL_REF.test(ref)) {
99
+ throw notFound();
100
+ }
101
+ const item = registryItem.safeParse(await getJson(`/r/${ref.split("/").map(encodeURIComponent).join("/")}`));
102
+ if (!item.success) {
103
+ throw new ServiceError("not_found", { server: "skillsRegistryMissing", params: { ref } });
104
+ }
105
+ const enc = new TextEncoder();
106
+ const read = contentOf(item.data.files.map((f) => {
107
+ // The registry hands out text; a file that is not came as something else (null, empty).
108
+ const data = typeof f.content === "string" ? enc.encode(f.content) : null;
109
+ return {
110
+ path: f.path.replace(/^\.?\//, ""),
111
+ text: data === null ? null : asText(data),
112
+ data,
113
+ };
114
+ }));
115
+ return { ...read, hash: contentHash(read.content) };
116
+ }
117
+ /** A skill of skills.sh to look at before it is added: everything it would bring. */
118
+ export async function previewSkill(userId, projectId, ref) {
119
+ await requireSkills();
120
+ await ownedProject(userId, projectId);
121
+ const read = await readRegistrySkill(ref);
122
+ const preview = {
123
+ ref,
124
+ name: read.content.name,
125
+ description: read.content.description,
126
+ body: read.content.body,
127
+ meta: read.content.meta,
128
+ fileList: read.content.files,
129
+ blobList: read.content.blobFiles.map((f) => ({ path: f.path, bytes: f.bytes })),
130
+ skipped: read.skipped,
131
+ official: officialSkill(ref),
132
+ bytes: skillBytes(read.content) + blobBytes(read.content.blobFiles),
133
+ hash: read.hash,
134
+ };
135
+ // What the space would refuse is said now, before anyone presses Add.
136
+ checkContent(read.content);
137
+ return preview;
138
+ }
139
+ /** Adds a skill of skills.sh to the space, as it is there now. */
140
+ export async function addRegistrySkill(userId, projectId, input) {
141
+ await requireSkills();
142
+ const project = await ownedProject(userId, projectId);
143
+ await requireWritableProject(project.id);
144
+ const read = await readRegistrySkill(input.ref);
145
+ await keepBlobs(read.blobs);
146
+ return insertSkill(project.id, read.content, {
147
+ source: "skills.sh",
148
+ mode: input.mode,
149
+ origin: input.ref,
150
+ originHash: read.hash,
151
+ rename: true,
152
+ });
153
+ }
154
+ /** What skills.sh has now for a skill added from it: null when nothing changed. */
155
+ export async function skillUpdate(userId, id) {
156
+ await requireSkills();
157
+ const row = await skillRow(id);
158
+ if (!row.origin || row.source !== "skills.sh") {
159
+ throw notFound();
160
+ }
161
+ await ownedProject(userId, row.projectId);
162
+ const read = await readRegistrySkill(row.origin);
163
+ if (read.hash === row.originHash) {
164
+ return { update: null };
165
+ }
166
+ return {
167
+ update: {
168
+ description: read.content.description,
169
+ body: read.content.body,
170
+ fileList: [
171
+ ...read.content.files.map((f) => ({ path: f.path, bytes: byteLength(f.text) })),
172
+ ...read.content.blobFiles.map((f) => ({ path: f.path, bytes: f.bytes })),
173
+ ].sort((a, b) => a.path.localeCompare(b.path)),
174
+ skipped: read.skipped,
175
+ hash: read.hash,
176
+ },
177
+ };
178
+ }
179
+ /** Takes what skills.sh has now; the skill keeps its name and when it counts. */
180
+ export async function applySkillUpdate(userId, id, hash) {
181
+ await requireSkills();
182
+ const row = await skillRow(id);
183
+ if (!row.origin || row.source !== "skills.sh") {
184
+ throw notFound();
185
+ }
186
+ await ownedProject(userId, row.projectId);
187
+ await requireWritableProject(row.projectId);
188
+ const read = await readRegistrySkill(row.origin);
189
+ // Taken only as it was shown: a change since the person looked is shown first.
190
+ if (read.hash !== hash) {
191
+ throw new ServiceError("revision_conflict", { server: "skillUpdateChanged" });
192
+ }
193
+ const next = checkContent({ ...read.content, name: row.name });
194
+ await checkAlways(row.projectId, row.id, row.mode, next.body);
195
+ await keepBlobs(read.blobs);
196
+ await db
197
+ .update(schema.spaceSkill)
198
+ .set({
199
+ description: next.description,
200
+ body: next.body,
201
+ meta: next.meta,
202
+ files: next.files,
203
+ blobFiles: next.blobFiles,
204
+ originHash: read.hash,
205
+ updatedAt: new Date(),
206
+ })
207
+ .where(eq(schema.spaceSkill.id, row.id));
208
+ return { ok: true };
209
+ }