@engenty/wizards-runtime 0.12.2 → 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 (96) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +25 -4
  2. package/apps/runtime/dist/app.js +11 -2
  3. package/apps/runtime/dist/credits/estimate.js +3 -3
  4. package/apps/runtime/dist/docs/dev/wizard-format/agent-steps.md +20 -2
  5. package/apps/runtime/dist/docs/user-guide/models.md +105 -30
  6. package/apps/runtime/dist/docs/user-guide/together.md +15 -2
  7. package/apps/runtime/dist/engine/decide.js +1 -1
  8. package/apps/runtime/dist/engine/requirements.js +139 -11
  9. package/apps/runtime/dist/engine/runner.js +47 -5
  10. package/apps/runtime/dist/engine/steps.js +13 -5
  11. package/apps/runtime/dist/engine/template.js +17 -0
  12. package/apps/runtime/dist/link-preview.js +9 -0
  13. package/apps/runtime/dist/manage.js +25 -0
  14. package/apps/runtime/dist/mcp/handler.js +55 -1
  15. package/apps/runtime/dist/mcp/seen.js +47 -0
  16. package/apps/runtime/dist/models.js +202 -11
  17. package/apps/runtime/dist/motion-graphics/step.js +2 -2
  18. package/apps/runtime/dist/prompts/goose.md +8 -7
  19. package/apps/runtime/dist/prompts/safety.md +18 -0
  20. package/apps/runtime/dist/prompts/step.md +1 -1
  21. package/apps/runtime/dist/routes/marketplace.js +3 -3
  22. package/apps/runtime/dist/routes/runs.js +5 -0
  23. package/apps/runtime/dist/routes/studio.js +103 -4
  24. package/apps/runtime/dist/safety.js +60 -18
  25. package/apps/runtime/dist/services/manage-reports.js +3 -0
  26. package/apps/runtime/dist/services/marketplace.js +7 -31
  27. package/apps/runtime/dist/services/pages.js +6 -2
  28. package/apps/runtime/dist/services/shares.js +5 -0
  29. package/apps/runtime/dist/services/spaces.js +15 -1
  30. package/apps/runtime/dist/texts.js +6 -0
  31. package/apps/runtime/dist/tools/index.js +3 -2
  32. package/apps/web/dist/assets/AboutDialog-B-JxkELB.js +1 -0
  33. package/apps/web/dist/assets/{ChangelogDialog-CKLgFL6r.js → ChangelogDialog-SwyId00t.js} +1 -1
  34. package/apps/web/dist/assets/{CodeEditor-B3nto_26.js → CodeEditor-BwZsk5Al.js} +1 -1
  35. package/apps/web/dist/assets/EditorPage-DQ_2FOzI.js +3 -0
  36. package/apps/web/dist/assets/{FlowPreview-zJCtixSi.js → FlowPreview-DtSpjVTl.js} +1 -1
  37. package/apps/web/dist/assets/Marketplace-DoH4YO3D.js +2 -0
  38. package/apps/web/dist/assets/{NewWizardChannels-B4N7GIYh.js → NewWizardChannels-Tgoexgj4.js} +1 -1
  39. package/apps/web/dist/assets/NewWizardPage-B24AF482.js +7 -0
  40. package/apps/web/dist/assets/OnboardingPage-BEvq4slJ.js +1 -0
  41. package/apps/web/dist/assets/PreviewPane-B_v7Y8R7.js +10 -0
  42. package/apps/web/dist/assets/ProjectPage-ClRuhFJo.js +10 -0
  43. package/apps/web/dist/assets/PublicRunner-MicrpVsv.js +1 -0
  44. package/apps/web/dist/assets/{ReadOnly-C9oGMkUB.js → ReadOnly-BXjv-MSv.js} +1 -1
  45. package/apps/web/dist/assets/SettingsPage-DY8O1r43.js +2 -0
  46. package/apps/web/dist/assets/SetupPage-BOVkVpMu.js +1 -0
  47. package/apps/web/dist/assets/{SharePage-DdMm1Y8K.js → SharePage-DXGzJSnR.js} +1 -1
  48. package/apps/web/dist/assets/SkillEditor-BzzTDeaU.js +1 -0
  49. package/apps/web/dist/assets/changelog-BLdS-0Bj.js +1 -0
  50. package/apps/web/dist/assets/{code-xml-Hx7YxCg0.js → code-xml-TwKzzMtA.js} +1 -1
  51. package/apps/web/dist/assets/{eye-BkMFLnYu.js → eye-Brd-xPUJ.js} +1 -1
  52. package/apps/web/dist/assets/i18n-8-Sw11tB.js +55 -0
  53. package/apps/web/dist/assets/index-OsdQFHmh.js +49 -0
  54. package/apps/web/dist/assets/index-QPipX5Fi.css +1 -0
  55. package/apps/web/dist/assets/{lock-CGXM95Mi.js → lock-C0uxcOlq.js} +1 -1
  56. package/apps/web/dist/assets/{phone-DMfwuh9V.js → phone-DhkHteoJ.js} +1 -1
  57. package/apps/web/dist/assets/{runners-D5qz6b_s.js → runners-G-XYaDgR.js} +1 -1
  58. package/apps/web/dist/assets/{session-DRy0k0nh.js → session-BWI-KENJ.js} +1 -1
  59. package/apps/web/dist/assets/theme-D7krsx0_.js +11 -0
  60. package/apps/web/dist/assets/ui-DSXG3f49.js +83 -0
  61. package/apps/web/dist/assets/{upload-DQJwLSGj.js → upload-BYZTwJTD.js} +1 -1
  62. package/apps/web/dist/assets/{useMutation-C20c2EH3.js → useMutation-D0QP_k2-.js} +1 -1
  63. package/apps/web/dist/assets/{volume-2-CC5qamYT.js → volume-2-CVHoxdGM.js} +1 -1
  64. package/apps/web/dist/index.html +9 -9
  65. package/apps/web/dist/mcp/flow.html +56 -56
  66. package/node_modules/@engenty/wizards-shared/dist/assistant.d.ts +1 -0
  67. package/node_modules/@engenty/wizards-shared/dist/assistant.js +5 -0
  68. package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +107 -0
  69. package/node_modules/@engenty/wizards-shared/dist/definition.js +67 -4
  70. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
  71. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
  72. package/node_modules/@engenty/wizards-shared/dist/marketplace.d.ts +0 -5
  73. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +61 -0
  74. package/node_modules/@engenty/wizards-shared/dist/run.js +50 -0
  75. package/node_modules/@engenty/wizards-shared/dist/tiers.d.ts +195 -0
  76. package/node_modules/@engenty/wizards-shared/dist/tiers.js +98 -0
  77. package/package.json +1 -1
  78. package/plugin/.claude-plugin/plugin.json +1 -1
  79. package/plugin/plugin.json +1 -1
  80. package/apps/web/dist/assets/AboutDialog-CLgnoYTI.js +0 -1
  81. package/apps/web/dist/assets/EditorPage-D9JDdAAI.js +0 -3
  82. package/apps/web/dist/assets/Marketplace-D4e0Oac9.js +0 -2
  83. package/apps/web/dist/assets/NewWizardPage-Dpt0Mzk8.js +0 -7
  84. package/apps/web/dist/assets/OnboardingPage-CDoYVjRC.js +0 -1
  85. package/apps/web/dist/assets/PreviewPane-DPB5nEd5.js +0 -10
  86. package/apps/web/dist/assets/ProjectPage-408YOoNa.js +0 -10
  87. package/apps/web/dist/assets/PublicRunner-BZ66xdRX.js +0 -1
  88. package/apps/web/dist/assets/SettingsPage-Dq3AZwJS.js +0 -2
  89. package/apps/web/dist/assets/SetupPage-CP3lbyZc.js +0 -1
  90. package/apps/web/dist/assets/SkillEditor-b5NMFB90.js +0 -1
  91. package/apps/web/dist/assets/changelog-82-DHogQ.js +0 -1
  92. package/apps/web/dist/assets/i18n-CKKh3Pn0.js +0 -55
  93. package/apps/web/dist/assets/index-Cy2NHzAx.js +0 -49
  94. package/apps/web/dist/assets/index-wR_-1hfN.css +0 -1
  95. package/apps/web/dist/assets/theme-DNPm6r4e.js +0 -11
  96. package/apps/web/dist/assets/ui-CwFQAfE-.js +0 -83
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { marginOf, } from "@engenty/wizards-shared/decision";
2
3
  import { branchValues, cardsFromData, conditionsOf, dataRef, followRules, formatsFor, isDecidedField, LIST_FORMATS, listRef, loopKey, MAX_SHOWN_FIELDS, optionsFromData, otherwiseOf, pageNeeds, textLang, whenHolds, wizardLang, } from "@engenty/wizards-shared/definition";
