wizards 0.2.46 → 0.2.48

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 (130) hide show
  1. package/apps/runtime/dist/agents/{project-assistant.js → studio-assistant.js} +199 -69
  2. package/apps/runtime/dist/agents/website.js +25 -2
  3. package/apps/runtime/dist/app.js +5 -1
  4. package/apps/runtime/dist/assistant/browser.js +26 -0
  5. package/apps/runtime/dist/assistant/docs.js +158 -0
  6. package/apps/runtime/dist/assistant/knows.js +325 -0
  7. package/apps/runtime/dist/assistant/primer.js +26 -0
  8. package/apps/runtime/dist/authoring/guide.js +5 -0
  9. package/apps/runtime/dist/cli/features.js +50 -0
  10. package/apps/runtime/dist/cli/main.js +4 -1
  11. package/apps/runtime/dist/connectors/plugin-connections.js +123 -29
  12. package/apps/runtime/dist/db/migrations/tenant/0012_assistant_chat.sql +40 -0
  13. package/apps/runtime/dist/db/migrations/tenant/meta/0012_snapshot.json +3132 -0
  14. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +7 -0
  15. package/apps/runtime/dist/db/schema.js +30 -0
  16. package/apps/runtime/dist/docs/dev/index.md +34 -0
  17. package/apps/runtime/dist/docs/dev/meta.json +7 -0
  18. package/apps/runtime/dist/docs/dev/plugins/connections.md +70 -0
  19. package/apps/runtime/dist/docs/dev/plugins/events.md +86 -0
  20. package/apps/runtime/dist/docs/dev/plugins/examples.md +99 -0
  21. package/apps/runtime/dist/docs/dev/plugins/index.md +72 -0
  22. package/apps/runtime/dist/docs/dev/plugins/layout.md +88 -0
  23. package/apps/runtime/dist/docs/dev/plugins/meta.json +29 -0
  24. package/apps/runtime/dist/docs/dev/plugins/pro-modules.md +59 -0
  25. package/apps/runtime/dist/docs/dev/plugins/quick-start.md +92 -0
  26. package/apps/runtime/dist/docs/dev/plugins/reference.md +298 -0
  27. package/apps/runtime/dist/docs/dev/plugins/reloading.md +75 -0
  28. package/apps/runtime/dist/docs/dev/plugins/routes.md +123 -0
  29. package/apps/runtime/dist/docs/dev/plugins/runners.md +184 -0
  30. package/apps/runtime/dist/docs/dev/plugins/server.md +191 -0
  31. package/apps/runtime/dist/docs/dev/plugins/shipping.md +98 -0
  32. package/apps/runtime/dist/docs/dev/plugins/space.md +260 -0
  33. package/apps/runtime/dist/docs/dev/plugins/starters.md +62 -0
  34. package/apps/runtime/dist/docs/dev/plugins/studio.md +261 -0
  35. package/apps/runtime/dist/docs/dev/plugins/styling.md +109 -0
  36. package/apps/runtime/dist/docs/dev/plugins/tables.md +102 -0
  37. package/apps/runtime/dist/docs/dev/plugins/tools.md +128 -0
  38. package/apps/runtime/dist/docs/meta.json +3 -0
  39. package/apps/runtime/dist/docs/user/ai-apps.md +99 -0
  40. package/apps/runtime/dist/docs/user/assistant.md +52 -0
  41. package/apps/runtime/dist/docs/user/build-a-wizard.md +79 -0
  42. package/apps/runtime/dist/docs/user/command-line.md +76 -0
  43. package/apps/runtime/dist/docs/user/connectors.md +80 -0
  44. package/apps/runtime/dist/docs/user/data.md +61 -0
  45. package/apps/runtime/dist/docs/user/first-start.md +42 -0
  46. package/apps/runtime/dist/docs/user/index.md +45 -0
  47. package/apps/runtime/dist/docs/user/install.md +76 -0
  48. package/apps/runtime/dist/docs/user/meta.json +29 -0
  49. package/apps/runtime/dist/docs/user/models.md +100 -0
  50. package/apps/runtime/dist/docs/user/plugins.md +61 -0
  51. package/apps/runtime/dist/docs/user/run.md +92 -0
  52. package/apps/runtime/dist/docs/user/server.md +50 -0
  53. package/apps/runtime/dist/docs/user/space.md +97 -0
  54. package/apps/runtime/dist/docs/user/steps.md +196 -0
  55. package/apps/runtime/dist/docs/user/test-and-share.md +210 -0
  56. package/apps/runtime/dist/docs/user/troubleshooting.md +57 -0
  57. package/apps/runtime/dist/engine/runner.js +12 -5
  58. package/apps/runtime/dist/features.js +123 -0
  59. package/apps/runtime/dist/manage.js +24 -0
  60. package/apps/runtime/dist/plugins/discovery.js +11 -0
  61. package/apps/runtime/dist/plugins/loader.js +12 -0
  62. package/apps/runtime/dist/routes/internal.js +3 -0
  63. package/apps/runtime/dist/routes/studio.js +126 -73
  64. package/apps/runtime/dist/services/assistant-chats.js +267 -0
  65. package/apps/runtime/dist/services/project-index.js +1 -1
  66. package/apps/runtime/dist/services/space-origin.js +45 -2
  67. package/apps/web/dist/assets/{AboutDialog-DkY1j7k6.js → AboutDialog-CuiVGknS.js} +1 -1
  68. package/apps/web/dist/assets/{ChangelogDialog-820LI5Jt.js → ChangelogDialog-DCEQD3Jd.js} +1 -1
  69. package/apps/web/dist/assets/ChatView-DFxrG2PD.js +10 -0
  70. package/apps/web/dist/assets/EditorPage-B5rzKNMy.js +3 -0
  71. package/apps/web/dist/assets/{FlowPreview-ChXfiMn_.js → FlowPreview-CYoR5DRY.js} +1 -1
  72. package/apps/web/dist/assets/{Harness-CfUfchNw.js → Harness-DAR1u4Dk.js} +1 -1
  73. package/apps/web/dist/assets/HomePage-BnYdh_Nx.js +1 -0
  74. package/apps/web/dist/assets/Marketplace-BDQNwMDB.js +2 -0
  75. package/apps/web/dist/assets/{NewWizardPage-C3NqEGmg.js → NewWizardPage-DztTEUlG.js} +1 -1
  76. package/apps/web/dist/assets/ProjectPage-B7-Lqx9a.js +2 -0
  77. package/apps/web/dist/assets/PublicRunner-CaH3bHHd.js +1 -0
  78. package/apps/web/dist/assets/{ReadOnly-C9P9aiU6.js → ReadOnly-DnB47DQC.js} +1 -1
  79. package/apps/web/dist/assets/RunDrawer-Dv0KRqGA.js +4 -0
  80. package/apps/web/dist/assets/RunnerView-Bzwv1u4j.js +2 -0
  81. package/apps/web/dist/assets/SettingsPage-oVO7CKvc.js +1 -0
  82. package/apps/web/dist/assets/SetupPage-D--8cWA0.js +1 -0
  83. package/apps/web/dist/assets/{SharePage-D5AvnhlY.js → SharePage-DjU08q7T.js} +1 -1
  84. package/apps/web/dist/assets/ThemeSwitch-C3EJRN06.js +1 -0
  85. package/apps/web/dist/assets/arrow-right-F7X_SjK9.js +1 -0
  86. package/apps/web/dist/assets/changelog-BRoVI_JJ.js +1 -0
  87. package/apps/web/dist/assets/{circle-alert-CPo3Naay.js → circle-alert-DdpaAYgd.js} +1 -1
  88. package/apps/web/dist/assets/{definition-CQGiBQ4X.js → definition-CHacJYmI.js} +2 -2
  89. package/apps/web/dist/assets/{external-link-CpU8aJY2.js → external-link-Dfc1VFvS.js} +1 -1
  90. package/apps/web/dist/assets/index-CX_yxZVQ.js +79 -0
  91. package/apps/web/dist/assets/index-Dr0bv52Q.css +1 -0
  92. package/apps/web/dist/assets/{lock-C_WlXIQ0.js → lock-Bu1wDFs8.js} +1 -1
  93. package/apps/web/dist/assets/{refresh-cw-Cli5WGnW.js → refresh-cw-BUDPOT39.js} +1 -1
  94. package/apps/web/dist/assets/{session-miDEdw2c.js → session-Blj2os_v.js} +1 -1
  95. package/apps/web/dist/assets/{settings-menu-ROT8Lbbj.js → settings-menu-BvxRnNtf.js} +1 -1
  96. package/apps/web/dist/assets/{sparkles-CP5H-O1E.js → sparkles-DWGJluyV.js} +1 -1
  97. package/apps/web/dist/assets/{trash-DU-hZpV0.js → trash-D9UB6TtS.js} +1 -1
  98. package/apps/web/dist/assets/ui-GsuU9WTj.js +9 -0
  99. package/apps/web/dist/assets/{upload-DMq5N6Fw.js → upload-BngimDBR.js} +1 -1
  100. package/apps/web/dist/assets/{volume-2-0SfkvOho.js → volume-2-BZju_bOP.js} +1 -1
  101. package/apps/web/dist/index.html +11 -11
  102. package/apps/web/dist/mcp/flow.html +51 -51
  103. package/node_modules/@engenty-wizards/plugin-sdk/dist/index.d.ts +103 -7
  104. package/node_modules/@engenty-wizards/plugin-sdk/dist/studio.d.ts +58 -4
  105. package/node_modules/@engenty-wizards/shared/dist/assistant.d.ts +113 -0
  106. package/node_modules/@engenty-wizards/shared/dist/assistant.js +55 -0
  107. package/node_modules/@engenty-wizards/shared/dist/definition.d.ts +56 -1
  108. package/node_modules/@engenty-wizards/shared/dist/definition.js +94 -4
  109. package/node_modules/@engenty-wizards/shared/dist/feature-flags.d.ts +54 -0
  110. package/node_modules/@engenty-wizards/shared/dist/feature-flags.js +46 -0
  111. package/node_modules/@engenty-wizards/shared/dist/features.d.ts +36 -0
  112. package/node_modules/@engenty-wizards/shared/dist/features.js +78 -0
  113. package/node_modules/@engenty-wizards/shared/dist/run.d.ts +3 -1
  114. package/package.json +1 -1
  115. package/apps/web/dist/assets/ChatView-DBl0iRMg.js +0 -10
  116. package/apps/web/dist/assets/EditorPage-BwJ-hqPg.js +0 -3
  117. package/apps/web/dist/assets/HomePage-BG5OZJkv.js +0 -1
  118. package/apps/web/dist/assets/Marketplace-BWhUJ4UX.js +0 -2
  119. package/apps/web/dist/assets/ProjectPage-Btf0TeP_.js +0 -2
  120. package/apps/web/dist/assets/PublicRunner-BxYinn04.js +0 -1
  121. package/apps/web/dist/assets/RunDrawer-DfnEMPTq.js +0 -4
  122. package/apps/web/dist/assets/RunnerView-CLrGb-oq.js +0 -2
  123. package/apps/web/dist/assets/SettingsPage-FWH84btd.js +0 -1
  124. package/apps/web/dist/assets/SetupPage-BI0kUNVW.js +0 -1
  125. package/apps/web/dist/assets/ThemeSwitch-C1qYFoYP.js +0 -1
  126. package/apps/web/dist/assets/arrow-right-Dpp_mpHe.js +0 -1
  127. package/apps/web/dist/assets/changelog-B6QMrVxX.js +0 -1
  128. package/apps/web/dist/assets/index-CIO9W4pe.js +0 -78
  129. package/apps/web/dist/assets/index-DKHClEy3.css +0 -1
  130. package/apps/web/dist/assets/ui-D92EkdEB.js +0 -9