3
4
  import { note, saidText, } from "@engenty/wizards-shared/run";
@@ -16,9 +17,10 @@ import { saveAsset } from "../files/storage.js";
16
17
  import { managed, tenantInfo } from "../manage.js";
17
18
  import { hasFfmpeg } from "../media/ffmpeg.js";
18
19
  import { NotedError, noteOf, saidOf } from "../model-errors.js";
19
- import { conversationAvailable, freeTierRefusal, freeTierText, ModelUnavailableError, noteFreeTierRefusal, } from "../models.js";
20
+ import { conversationAvailable, freeTierRefusal, freeTierText, ModelUnavailableError, noteFreeTierRefusal, takeMasked, } from "../models.js";
20
21
  import { runEnded } from "../plugins/events.js";
21
22
  import { prompt } from "../prompts.js";
23
+ import { ContentBlockedError, checkGuestInput, checkGuestText, guestChecksOn, guestRun, } from "../safety.js";
22
24
  import { reportRun } from "../services/manage-reports.js";
23
25
  import { projectFiles } from "../services/project-files.js";
24
26
  import { projectProfile } from "../services/projects.js";
@@ -34,7 +36,7 @@ import { clearDeviceCalls } from "./device.js";
34
36
  import { emitEvent, recentEvents, signalChanged } from "./events.js";
35
37
  import { readPageInput } from "./input.js";
36
38
  import { pushRun } from "./push.js";
37
- import { blockingMessage, closedChoices, missingModelsSaid, openValue, stepsWithoutModel, } from "./requirements.js";
39
+ import { blockingMessage, closedChoices, maskedNote, missingModelsSaid, openValue, stepsWithoutModel, tierRefusalSaid, } from "./requirements.js";
38
40
  import { releaseResources, resourcesFor } from "./resources.js";
39
41
  import { outputSchema, runAutomaticStep } from "./steps.js";
40
42
  import { answersAsText, resolveRef } from "./template.js";
@@ -153,10 +155,23 @@ function friendly(err) {
153
155
  * as that note, so a runner shows it in its language; the run's error is in the wizard's.
154
156
  */
155
157
  async function failRun(run, stepId, err) {
156
- const said = noteOf(err) ?? friendly(err);
158
+ const said = noteOf(err) ?? (await tierRefusalSaid(err)) ?? friendly(err);
157
159
  const message = saidText(said, textLang(wizardLang(run.definition)));
158
160
  await emitEvent(run.id, stepId, "error", said);
159
- await updateRun(run.id, { status: "failed", error: message });
161
+ // What the content rules stopped is kept on the run: Manage hears of it with the failed turn.
162
+ const blocked = err instanceof ContentBlockedError
163
+ ? (await db.query.run.findFirst({
164
+ where: eq(schema.run.id, run.id),
165
+ columns: { state: true },
166
+ }))?.state
167
+ : undefined;
168
+ await updateRun(run.id, {
169
+ status: "failed",
170
+ error: message,
171
+ ...(blocked && err instanceof ContentBlockedError
172
+ ? { state: { ...blocked, blocked: err.kind } }
173
+ : {}),
174
+ });
160
175
  }
161
176
  // --- creating & driving ------------------------------------------------------
162
177
  export async function createRun(input) {
@@ -658,16 +673,39 @@ async function drive(runId, signal) {
658
673
  const project = await loadProject(run);
659
674
  const state = structuredClone(run.state);
660
675
  try {
661
- const output = await runAutomaticStep(step, await makeContext(run, project, state, signal));
676
+ const ctx = await makeContext(run, project, state, signal);
677
+ // A guest's answers are checked once before any model works on them, and what a step
678
+ // wrote for a guest before it is kept (docs/plans/guest-content-guards.md).
679
+ const guest = guestRun(run) && (await guestChecksOn());
680
+ if (guest) {
681
+ const answers = [answersAsText(ctx.scope), ...Object.values(state.notes)].join("\n");
682
+ const hash = createHash("sha256").update(answers).digest("base64url").slice(0, 24);
683
+ if (state.inputChecked !== hash) {
684
+ await checkGuestInput({ text: answers, call: ctx.call, signal });
685
+ state.inputChecked = hash;
686
+ }
687
+ }
688
+ const output = await runAutomaticStep(step, ctx);
662
689
  if (signal.aborted) {
663
690
  return;
664
691
  }
692
+ if (guest) {
693
+ await checkGuestText({
694
+ text: output.text || (output.json ? JSON.stringify(output.json) : ""),
695
+ call: ctx.call,
696
+ signal,
697
+ });
698
+ }
665
699
  await syncRunCost(runId);
666
700
  state.outputs[step.id] = output;
667
701
  delete state.notes[step.id];
668
702
  delete state.redo?.[step.id];
669
703
  const cursor = await advance(run, step.id, state);
670
704
  await updateRun(runId, { state, cursor, status: cursor ? "running" : "done", error: null });
705
+ const masked = takeMasked(runId, step.id);
706
+ if (masked) {
707
+ await emitEvent(runId, step.id, "info", maskedNote(masked));
708
+ }
671
709
  await emitEvent(runId, step.id, "step_done", step.title);
672
710
  }
673
711
  catch (err) {
@@ -819,6 +857,10 @@ export async function reviewStep(runId, stepId, action) {
819
857
  else {
820
858
  state.outputs[target] = editedJson(run.definition, target, output, edit);
821
859
  }
860
+ // A guest's own words in a result are held to the same rules as what a step wrote.
861
+ if (guestRun(run) && (await guestChecksOn())) {
862
+ await checkGuestText({ text: typeof edit === "string" ? edit : JSON.stringify(edit) });
863
+ }
822
864
  }
823
865
  state.history.push(stepId);
824
866
  const cursor = await advance(run, stepId, state);
@@ -1,5 +1,5 @@
1
1
  import { pOf } from "@engenty/wizards-shared/decision";
2
- import { allFields, dataRef, isDecisionStep, langNameEn, localeOf, stepShape, templateRefs, wizardLang, } from "@engenty/wizards-shared/definition";
2
+ import { allFields, classIdOf, dataRef, isDecisionStep, langNameEn, localeOf, stepShape, templateRefs, textClassOf, wizardLang, } from "@engenty/wizards-shared/definition";
3
3
  import { mainLogo, ruleLines, runTheme } from "@engenty/wizards-shared/projects";
4
4
  import { note as runNote } from "@engenty/wizards-shared/run";
5
5
  import { fitData, labelOf, recordsOf, shapeJsonSchema, shapeLines, shapeZod, titleKey, } from "@engenty/wizards-shared/shape";
@@ -24,7 +24,7 @@ import { runWidgetStep } from "../widgets/step.js";
24
24
  import { decide } from "./decide.js";
25
25
  import { prepareInputs } from "./prepare.js";
26
26
  import { runSurfaceStep } from "./surface.js";
27
- import { answersAsText, assetSectionLine, colorLine, factLines, logoSectionLine, renderTemplate, resolveRef, typeLines, } from "./template.js";
27
+ import { answersAsText, assetSectionLine, colorLine, factLines, logoSectionLine, renderTask, renderTemplate, resolveRef, typeLines, } from "./template.js";
28
28
  import { StepError } from "./types.js";
29
29
  /** Today's date as the wizard's people write it. */
30
30
  function today(ctx) {
@@ -477,7 +477,11 @@ export async function runAgentStep(step, ctx) {
477
477
  if (step.each) {
478
478
  return runAgentEach(step, ctx);
479
479
  }
480
- const resolved = await textModel(step.model ?? "standard", { ...ctx.call, effort: step.effort });
480
+ const resolved = await textModel(textClassOf(step.model ?? "standard"), {
481
+ ...ctx.call,
482
+ effort: step.effort,
483
+ makerClass: step.maker ? classIdOf(step, "standard") : undefined,
484
+ });
481
485
  const uploads = await personUploads(ctx);
482
486
  const { tools, assets, instructions } = await buildStepTools(step, ctx, resolved, uploads);
483
487
  // A step without tools of its own and without uploads: the run's device may answer it alone.
@@ -511,7 +515,7 @@ export async function runAgentStep(step, ctx) {
511
515
  .filter(Boolean)
512
516
  .join("\n\n");
513
517
  const request = [
514
- `# TASK\n${renderTemplate(step.instructions, ctx.scope)}`,
518
+ `# TASK\n${renderTask(step.instructions, ctx.scope)}`,
515
519
  answersBlock(ctx),
516
520
  photos.length
517
521
  ? prompt("step", "photos", {
@@ -774,7 +778,11 @@ async function writeHtml(step, ctx, kind) {
774
778
  const request = [`# BRIEF\n${brief}`, answersBlock(ctx), await revisionBlock(ctx, step.id)]
775
779
  .filter(Boolean)
776
780
  .join("\n\n");
777
- const writer = await textModel(step.model ?? "standard", { ...ctx.call, effort: step.effort });
781
+ const writer = await textModel(textClassOf(step.model ?? "standard"), {
782
+ ...ctx.call,
783
+ effort: step.effort,
784
+ makerClass: step.maker ? classIdOf(step, "standard") : undefined,
785
+ });
778
786
  const result = await generateText({
779
787
  model: writer.model,
780
788
  system,
@@ -225,6 +225,23 @@ export function resolveRef(ref, scope) {
225
225
  export function renderTemplate(template, scope) {
226
226
  return template.replace(TEMPLATE_RE, (_m, ref) => stringify(resolveRef(ref.trim(), scope)));
227
227
  }
228
+ const REFERENCE_KINDS = new Set(["image", "file", "signature"]);
229
+ /**
230
+ * A step's task with what the person typed marked as data: a field's value in `<data field="…">`,
231
+ * so a model tells the wizard's instructions from a visitor's words (prompts/step.md,
232
+ * ground_rules). Files and images stay names a tool reads; the rest as `renderTemplate`.
233
+ */
234
+ export function renderTask(template, scope) {
235
+ return template.replace(TEMPLATE_RE, (_m, ref) => {
236
+ const value = stringify(resolveRef(ref.trim(), scope));
237
+ const head = ref.trim().split(".")[0];
238
+ const field = allFields(scope.def).find((f) => f.id === head);
239
+ if (!field || REFERENCE_KINDS.has(field.kind) || value === "") {
240
+ return value;
241
+ }
242
+ return `<data field="${head}">${value.replaceAll("</data>", "")}</data>`;
243
+ });
244
+ }
228
245
  /** Everything the person entered so far, readable — handed to agents as data. */
229
246
  export function answersAsText(scope) {
230
247
  const lines = [];
@@ -2,6 +2,7 @@ import { and, eq } from "drizzle-orm";
2
2
  import { db, schema } from "./db/client.js";
3
3
  import { env } from "./env.js";
4
4
  import { escapeHtml } from "./render/convert.js";
5
+ import { guestRun } from "./safety.js";
5
6
  import { sharedRun, shareView } from "./services/shares.js";
6
7
  function tags(p) {
7
8
  const t = [
@@ -32,6 +33,14 @@ export async function linkPreview(path) {
32
33
  return null;
33
34
  }
34
35
  const view = await shareView(run);
36
+ // A guest's result stays private: the card names the wizard, never what it made.
37
+ if (guestRun(run)) {
38
+ return tags({
39
+ title: view.wizard.title,
40
+ description: view.wizard.description,
41
+ url: `${env.publicUrl}/s/${share[1]}`,
42
+ });
43
+ }
35
44
  return tags({
36
45
  title: view.title === view.wizard.title ? view.title : `${view.title} · ${view.wizard.title}`,
37
46
  description: view.message ?? view.wizard.description,
@@ -217,6 +217,31 @@ export async function tenantInfo(id, fresh = false) {
217
217
  export function forgetTenant(id) {
218
218
  tenants.delete(id);
219
219
  }
220
+ /**
221
+ * Saves the organization's model policy for the admin who asks (`actorId`): the Manage-App checks
222
+ * their role and the plan's ways and answers with the policy as it stands now.
223
+ */
224
+ export async function saveModelPolicy(tenantId, actorId, modelPolicy) {
225
+ const saved = await call("PUT", `${tenantPath(tenantId)}/model-policy`, { actorId, ...modelPolicy });
226
+ forgetTenant(tenantId);
227
+ return saved.modelPolicy;
228
+ }
229
+ /**
230
+ * Puts the organization on another tier its plan offers, for the admin who asks (`actorId`); the
231
+ * Manage-App refuses one a contract set.
232
+ */
233
+ export async function saveModelTier(tenantId, actorId, tier) {
234
+ await call("PUT", `${tenantPath(tenantId)}/model-tier`, { actorId, tier });
235
+ forgetTenant(tenantId);
236
+ }
237
+ /** What a model would see of `text` with masking on: the labels given, else the saved ones. */
238
+ export async function tryMasking(tenantId, actorId, text, maskLabels) {
239
+ return call("POST", `${tenantPath(tenantId)}/model-policy/try`, {
240
+ actorId,
241
+ text,
242
+ ...(maskLabels ? { maskLabels } : {}),
243
+ });
244
+ }
220
245
  /** Renames the organization at the Manage-App; what it answers is the tenant as it stands now. */
221
246
  export async function renameTenant(id, name) {
222
247
  const value = await call("PATCH", `/v1/tenants/${encodeURIComponent(id)}`, {
@@ -1,14 +1,64 @@
1
1
  import { createMcpHandler, McpServer, originValidationResponse, } from "@modelcontextprotocol/server";
2
2
  import { withTenant } from "../db/client.js";
3
3
  import { env } from "../env.js";
4
+ import { feature } from "../features.js";
4
5
  import { nudge } from "../live/hub.js";
6
+ import { managed, tenantInfo } from "../manage.js";
5
7
  import { prompt } from "../prompts.js";
6
8
  import { asRole } from "../services/access.js";
7
9
  import { tenantStatus } from "../tenants/control.js";
10
+ import { serverText } from "../texts.js";
8
11
  import { authenticate, principalOf } from "./auth.js";
9
12
  import { registerFlowApp } from "./flow-app.js";
10
- import { noteRequest } from "./seen.js";
13
+ import { appKind, clientNameOf, noteChecked, noteRequest } from "./seen.js";
11
14
  import { registerPrompts, registerTools } from "./tools.js";
15
+ /**
16
+ * An app the organization's model policy keeps out of its spaces (`modelPolicy.apps`): its tool
17
+ * calls are answered with a tool error the app shows, before any tool reads the space. Calls of
18
+ * other kinds (listing the tools) go on. Behind `modelTiers`. Best effort: an app is told apart
19
+ * by the name it gives itself, and any name not known as a local app's counts as a subscription.
20
+ */
21
+ async function appRefusal(who, client, body) {
22
+ const calls = (Array.isArray(body) ? body : [body]).filter((m) => Boolean(m) && typeof m === "object" && m.method === "tools/call");
23
+ // A runtime that runs alone has no organization and no policy.
24
+ if (!calls.length || !managed) {
25
+ return null;
26
+ }
27
+ const info = await tenantInfo(who.tenantId).catch(() => null);
28
+ // When the Manage-App can't say what the policy allows, the app waits.
29
+ const policy = info && feature("modelTiers", info.features) ? info.modelPolicy : undefined;
30
+ if (info && !policy) {
31
+ return null;
32
+ }
33
+ const kind = appKind(client, who.client);
34
+ const allowed = policy
35
+ ? kind === "local"
36
+ ? policy.apps.local
37
+ : policy.apps.subscriptions
38
+ : false;
39
+ noteChecked(who.tenantId, client, who.name ?? who.email ?? null, allowed, kind);
40
+ if (allowed) {
41
+ return null;
42
+ }
43
+ const text = !info
44
+ ? serverText("en", "appPolicyUnavailable", { app: client })
45
+ : kind === "local"
46
+ ? serverText("en", "appLocalRefused", { organization: info.name, app: client })
47
+ : serverText("en", "appSubscriptionRefused", {
48
+ organization: info.name,
49
+ app: client,
50
+ tier: info.tier?.name ?? serverText("en", "appYourTier"),
51
+ });
52
+ const answers = calls.map((call) => ({
53
+ jsonrpc: "2.0",
54
+ id: call.id ?? null,
55
+ result: { content: [{ type: "text", text }], isError: true },
56
+ }));
57
+ return new Response(JSON.stringify(Array.isArray(body) ? answers : answers[0]), {
58
+ status: 200,
59
+ headers: { "content-type": "application/json" },
60
+ });
61
+ }
12
62
  /** A wizard definition is a few KB; this leaves room and refuses anything far beyond it. */
13
63
  const MAX_BODY_BYTES = 300_000;
14
64
  /**
@@ -48,6 +98,10 @@ export function mcpHandler() {
48
98
  .json()
49
99
  .catch(() => null);
50
100
  noteRequest(who.tenantId, authInfo.clientId, who.client, body);
101
+ const refused = await appRefusal(who, clientNameOf(authInfo.clientId, who.client), body);
102
+ if (refused) {
103
+ return refused;
104
+ }
51
105
  }
52
106
  const answer = await withTenant(who.tenantId, () => asRole(who.role, () => handler.fetch(request, { authInfo })));
53
107
  if (request.method === "POST") {
@@ -63,3 +63,50 @@ export function seenApps(tenantId) {
63
63
  }
64
64
  return out;
65
65
  }
66
+ /** The name a sign-in's client gave on `initialize`, else the one its sign-in carries. */
67
+ export function clientNameOf(signIn, client) {
68
+ return names.get(signIn) ?? client;
69
+ }
70
+ /**
71
+ * Apps whose model runs on the member's computer: what they read of a space stays there. Goose
72
+ * is not one: it mostly thinks on a provider's model.
73
+ */
74
+ const LOCAL_APPS = new Set(["lm-studio"]);
75
+ /**
76
+ * Whether an app thinks on the member's computer (`local`) or on a provider under the member's
77
+ * own subscription, from every name it goes by (the one it gave on `initialize`, its sign-in's).
78
+ * It counts as local only where a name says so and none names another app; any other counts as
79
+ * one on a subscription.
80
+ */
81
+ export function appKind(...names) {
82
+ const ids = names.flatMap(appIdsOf);
83
+ return ids.length && ids.every((id) => LOCAL_APPS.has(id)) ? "local" : "subscription";
84
+ }
85
+ const checked = new Map();
86
+ /** Counts one tool call of an app the policy allowed or refused. */
87
+ export function noteChecked(tenantId, app, person, allowed, kind) {
88
+ const key = `${tenantId}\n${app}\n${person ?? ""}`;
89
+ const last = checked.get(key) ?? {
90
+ app,
91
+ kind,
92
+ person,
93
+ allowed: 0,
94
+ refused: 0,
95
+ at: 0,
96
+ };
97
+ last.at = Date.now();
98
+ if (allowed) {
99
+ last.allowed++;
100
+ }
101
+ else {
102
+ last.refused++;
103
+ }
104
+ checked.set(key, last);
105
+ }
106
+ /** The apps the tenant's members used on its spaces since the runtime started, latest first. */
107
+ export function checkedApps(tenantId) {
108
+ return [...checked]
109
+ .filter(([key]) => key.startsWith(`${tenantId}\n`))
110
+ .map(([, value]) => value)
111
+ .sort((a, b) => b.at - a.at);
112
+ }