@@ -0,0 +1,123 @@
1
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { declaredByPlugin, defaultFeatures, FEATURES, parseFeatures, resolveFeatures, } from "@engenty-wizards/shared/features";
4
+ import { accountOverview } from "./auth/account.js";
5
+ import { isCheckout, layout, packageRoot } from "./cli/home.js";
6
+ import { env } from "./env.js";
7
+ import { managed, tenantInfo } from "./manage.js";
8
+ import { loadedPlugins } from "./plugins/registry.js";
9
+ import { currentTenantOrNull } from "./tenants/tenant.js";
10
+ /**
11
+ * Which feature switches are on for this runtime (packages/shared/src/features.ts), laid over
12
+ * each other, the last winning:
13
+ *
14
+ * 1. the defaults the code declares: the core's (packages/shared/src/feature-flags.ts) and the
15
+ * loaded plugins' (their manifests' `features`, under the plugin's id)
16
+ * 2. the `FEATURES` environment variable (`teamPlans=on,site=off`): the cloud image, compose, dev
17
+ * 3. what the Manage-App says — for the team of a cloud runtime, for the linked account of a
18
+ * local one; a plan's switches and what an admin set for the team or for everyone
19
+ * 4. the `.features` file of this install (`~/.engenty/wizards/.features`; a checkout reads
20
+ * the repo root's, a cloud runtime its data folder's) — this machine's word is the last
21
+ *
22
+ * The file is read on every call, so a change counts at once. Nothing here is documented
23
+ * outside the code.
24
+ */
25
+ /** The `.features` file this runtime reads: the install's, the checkout's root, or the data folder's. */
26
+ export function featuresFile() {
27
+ if (managed) {
28
+ return join(env.dataDir, ".features");
29
+ }
30
+ return isCheckout() ? join(packageRoot, ".features") : join(layout().home, ".features");
31
+ }
32
+ let fileCache = null;
33
+ /** What the `.features` file says, read again when it changed. */
34
+ export function fileFeatures(file = featuresFile()) {
35
+ let mtime = -1;
36
+ try {
37
+ mtime = statSync(file).mtimeMs;
38
+ }
39
+ catch {
40
+ fileCache = null;
41
+ return {};
42
+ }
43
+ if (fileCache && fileCache.file === file && fileCache.mtime === mtime) {
44
+ return fileCache.value;
45
+ }
46
+ const value = parseFeatures(readFileSync(file, "utf8"));
47
+ fileCache = { file, mtime, value };
48
+ return value;
49
+ }
50
+ const envFeatures = () => parseFeatures(process.env.FEATURES ?? "");
51
+ /** Every switch something declared: the core's, then each plugin's under its id. */
52
+ export function declaredFeatures(sources = loadedPlugins().map((p) => p.source)) {
53
+ const out = { ...FEATURES };
54
+ for (const source of sources) {
55
+ Object.assign(out, declaredByPlugin(source.id, source.manifest.features));
56
+ }
57
+ return out;
58
+ }
59
+ /** The switches, with what the Manage-App said for the team or account laid in. */
60
+ export function features(remote) {
61
+ return resolveFeatures(defaultFeatures(declaredFeatures()), envFeatures(), remote, fileFeatures());
62
+ }
63
+ export function feature(name, remote) {
64
+ return features(remote)[name] === true;
65
+ }
66
+ let accountCache = null;
67
+ /**
68
+ * What the Manage-App says for the tenant at hand: the team's switches on a cloud runtime
69
+ * (cached a minute by `tenantInfo`), the linked account's on a local one (cached a minute
70
+ * here). Null when nothing is linked or the Manage-App does not answer.
71
+ */
72
+ export async function remoteFeatures() {
73
+ if (managed) {
74
+ const id = currentTenantOrNull();
75
+ if (!id) {
76
+ return null;
77
+ }
78
+ return tenantInfo(id)
79
+ .then((info) => info.features ?? null)
80
+ .catch(() => null);
81
+ }
82
+ if (accountCache && Date.now() - accountCache.at < 60_000) {
83
+ return accountCache.value;
84
+ }
85
+ const overview = await accountOverview().catch(() => null);
86
+ accountCache = { at: Date.now(), value: overview?.tenant.features ?? null };
87
+ return accountCache.value;
88
+ }
89
+ /** The switches for the tenant at hand, with what the Manage-App says fetched. */
90
+ export async function currentFeatures() {
91
+ return features(await remoteFeatures());
92
+ }
93
+ /**
94
+ * Writes one switch into the `.features` file as `name=on` or `name=off`, on the line that
95
+ * names it when there is one (commented out or not), else at the end; `null` turns the line
96
+ * back into the template's `# name=on|off`. Other lines and comments stay as they are. For the
97
+ * `wizards features` command.
98
+ */
99
+ export function writeFeature(name, on, file = featuresFile()) {
100
+ let lines = [];
101
+ try {
102
+ lines = readFileSync(file, "utf8").replace(/\n+$/, "").split("\n");
103
+ }
104
+ catch {
105
+ lines = [];
106
+ }
107
+ const names = (line) => {
108
+ const m = /^\s*#?\s*([A-Za-z0-9.]+)\s*=\s*\S+\s*(?:#.*)?$/.exec(line);
109
+ return m?.[1] === name;
110
+ };
111
+ const written = on === null ? `# ${name}=on|off` : `${name}=${on ? "on" : "off"}`;
112
+ const at = lines.findIndex(names);
113
+ if (at === -1) {
114
+ lines.push(written);
115
+ }
116
+ else {
117
+ lines[at] = written;
118
+ }
119
+ mkdirSync(dirname(file), { recursive: true });
120
+ writeFileSync(file, `${lines.join("\n")}\n`);
121
+ fileCache = null;
122
+ return fileFeatures(file);
123
+ }
@@ -109,6 +109,19 @@ async function call(method, path, body) {
109
109
  export function tenantMembers(id) {
110
110
  return call("GET", `/v1/tenants/${encodeURIComponent(id)}/members`);
111
111
  }
112
+ const users = new Map();
113
+ /** A person's own feature switches, as an admin set them at the Manage-App; cached a minute. */
114
+ export async function userFeatures(userId) {
115
+ const hit = users.get(userId);
116
+ if (hit && Date.now() - hit.at < 60_000) {
117
+ return hit.value;
118
+ }
119
+ const value = await call("GET", `/v1/users/${encodeURIComponent(userId)}`)
120
+ .then((u) => u.features ?? {})
121
+ .catch(() => hit?.value ?? {});
122
+ users.set(userId, { at: Date.now(), value });
123
+ return value;
124
+ }
112
125
  const tenants = new Map();
113
126
  /** Plan, limits and balance of a tenant, cached for a minute. */
114
127
  export async function tenantInfo(id, fresh = false) {
@@ -144,6 +157,17 @@ export function release(runId) {
144
157
  export function runUsage(tenantId, runId) {
145
158
  return call("GET", `/v1/runs/${encodeURIComponent(runId)}/usage?tenantId=${encodeURIComponent(tenantId)}`);
146
159
  }
160
+ export function tenantUsage(tenantId, months = 3) {
161
+ return call("GET", `/v1/tenants/${encodeURIComponent(tenantId)}/usage?months=${months}`);
162
+ }
163
+ /** The plans of a Manage-App: public, no key needed. */
164
+ export async function publicPlans(base) {
165
+ const res = await fetch(`${base}/v1/plans`, { signal: AbortSignal.timeout(10_000) });
166
+ if (!res.ok) {
167
+ throw new ManageError(res.status, "error", `Manage-App ${res.status}`);
168
+ }
169
+ return (await res.json());
170
+ }
147
171
  export function bookUsage(input) {
148
172
  return call("POST", "/v1/usage", input);
149
173
  }
@@ -20,6 +20,17 @@ const manifestSchema = z.looseObject({
20
20
  server: z.string().optional(),
21
21
  studio: z.string().optional(),
22
22
  styles: z.string().optional(),
23
+ features: z
24
+ .record(z.string().regex(/^[a-z][a-zA-Z0-9]*$/), z.union([
25
+ z.boolean(),
26
+ z.object({
27
+ kind: z.enum(["release", "plan"]).optional(),
28
+ default: z.boolean().optional(),
29
+ label: z.string().max(80).optional(),
30
+ hint: z.string().max(300).optional(),
31
+ }),
32
+ ]))
33
+ .optional(),
23
34
  });
24
35
  /** `.mjs` is left out: Node keeps such a file once imported, so a reload would not read it again. */
25
36
  const CODE = new Set([".ts", ".js"]);
@@ -12,8 +12,10 @@ import { pluginConnections } from "../connectors/plugin-connections.js";
12
12
  import { db, onTenantOpen } from "../db/client.js";
13
13
  import { parseDocument } from "../documents/parse.js";
14
14
  import { env } from "../env.js";
15
+ import { currentFeatures } from "../features.js";
15
16
  import { managed } from "../manage.js";
16
17
  import { conversationAccess, ModelUnavailableError, textModel } from "../models.js";
18
+ import { seal, unseal } from "../secrets/crypto.js";
17
19
  import { putIndexEntry, removeIndexEntries } from "../services/project-index.js";
18
20
  import { originData } from "../services/space-origin.js";
19
21
  import { safeFetch } from "../tools/net-guard.js";
@@ -92,6 +94,15 @@ function apiFor(record) {
92
94
  plugin: source.manifest,
93
95
  resolvePath: (relative) => resolve(source.root, relative),
94
96
  config: { get: (key) => process.env[key]?.trim() || undefined },
97
+ features: {
98
+ // A short name is the plugin's own switch; a dotted or core name is taken as it is.
99
+ has: async (name) => {
100
+ const all = await currentFeatures();
101
+ const own = `${source.id}.${name}`;
102
+ return (own in all ? all[own] : all[name]) === true;
103
+ },
104
+ all: currentFeatures,
105
+ },
95
106
  log: {
96
107
  info: (...args) => console.log(tag, ...args),
97
108
  warn: (...args) => console.warn(tag, ...args),
@@ -205,6 +216,7 @@ function apiFor(record) {
205
216
  };
206
217
  },
207
218
  connections: pluginConnections(source.id),
219
+ secrets: { seal, unseal },
208
220
  registerStarter(starter) {
209
221
  if (!PLUGIN_ID.test(starter.id)) {
210
222
  throw new Error(`Starter "${starter.id}": an id is lower case, digits and "-".`);
@@ -6,6 +6,7 @@ import { z } from "zod";
6
6
  import { closeTenantDb, tenantDb } from "../db/client.js";
7
7
  import { logs, runDetail, status, tenantModels } from "../debug.js";
8
8
  import { env } from "../env.js";
9
+ import { declaredFeatures } from "../features.js";
9
10
  import { removeTenantObjects } from "../files/objects.js";
10
11
  import { tailQuery } from "../log.js";
11
12
  import { forgetTenant, managed } from "../manage.js";
@@ -51,6 +52,8 @@ export const internalRoutes = new Hono()
51
52
  description: p.source.manifest.description ?? "",
52
53
  version: p.source.manifest.version ?? null,
53
54
  })),
55
+ /** Every feature switch this runtime knows: the core's and its plugins' (under their ids). */
56
+ features: declaredFeatures(),
54
57
  });
55
58
  })
56
59
  .post("/tenants/:id", async (c) => {
@@ -1,15 +1,18 @@
1
1
  import { mkdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { MODEL_CLASSES, PLUGIN_ID, TEXT_CLASSES } from "@engenty-wizards/shared/definition";
3
+ import { ASSISTANT_LAYOUTS, ASSISTANT_PAGE_BYTES, assistantTurnSchema, } from "@engenty-wizards/shared/assistant";
4
+ import { MODEL_CLASSES, TEXT_CLASSES } from "@engenty-wizards/shared/definition";
4
5
  import { CATEGORY_TYPES, whereSchema } from "@engenty-wizards/shared/knowledge";
5
6
  import { PROJECT_FILE_KINDS } from "@engenty-wizards/shared/projects";
6
7
  import { isCreditsRef } from "@engenty-wizards/shared/providers";
7
8
  import { generateText } from "ai";
8
9
  import { Hono } from "hono";
9
10
  import { streamSSE } from "hono/streaming";
11
+ import { nanoid } from "nanoid";
10
12
  import { z } from "zod";
11
- import { runProjectAssistant } from "../agents/project-assistant.js";
13
+ import { runStudioAssistant } from "../agents/studio-assistant.js";
12
14
  import { chatEngine, setChatEngine, subscriptionClients } from "../agents/subscription.js";
15
+ import { answerBrowser, awaitBrowser } from "../assistant/browser.js";
13
16
  import { accountOverview, linkedAccount, startLink, unlink } from "../auth/account.js";
14
17
  import { createLocalKey, deleteLocalKey, listLocalKeys } from "../auth/keys.js";
15
18
  import { appStates, connectApps } from "../cli/connect.js";
@@ -19,18 +22,20 @@ import { balanceCredits, canSpend } from "../credits/credits.js";
19
22
  import { estimateRun } from "../credits/estimate.js";
20
23
  import { missingModels, stepsWithoutModel } from "../engine/requirements.js";
21
24
  import { env } from "../env.js";
25
+ import { feature, features } from "../features.js";
22
26
  import { freshAuth, loginEnv } from "../harness/env.js";
23
27
  import { detectHarness, detectHarnesses, HARNESS_IDS, harness, installSpec, } from "../harness/index.js";
24
28
  import { closeTerminal, openTerminal, resizeTerminal, subscribeTerminal, writeTerminal, } from "../harness/terminal.js";
25
- import { managed, tenantInfo, tenantMembers } from "../manage.js";
29
+ import { managed, tenantInfo, tenantMembers, userFeatures } from "../manage.js";
26
30
  import { seenApps } from "../mcp/seen.js";
27
31
  import { generateImageMedia, generateSpeechMedia, generateVideoMedia } from "../media/generate.js";
28
32
  import { transcribeAudio } from "../media/transcribe.js";
29
- import { checkKey, classProblem, embeddingModel, hasTextModel, LOCAL_KEYS, localModelSettings, ModelUnavailableError, modelSettings, saveLocalModels, saveModels, storedKey, textModel, } from "../models.js";
33
+ import { checkKey, classProblem, classWays, embeddingModel, hasTextModel, LOCAL_KEYS, localModelSettings, ModelUnavailableError, modelSettings, saveLocalModels, saveModels, storedKey, textModel, } from "../models.js";
30
34
  import { refreshPro } from "../plugins/pro.js";
31
35
  import { HTML_RESPONSE_CSP } from "../render/guard.js";
32
36
  import { isAdminRole, mayBuild, mayCreate, projectWritable, requireWritable, } from "../services/access.js";
33
37
  import { architectTurn } from "../services/architect.js";
38
+ import { addMessage, assistantLayout, currentChat, earlierChats, foldChat, newChat, openChat, readChat, turnHistory, } from "../services/assistant-chats.js";
34
39
  import { checkForCloud, cloudLinked, cloudSpaces, cloudState, forgetCloud, publishAndSync, pushSharing, removeFromCloud, replaceCloudSpaces, rotateInCloud, syncToCloud, } from "../services/cloud.js";
35
40
  import { notFound, ServiceError } from "../services/errors.js";
36
41
  import { deleteFile, listFiles, readFile, writeFile } from "../services/files.js";
@@ -189,8 +194,9 @@ export const studio = new Hono()
189
194
  const linked = managed ? null : await linkedAccount();
190
195
  const overview = linked ? await accountOverview() : null;
191
196
  const profile = await userProfile(user);
192
- // What the Manage-App says of the tenant: its plan and feature switches.
197
+ // What the Manage-App says of the tenant: its plan and feature switches; and of the person.
193
198
  const info = managed ? await tenantInfo(user.tenantId).catch(() => null) : null;
199
+ const own = managed ? await userFeatures(user.id) : null;
194
200
  return c.json({
195
201
  user: { id: user.id, name: profile.name, email: profile.email, image: user.image ?? null },
196
202
  /** What the person says about themselves; name and e-mail are the account's when managed. */
@@ -201,8 +207,8 @@ export const studio = new Hono()
201
207
  /** The plan the team is on; null alone, or where the Manage-App names none. */
202
208
  plan: info?.plan ?? null,
203
209
  },
204
- /** The plan's feature switches (`ownKeys`, …); alone, everything is on. */
205
- features: managed ? (info?.features ?? {}) : { ownKeys: true },
210
+ /** The feature switches: the code's defaults, what the Manage-App says of the team and the person, this install's file. */
211
+ features: features(managed ? { ...info?.features, ...own } : overview?.tenant.features),
206
212
  mode: managed ? "managed" : "local",
207
213
  /** The tenant's balance; null where the runtime resolves models itself. */
208
214
  credits: managed ? await balanceCredits() : null,
@@ -277,6 +283,118 @@ export const studio = new Hono()
277
283
  return c.json(await updateStatus());
278
284
  })
279
285
  .put("/profile", async (c) => c.json(await saveProfile(c.get("user"), profileSchema.parse(await c.req.json()))))
286
+ // --- the studio's assistant -------------------------------------------------
287
+ // One open chat per person and tenant, on every page; turns stream as SSE events shaped like
288
+ // AG-UI's (packages/shared/src/assistant.ts).
289
+ .get("/assistant/chat", async (c) => c.json(await currentChat(c.get("user"))))
290
+ .post("/assistant/chat/new", async (c) => c.json(await newChat(c.get("user"))))
291
+ .get("/assistant/chats", async (c) => c.json({ chats: await earlierChats(c.get("user")) }))
292
+ .get("/assistant/chats/:id", async (c) => c.json(await readChat(c.get("user"), c.req.param("id"))))
293
+ .get("/assistant/layout", async (c) => c.json({ layout: await assistantLayout(c.get("user")) }))
294
+ .put("/assistant/layout", async (c) => {
295
+ const { layout } = z.object({ layout: z.enum(ASSISTANT_LAYOUTS) }).parse(await c.req.json());
296
+ await writeSetting(`assistant-layout:${c.get("user").tenantId}:${c.get("user").id}`, layout);
297
+ return c.json({ layout });
298
+ })
299
+ // Live chat reads answers aloud with the speech model where one is set up; else the browser's voices.
300
+ .get("/assistant/voice", async (c) => c.json({ way: (await classWays()).speech.kind }))
301
+ .post("/assistant/speak", async (c) => {
302
+ const { text } = z.object({ text: z.string().min(1).max(4000) }).parse(await c.req.json());
303
+ if ((await classWays()).speech.kind === "none") {
304
+ throw new ServiceError("refused", "Hier spricht kein Sprachmodell.");
305
+ }
306
+ if (!(await canSpend())) {
307
+ throw new ServiceError("no_credits", "Dein Guthaben ist aufgebraucht.");
308
+ }
309
+ const voice = await generateSpeechMedia({ text, abortSignal: c.req.raw.signal });
310
+ return c.body(new Uint8Array(voice.bytes), 200, { "content-type": voice.mime });
311
+ })
312
+ // A browser tool's result: the turn that waits for it goes on.
313
+ .post("/assistant/tool/:callId", async (c) => {
314
+ const body = z.object({ result: z.unknown() }).parse(await c.req.json());
315
+ const taken = answerBrowser(c.get("user").id, c.req.param("callId"), body.result ?? null);
316
+ return c.json({ ok: taken }, taken ? 200 : 404);
317
+ })
318
+ .post("/assistant/turn", async (c) => {
319
+ const user = c.get("user");
320
+ const body = assistantTurnSchema
321
+ .extend({ lang: z.enum(["de", "en"]).default("de") })
322
+ .parse(await c.req.json());
323
+ if (!(await canSpend())) {
324
+ throw new ServiceError("no_credits", "Dein Guthaben ist aufgebraucht.");
325
+ }
326
+ const project = body.projectId ? await ownedProject(user.id, body.projectId) : null;
327
+ const writable = project ? await projectWritable(project) : false;
328
+ // The page's snapshot is cut, not refused: a page that says too much still gets an answer.
329
+ const page = body.page && JSON.stringify(body.page).length > ASSISTANT_PAGE_BYTES
330
+ ? { route: body.page.route, title: body.page.title, view: body.page.view }
331
+ : (body.page ?? null);
332
+ const chat = await openChat(user);
333
+ const history = await turnHistory(user, chat);
334
+ const runId = nanoid(10);
335
+ const userMessageId = await addMessage(chat.id, {
336
+ role: "user",
337
+ content: body.message,
338
+ page: page ? { route: page.route, title: page.title } : null,
339
+ });
340
+ return streamSSE(c, async (stream) => {
341
+ const abort = new AbortController();
342
+ stream.onAbort(() => abort.abort());
343
+ const send = (event, data) => stream.writeSSE({ event, data: JSON.stringify(data) });
344
+ const messageId = nanoid(14);
345
+ await send("run_started", { threadId: chat.id, runId, messageId: userMessageId });
346
+ let reply = "";
347
+ try {
348
+ const result = await runStudioAssistant({
349
+ user,
350
+ chat,
351
+ history,
352
+ project,
353
+ writable,
354
+ message: body.message,
355
+ page,
356
+ browserTools: body.tools,
357
+ lang: body.lang,
358
+ signal: abort.signal,
359
+ onText: (delta) => {
360
+ reply += delta;
361
+ void send("text", { messageId, delta });
362
+ },
363
+ onActivity: (label) => void send("activity", { label }),
364
+ onChanged: () => void send("changed", {}),
365
+ onCard: (card) => void send("card", card),
366
+ onToolCall: (call) => void send("tool_call", call),
367
+ onToolResult: (result) => void send("tool_result", result),
368
+ callBrowser: (call) => awaitBrowser(user.id, call.toolCallId, abort.signal),
369
+ });
370
+ reply =
371
+ result.reply || (result.changed ? (body.lang === "de" ? "Erledigt." : "Done.") : "");
372
+ const stored = await addMessage(chat.id, {
373
+ role: "assistant",
374
+ content: reply,
375
+ cards: result.cards,
376
+ toolCalls: result.toolCalls,
377
+ changed: result.changed,
378
+ });
379
+ await send("done", { messageId: stored, reply, changed: result.changed });
380
+ }
381
+ catch (err) {
382
+ console.error("[studio-assistant]", err);
383
+ if (reply.trim()) {
384
+ await addMessage(chat.id, { role: "assistant", content: reply.trim() }).catch(() => null);
385
+ }
386
+ await send("error", {
387
+ message: err instanceof ServiceError || err instanceof ModelUnavailableError
388
+ ? err.message
389
+ : body.lang === "de"
390
+ ? "Da ist etwas schiefgelaufen. Bitte noch einmal versuchen."
391
+ : "Something went wrong. Please try again.",
392
+ });
393
+ }
394
+ // Older messages fold into the chat's running summary once enough have piled up.
395
+ void foldChat(chat.id).catch((err) => console.error("[studio-assistant] fold:", err));
396
+ });
397
+ })
280
398
  // --- projects --------------------------------------------------------------
281
399
  .get("/projects", async (c) => {
282
400
  const projects = await listProjects(c.get("user").id);
@@ -396,71 +514,6 @@ export const studio = new Hono()
396
514
  .object({ query: z.string().min(1).max(400), where: whereSchema.optional() })
397
515
  .parse(await c.req.json());
398
516
  return c.json(await searchKnowledge(project.id, body.query, { where: body.where }));
399
- })
400
- // The assistant fills the project in: from a description, a website, the files given.
401
- .post("/projects/:id/assist", async (c) => {
402
- const user = c.get("user");
403
- const project = await ownedProject(user.id, c.req.param("id"));
404
- await requireWritable(project);
405
- const body = z
406
- .object({
407
- message: z.string().min(1).max(8000),
408
- history: z
409
- .array(z.object({ role: z.enum(["user", "assistant"]), content: z.string().max(8000) }))
410
- .max(24)
411
- .default([]),
412
- part: z.enum(["info", "knowledge"]).default("info"),
413
- plugin: z.string().regex(PLUGIN_ID).optional(),
414
- })
415
- .parse(await c.req.json());
416
- if (!(await canSpend())) {
417
- throw new ServiceError("no_credits", "Dein Guthaben ist aufgebraucht.");
418
- }
419
- return streamSSE(c, async (stream) => {
420
- const abort = new AbortController();
421
- stream.onAbort(() => abort.abort());
422
- try {
423
- const result = await runProjectAssistant({
424
- userId: user.id,
425
- projectId: project.id,
426
- message: body.message,
427
- history: body.history,
428
- part: body.part,
429
- plugin: body.plugin,
430
- signal: abort.signal,
431
- onText: (delta) => {
432
- void stream.writeSSE({ event: "text", data: JSON.stringify(delta) });
433
- },
434
- onActivity: (label) => {
435
- void stream.writeSSE({ event: "activity", data: JSON.stringify(label) });
436
- },
437
- onChanged: () => {
438
- void stream.writeSSE({ event: "changed", data: "1" });
439
- },
440
- onCard: (card) => {
441
- void stream.writeSSE({ event: "card", data: JSON.stringify(card) });
442
- },
443
- });
444
- await stream.writeSSE({
445
- event: "done",
446
- data: JSON.stringify({
447
- reply: result.reply || (result.changed ? "Erledigt." : ""),
448
- changed: result.changed,
449
- }),
450
- });
451
- }
452
- catch (err) {
453
- console.error("[project-assistant]", err);
454
- await stream.writeSSE({
455
- event: "error",
456
- data: JSON.stringify({
457
- message: err instanceof ServiceError || err instanceof ModelUnavailableError
458
- ? err.message
459
- : "Da ist etwas schiefgelaufen. Bitte noch einmal versuchen.",
460
- }),
461
- });
462
- }
463
- });
464
517
  })
465
518
  .delete("/projects/:id", async (c) => {
466
519
  await deleteProject(c.get("user").id, c.req.param("id"));
@@ -1034,7 +1087,7 @@ export const studio = new Hono()
1034
1087
  const info = await tenantInfo(c.get("user").tenantId).catch(() => null);
1035
1088
  const own = Object.values(input.keys ?? {}).some((key) => key?.trim()) ||
1036
1089
  Object.values(input.bindings ?? {}).some((ref) => ref && !isCreditsRef(ref));
1037
- if (own && info && info.features?.ownKeys === false) {
1090
+ if (own && info && !feature("ownKeys", info.features)) {
1038
1091
  return c.json({
1039
1092
  error: `Eigene API Keys gibt es nicht im Paket ${info.plan?.name ?? "des Teams"}.`,
1040
1093
  code: "plan",