wizards 0.2.47 → 0.2.49

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 (181) hide show
  1. package/README.md +2 -1
  2. package/apps/runtime/dist/agents/{project-assistant.js → studio-assistant.js} +199 -69
  3. package/apps/runtime/dist/agents/website.js +25 -2
  4. package/apps/runtime/dist/app.js +2 -1
  5. package/apps/runtime/dist/apple/wizards-apple +0 -0
  6. package/apps/runtime/dist/assistant/browser.js +26 -0
  7. package/apps/runtime/dist/assistant/docs.js +158 -0
  8. package/apps/runtime/dist/assistant/knows.js +325 -0
  9. package/apps/runtime/dist/assistant/primer.js +26 -0
  10. package/apps/runtime/dist/authoring/guide.js +5 -0
  11. package/apps/runtime/dist/cli/status.js +1 -1
  12. package/apps/runtime/dist/connectors/plugin-connections.js +123 -29
  13. package/apps/runtime/dist/db/migrations/tenant/0012_assistant_chat.sql +40 -0
  14. package/apps/runtime/dist/db/migrations/tenant/0013_run_origin.sql +1 -0
  15. package/apps/runtime/dist/db/migrations/tenant/meta/0012_snapshot.json +3132 -0
  16. package/apps/runtime/dist/db/migrations/tenant/meta/0013_snapshot.json +3139 -0
  17. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +14 -0
  18. package/apps/runtime/dist/db/schema.js +35 -0
  19. package/apps/runtime/dist/docs/dev/index.md +34 -0
  20. package/apps/runtime/dist/docs/dev/meta.json +7 -0
  21. package/apps/runtime/dist/docs/dev/plugins/connections.md +70 -0
  22. package/apps/runtime/dist/docs/dev/plugins/events.md +86 -0
  23. package/apps/runtime/dist/docs/dev/plugins/examples.md +99 -0
  24. package/apps/runtime/dist/docs/dev/plugins/index.md +72 -0
  25. package/apps/runtime/dist/docs/dev/plugins/layout.md +88 -0
  26. package/apps/runtime/dist/docs/dev/plugins/meta.json +29 -0
  27. package/apps/runtime/dist/docs/dev/plugins/pro-modules.md +59 -0
  28. package/apps/runtime/dist/docs/dev/plugins/quick-start.md +92 -0
  29. package/apps/runtime/dist/docs/dev/plugins/reference.md +298 -0
  30. package/apps/runtime/dist/docs/dev/plugins/reloading.md +75 -0
  31. package/apps/runtime/dist/docs/dev/plugins/routes.md +123 -0
  32. package/apps/runtime/dist/docs/dev/plugins/runners.md +184 -0
  33. package/apps/runtime/dist/docs/dev/plugins/server.md +191 -0
  34. package/apps/runtime/dist/docs/dev/plugins/shipping.md +98 -0
  35. package/apps/runtime/dist/docs/dev/plugins/space.md +260 -0
  36. package/apps/runtime/dist/docs/dev/plugins/starters.md +62 -0
  37. package/apps/runtime/dist/docs/dev/plugins/studio.md +261 -0
  38. package/apps/runtime/dist/docs/dev/plugins/styling.md +109 -0
  39. package/apps/runtime/dist/docs/dev/plugins/tables.md +102 -0
  40. package/apps/runtime/dist/docs/dev/plugins/tools.md +128 -0
  41. package/apps/runtime/dist/docs/meta.json +3 -0
  42. package/apps/runtime/dist/docs/user/ai-apps.md +99 -0
  43. package/apps/runtime/dist/docs/user/assistant.md +52 -0
  44. package/apps/runtime/dist/docs/user/build-a-wizard.md +79 -0
  45. package/apps/runtime/dist/docs/user/command-line.md +76 -0
  46. package/apps/runtime/dist/docs/user/connectors.md +80 -0
  47. package/apps/runtime/dist/docs/user/data.md +61 -0
  48. package/apps/runtime/dist/docs/user/first-start.md +42 -0
  49. package/apps/runtime/dist/docs/user/index.md +45 -0
  50. package/apps/runtime/dist/docs/user/install.md +76 -0
  51. package/apps/runtime/dist/docs/user/meta.json +30 -0
  52. package/apps/runtime/dist/docs/user/models.md +125 -0
  53. package/apps/runtime/dist/docs/user/plugins.md +61 -0
  54. package/apps/runtime/dist/docs/user/run.md +92 -0
  55. package/apps/runtime/dist/docs/user/server.md +50 -0
  56. package/apps/runtime/dist/docs/user/space.md +97 -0
  57. package/apps/runtime/dist/docs/user/steps.md +196 -0
  58. package/apps/runtime/dist/docs/user/test-and-share.md +216 -0
  59. package/apps/runtime/dist/docs/user/troubleshooting.md +57 -0
  60. package/apps/runtime/dist/docs/user/wordpress.md +103 -0
  61. package/apps/runtime/dist/engine/device.js +182 -0
  62. package/apps/runtime/dist/engine/events.js +3 -0
  63. package/apps/runtime/dist/engine/input.js +3 -0
  64. package/apps/runtime/dist/engine/prepare.js +1 -0
  65. package/apps/runtime/dist/engine/requirements.js +6 -109
  66. package/apps/runtime/dist/engine/runner.js +13 -5
  67. package/apps/runtime/dist/engine/steps.js +2 -1
  68. package/apps/runtime/dist/env.js +1 -1
  69. package/apps/runtime/dist/harness/apple.js +258 -0
  70. package/apps/runtime/dist/harness/model.js +3 -1
  71. package/apps/runtime/dist/manage.js +11 -0
  72. package/apps/runtime/dist/mcp/auth.js +3 -0
  73. package/apps/runtime/dist/mcp/scopes.js +11 -2
  74. package/apps/runtime/dist/media/transcribe.js +6 -1
  75. package/apps/runtime/dist/models.js +63 -9
  76. package/apps/runtime/dist/plugins/loader.js +2 -0
  77. package/apps/runtime/dist/routes/api.js +232 -1
  78. package/apps/runtime/dist/routes/plugins.js +6 -2
  79. package/apps/runtime/dist/routes/runs.js +65 -3
  80. package/apps/runtime/dist/routes/studio.js +130 -69
  81. package/apps/runtime/dist/services/api.js +244 -0
  82. package/apps/runtime/dist/services/assistant-chats.js +267 -0
  83. package/apps/runtime/dist/services/engenty-shapes.js +1 -1
  84. package/apps/runtime/dist/services/package.js +77 -9
  85. package/apps/runtime/dist/services/project-index.js +1 -1
  86. package/apps/runtime/dist/services/runs.js +4 -3
  87. package/apps/runtime/dist/services/site.js +262 -0
  88. package/apps/runtime/dist/services/space-origin.js +45 -2
  89. package/apps/web/dist/assets/AboutDialog-6CCpWqAl.js +1 -0
  90. package/apps/web/dist/assets/ChangelogDialog-ApswqjRk.js +1 -0
  91. package/apps/web/dist/assets/ChatView-D7N2QyGS.js +10 -0
  92. package/apps/web/dist/assets/EditorPage-CbtYQTWj.js +3 -0
  93. package/apps/web/dist/assets/FlowPreview-KTaelucs.js +1 -0
  94. package/apps/web/dist/assets/{Harness-zKMptCzB.js → Harness-_mD1Stm4.js} +2 -2
  95. package/apps/web/dist/assets/Marketplace-DKQ9j4OC.js +2 -0
  96. package/apps/web/dist/assets/NewWizardPage-CoCCRcoi.js +1 -0
  97. package/apps/web/dist/assets/ProjectPage-DDLh_qxi.js +2 -0
  98. package/apps/web/dist/assets/PublicRunner-Lpu-BY5w.js +1 -0
  99. package/apps/web/dist/assets/ReadOnly-ClY8xMQS.js +1 -0
  100. package/apps/web/dist/assets/RunDrawer-JXG5wZp7.js +4 -0
  101. package/apps/web/dist/assets/RunnerView-BlUSqfqB.js +1 -0
  102. package/apps/web/dist/assets/SettingsPage-V_E267hI.js +1 -0
  103. package/apps/web/dist/assets/SetupPage-Dvoze8cZ.js +1 -0
  104. package/apps/web/dist/assets/SharePage-DBcp_npb.js +1 -0
  105. package/apps/web/dist/assets/brand-CNF5NxD9.js +2 -0
  106. package/apps/web/dist/assets/changelog-CmZrNHwc.js +1 -0
  107. package/apps/web/dist/assets/circle-alert-r2qc1Vej.js +1 -0
  108. package/apps/web/dist/assets/engenty-eXZ-EAwd.js +1 -0
  109. package/apps/web/dist/assets/esm-DZeij_95.js +7 -0
  110. package/apps/web/dist/assets/{fluffy-engenty-D7rFrNcJ.js → fluffy-engenty-ClRou7yu.js} +1 -1
  111. package/apps/web/dist/assets/index-BbogBDv_.js +11 -0
  112. package/apps/web/dist/assets/index-Dr0bv52Q.css +1 -0
  113. package/apps/web/dist/assets/jsx-runtime-BNakU3Ej.js +1 -0
  114. package/apps/web/dist/assets/lock-N-C6-ZeG.js +1 -0
  115. package/apps/web/dist/assets/logo-C4V2_3Ar.js +1 -0
  116. package/apps/web/dist/assets/oss-credits-BQQX0kvk.js +1 -0
  117. package/apps/web/dist/assets/pdfmake-Cx9scTbD.js +228 -0
  118. package/apps/web/dist/assets/rolldown-runtime-hePW80VL.js +1 -0
  119. package/apps/web/dist/assets/session-Cpg5S8B3.js +1 -0
  120. package/apps/web/dist/assets/settings-menu-C7m2i7Sf.js +1 -0
  121. package/apps/web/dist/assets/ui-DKcggL84.js +133 -0
  122. package/apps/web/dist/assets/upload-D24SDj7W.js +1 -0
  123. package/apps/web/dist/assets/useMutation-DKyQXgyj.js +1 -0
  124. package/apps/web/dist/assets/vfs_fonts-DllDSYt1.js +1 -0
  125. package/apps/web/dist/assets/volume-2-C-Y7-S4b.js +1 -0
  126. package/apps/web/dist/embed.js +57 -8
  127. package/apps/web/dist/index.html +12 -16
  128. package/apps/web/dist/mcp/flow.html +435 -207
  129. package/modules/calls/dist/client.css +1 -1
  130. package/modules/sms/dist/client.css +1 -1
  131. package/modules/whatsapp/dist/client.css +1 -1
  132. package/node_modules/@engenty-wizards/plugin-sdk/dist/index.d.ts +82 -7
  133. package/node_modules/@engenty-wizards/plugin-sdk/dist/studio.d.ts +58 -4
  134. package/node_modules/@engenty-wizards/shared/dist/assistant.d.ts +113 -0
  135. package/node_modules/@engenty-wizards/shared/dist/assistant.js +55 -0
  136. package/node_modules/@engenty-wizards/shared/dist/definition.d.ts +58 -1
  137. package/node_modules/@engenty-wizards/shared/dist/definition.js +94 -4
  138. package/node_modules/@engenty-wizards/shared/dist/fit.d.ts +71 -0
  139. package/node_modules/@engenty-wizards/shared/dist/fit.js +381 -0
  140. package/node_modules/@engenty-wizards/shared/dist/run.d.ts +3 -1
  141. package/package.json +1 -1
  142. package/apps/web/dist/assets/AboutDialog-t7bpiasT.js +0 -1
  143. package/apps/web/dist/assets/ChangelogDialog-B87yS6aN.js +0 -1
  144. package/apps/web/dist/assets/ChatView-Dm764bYy.js +0 -10
  145. package/apps/web/dist/assets/EditorPage-BG_Ue2iC.js +0 -3
  146. package/apps/web/dist/assets/FlowPreview-ChXfiMn_.js +0 -1
  147. package/apps/web/dist/assets/HomePage-BXSg5P5k.js +0 -1
  148. package/apps/web/dist/assets/Marketplace-BWhUJ4UX.js +0 -2
  149. package/apps/web/dist/assets/NewWizardPage-C3NqEGmg.js +0 -1
  150. package/apps/web/dist/assets/ProjectPage-D6Fy7uTV.js +0 -2
  151. package/apps/web/dist/assets/PublicRunner-ChgJs0C9.js +0 -1
  152. package/apps/web/dist/assets/ReadOnly-C9P9aiU6.js +0 -1
  153. package/apps/web/dist/assets/RunDrawer-CvIKLphz.js +0 -4
  154. package/apps/web/dist/assets/RunnerView-Bmayop7s.js +0 -2
  155. package/apps/web/dist/assets/SettingsPage-QkwtRFoD.js +0 -1
  156. package/apps/web/dist/assets/SetupPage-B3IOQLO3.js +0 -1
  157. package/apps/web/dist/assets/SharePage-C3QEzicl.js +0 -1
  158. package/apps/web/dist/assets/ThemeSwitch-3IzIOlNz.js +0 -1
  159. package/apps/web/dist/assets/arrow-right-Dpp_mpHe.js +0 -1
  160. package/apps/web/dist/assets/changelog-Du2gWzlN.js +0 -1
  161. package/apps/web/dist/assets/circle-alert-CPo3Naay.js +0 -1
  162. package/apps/web/dist/assets/definition-CQGiBQ4X.js +0 -56
  163. package/apps/web/dist/assets/engenty-Cm8yZLON.js +0 -1
  164. package/apps/web/dist/assets/esm-rJY59Ixx.js +0 -7
  165. package/apps/web/dist/assets/external-link-CpU8aJY2.js +0 -1
  166. package/apps/web/dist/assets/index-Cz6c1S5g.js +0 -78
  167. package/apps/web/dist/assets/index-DKHClEy3.css +0 -1
  168. package/apps/web/dist/assets/jsx-runtime-D3jfb0Ew.js +0 -1
  169. package/apps/web/dist/assets/lock-C_WlXIQ0.js +0 -1
  170. package/apps/web/dist/assets/logo-C80CWCDM.js +0 -1
  171. package/apps/web/dist/assets/oss-credits-CIxnNZor.js +0 -1
  172. package/apps/web/dist/assets/react-dom-DenslgJm.js +0 -1
  173. package/apps/web/dist/assets/refresh-cw-Cli5WGnW.js +0 -1
  174. package/apps/web/dist/assets/session-miDEdw2c.js +0 -1
  175. package/apps/web/dist/assets/settings-menu-ROT8Lbbj.js +0 -1
  176. package/apps/web/dist/assets/sparkles-CP5H-O1E.js +0 -1
  177. package/apps/web/dist/assets/trash-DU-hZpV0.js +0 -1
  178. package/apps/web/dist/assets/ui-D92EkdEB.js +0 -9
  179. package/apps/web/dist/assets/upload-DMq5N6Fw.js +0 -1
  180. package/apps/web/dist/assets/useMutation-DKcIz55V.js +0 -1
  181. package/apps/web/dist/assets/volume-2-0SfkvOho.js +0 -1
@@ -1,15 +1,24 @@
1
1
  import { Hono } from "hono";
2
2
  import { bodyLimit } from "hono/body-limit";
3
3
  import { z } from "zod";
4
+ import { balanceCredits } from "../credits/credits.js";
4
5
  import { withTenant } from "../db/client.js";
6
+ import { env } from "../env.js";
5
7
  import { allowed } from "../limits.js";
8
+ import { managed, tenantInfo } from "../manage.js";
6
9
  import { authenticate, principalOf } from "../mcp/auth.js";
7
- import { asRole } from "../services/access.js";
10
+ import { loadedPlugin, pluginIdsOf } from "../plugins/registry.js";
11
+ import { asRole, mayBuild, mayCreate } from "../services/access.js";
12
+ import { apiRun, apiRuns, apiSpaceDetails, apiSpaces, apiWizards } from "../services/api.js";
8
13
  import { ServiceError } from "../services/errors.js";
9
14
  import { deleteFile, draftFiles, writeFile } from "../services/files.js";
15
+ import { asLang, searchMarketplace } from "../services/marketplace.js";
16
+ import { exportWizard, PACKAGE_MIME } from "../services/package.js";
17
+ import { siteJob, siteSchema, startSiteJob } from "../services/site.js";
10
18
  import { checkOnServer, checkSchema, listSyncedSpaces, patchSyncedWizard, removeSyncedSpace, removeSyncedWizard, rotateSyncedLink, syncDataSchema, syncSettingsSchema, syncSpaceData, syncWizard, syncWizardSchema, } from "../services/spaces.js";
11
19
  import { createWizard, ownedWizard, publishWizard, writeDraft } from "../services/wizards.js";
12
20
  import { codeOf, tenantStatus } from "../tenants/control.js";
21
+ import { dispatchAs } from "./plugins.js";
13
22
  const importSchema = z.object({
14
23
  /** An earlier import's wizard: it is updated instead of a new one being made. */
15
24
  wizardId: z.string().optional(),
@@ -24,6 +33,10 @@ const importSchema = z.object({
24
33
  /** Runs a call in the caller's tenant, as the caller's role. */
25
34
  const inTenantAs = (who, fn) => withTenant(who.tenantId, () => asRole(who.role, fn));
26
35
  const HOUR = 60 * 60 * 1000;
36
+ /** Where the account of a managed runtime is looked after: plan, credits, keys. */
37
+ const accountUrl = () => env.manage.url || null;
38
+ /** Plugins of the plans above Free that a client offers when the tenant lacks them. */
39
+ const PRO_PLUGINS = ["contacts", "appointments"];
27
40
  /** A wizard with its workspace: 25 MB of files as base64, and the definition. */
28
41
  const WIZARD_BYTES = 48 * 1024 * 1024;
29
42
  const tooLarge = bodyLimit({
@@ -54,12 +67,230 @@ function withinSyncLimit(c, who) {
54
67
  ? null
55
68
  : c.json({ error: "Zu viele Übertragungen. Bitte später noch einmal.", code: "rate_limited" }, 429);
56
69
  }
70
+ /**
71
+ * A plugin's routes for a client with a key or token (the WordPress plugin's Kontakte, Termine):
72
+ * the plugin's own `registerHttpRoute`s, as the key's person. Reading needs `wizards:read`,
73
+ * anything else `wizards:write`. A plugin the tenant's plan lacks answers `403 { code: "plugin" }`.
74
+ */
75
+ async function pluginCall(c) {
76
+ const who = await caller(c, [c.req.method === "GET" ? "wizards:read" : "wizards:write"]);
77
+ if (who instanceof Response) {
78
+ return who;
79
+ }
80
+ const id = c.req.param("id") ?? "";
81
+ if (!(await pluginIdsOf(who.tenantId)).has(id)) {
82
+ return loadedPlugin(id) || PRO_PLUGINS.includes(id)
83
+ ? c.json({
84
+ error: "Dieses Plugin gehört nicht zu deinem Paket. Mit Pro ist es dabei.",
85
+ code: "plugin",
86
+ plugin: id,
87
+ }, 403)
88
+ : c.json({ error: "not found", code: "not_found" }, 404);
89
+ }
90
+ return inTenantAs(who, () => dispatchAs(c, {
91
+ id: who.userId,
92
+ tenantId: who.tenantId,
93
+ role: who.role,
94
+ name: who.name ?? "",
95
+ email: who.email ?? "",
96
+ }));
97
+ }
98
+ const runsQuery = z.object({
99
+ space: z.string().optional(),
100
+ wizard: z.string().optional(),
101
+ status: z.enum(["done", "open", "all"]).optional(),
102
+ q: z.string().max(200).optional(),
103
+ days: z.coerce.number().int().min(1).max(3650).optional(),
104
+ page: z.coerce.number().int().min(1).max(10_000).optional(),
105
+ });
57
106
  /**
58
107
  * The runtime's API for other programs. `/spaces/…` is how a local install's project comes
59
108
  * here: the wizards it publishes, under the ids they have there (docs/manage-contract.md).
60
109
  * `POST /wizards/import` takes a whole wizard as a new one of a tenant that builds here.
61
110
  */
62
111
  export const apiRoutes = new Hono()
112
+ // Who the key or token acts for, and what the account has: plan, plugins, spaces, credits.
113
+ .get("/me", async (c) => {
114
+ const who = await caller(c, []);
115
+ if (who instanceof Response) {
116
+ return who;
117
+ }
118
+ const info = managed ? await tenantInfo(who.tenantId).catch(() => null) : null;
119
+ return inTenantAs(who, async () => {
120
+ const plugins = [...(await pluginIdsOf(who.tenantId))].sort();
121
+ const account = accountUrl();
122
+ return c.json({
123
+ user: { id: who.userId, name: who.name ?? "", email: who.email ?? "", role: who.role },
124
+ tenant: {
125
+ id: who.tenantId,
126
+ name: info?.name ?? "",
127
+ plan: info?.plan ?? null,
128
+ credits: await balanceCredits(),
129
+ },
130
+ /** Makes and changes wizards and spaces here; Free builds in the local app. */
131
+ build: await mayBuild(),
132
+ create: await mayCreate(),
133
+ plugins,
134
+ /** What a plan above this one would add. */
135
+ missing: PRO_PLUGINS.filter((id) => !plugins.includes(id)),
136
+ spaces: await apiSpaces(who.userId),
137
+ scopes: who.scopes,
138
+ client: who.client,
139
+ urls: {
140
+ app: env.appUrl,
141
+ embed: `${env.appUrl}/embed.js`,
142
+ studio: `${env.appUrl}/studio`,
143
+ newWizard: `${env.appUrl}/studio/new`,
144
+ space: `${env.appUrl}/studio/space`,
145
+ account: account,
146
+ billing: account ? `${account}/billing` : null,
147
+ upgrade: account ? `${account}/billing?upgrade=pro` : null,
148
+ },
149
+ });
150
+ });
151
+ })
152
+ // The wizards of the caller's spaces: published ones with their link and ID, drafts without.
153
+ .get("/wizards", async (c) => {
154
+ const who = await caller(c, ["wizards:read"]);
155
+ if (who instanceof Response) {
156
+ return who;
157
+ }
158
+ return inTenantAs(who, async () => c.json({ wizards: await apiWizards(who.userId, c.req.query("space")) }));
159
+ })
160
+ // The published wizard as a `.wizard` package: what a WordPress site runs on its own; with
161
+ // `knowledge=1` the project's pages come along as files (up to the snapshot's cap).
162
+ .get("/wizards/:id/package", async (c) => {
163
+ const who = await caller(c, ["wizards:read"]);
164
+ if (who instanceof Response) {
165
+ return who;
166
+ }
167
+ return inTenantAs(who, async () => {
168
+ const found = await exportWizard(who.userId, c.req.param("id"), {
169
+ published: true,
170
+ knowledge: c.req.query("knowledge") === "1",
171
+ });
172
+ if (!found) {
173
+ return c.json({ error: "Der Wizard ist noch nicht veröffentlicht.", code: "not_found" }, 404);
174
+ }
175
+ return new Response(new Uint8Array(found.zip), {
176
+ headers: {
177
+ "content-type": PACKAGE_MIME,
178
+ "content-disposition": `attachment; filename="${found.name}"`,
179
+ "cache-control": "no-store",
180
+ },
181
+ });
182
+ });
183
+ })
184
+ // A new wizard from a template, published at once: what a website starts with.
185
+ .post("/wizards", async (c) => {
186
+ const who = await caller(c, ["wizards:write", "wizards:publish"]);
187
+ if (who instanceof Response) {
188
+ return who;
189
+ }
190
+ const body = z
191
+ .object({
192
+ starterId: z.string().min(1).max(200),
193
+ spaceId: z.string().optional(),
194
+ lang: z.string().max(10).optional(),
195
+ publish: z.boolean().default(true),
196
+ })
197
+ .parse(await c.req.json());
198
+ return inTenantAs(who, async () => {
199
+ const writer = { source: "mcp", client: who.client };
200
+ const created = await createWizard(who.userId, { projectId: body.spaceId, starterId: body.starterId, lang: body.lang }, writer);
201
+ let published = false;
202
+ if (body.publish && !created.issues.length) {
203
+ published = await publishWizard(who.userId, created.id).then(() => true, () => false);
204
+ }
205
+ const wizard = (await apiWizards(who.userId)).find((w) => w.id === created.id);
206
+ return c.json({ wizard, published, issues: created.issues });
207
+ });
208
+ })
209
+ // What a new wizard can start from: the plugins' starters first, then the marketplace's.
210
+ .get("/templates", async (c) => {
211
+ const who = await caller(c, ["wizards:read"]);
212
+ if (who instanceof Response) {
213
+ return who;
214
+ }
215
+ const q = c.req.query("q")?.trim() ?? "";
216
+ return inTenantAs(who, async () => {
217
+ const { entries } = await searchMarketplace({
218
+ q,
219
+ lang: asLang(c.req.query("lang")),
220
+ limit: 40,
221
+ });
222
+ return c.json({
223
+ templates: entries
224
+ .filter((e) => e.usable && (q || e.starter))
225
+ .map((e) => ({
226
+ id: e.id,
227
+ title: e.title,
228
+ pitch: e.pitch,
229
+ avatar: e.avatar,
230
+ language: e.language,
231
+ useCases: e.useCases,
232
+ formats: e.formats,
233
+ plan: e.plan ?? "free",
234
+ plugin: e.plugin ?? null,
235
+ /** Plugins the tenant lacks: a wizard made from it would not run. */
236
+ needs: e.needs ?? [],
237
+ credits: e.credits,
238
+ })),
239
+ });
240
+ });
241
+ })
242
+ // What visitors left: the live runs of the caller's wizards, by pages of 50.
243
+ .get("/runs", async (c) => {
244
+ const who = await caller(c, ["runs:read"]);
245
+ if (who instanceof Response) {
246
+ return who;
247
+ }
248
+ const query = runsQuery.parse(c.req.query());
249
+ return inTenantAs(who, async () => c.json(await apiRuns(who.userId, {
250
+ spaceId: query.space,
251
+ wizardId: query.wizard,
252
+ status: query.status,
253
+ q: query.q,
254
+ days: query.days,
255
+ page: query.page,
256
+ })));
257
+ })
258
+ .get("/runs/:id", async (c) => {
259
+ const who = await caller(c, ["runs:read"]);
260
+ if (who instanceof Response) {
261
+ return who;
262
+ }
263
+ return inTenantAs(who, async () => c.json(await apiRun(who.userId, c.req.param("id"))));
264
+ })
265
+ // The space's own details: title, about, colours, facts, logo, how much Wissen it holds.
266
+ .get("/space", async (c) => {
267
+ const who = await caller(c, ["wizards:read"]);
268
+ if (who instanceof Response) {
269
+ return who;
270
+ }
271
+ return inTenantAs(who, async () => c.json(await apiSpaceDetails(who.userId, c.req.query("space"))));
272
+ })
273
+ // A website reads itself into the space (services/site.ts); answers with the job to ask after.
274
+ .post("/space/site", tooLarge, async (c) => {
275
+ const who = await caller(c, ["wizards:write"]);
276
+ if (who instanceof Response) {
277
+ return who;
278
+ }
279
+ if (!allowed(`site:${who.tenantId}`, 20, HOUR)) {
280
+ return c.json({ error: "Zu oft hintereinander. Bitte später noch einmal.", code: "rate_limited" }, 429);
281
+ }
282
+ const body = siteSchema.parse(await c.req.json());
283
+ return inTenantAs(who, async () => c.json(await startSiteJob(who, body)));
284
+ })
285
+ .get("/space/site/:job", async (c) => {
286
+ const who = await caller(c, ["wizards:read"]);
287
+ if (who instanceof Response) {
288
+ return who;
289
+ }
290
+ return inTenantAs(who, () => c.json(siteJob(c.req.param("job"))));
291
+ })
292
+ .all("/plugins/:id", pluginCall)
293
+ .all("/plugins/:id/*", pluginCall)
63
294
  .get("/spaces", async (c) => {
64
295
  const who = await caller(c, ["wizards:read"]);
65
296
  if (who instanceof Response) {
@@ -41,8 +41,11 @@ export function answerOf(err) {
41
41
  ? { status: e.status, body: { error: String(e.message ?? e.code), code: e.code } }
42
42
  : null;
43
43
  }
44
- async function dispatch(c) {
45
- const user = c.get("user");
44
+ /**
45
+ * Calls the plugin route the request names, as `user`: a signed-in person of the studio, or the
46
+ * person behind an API key or token (`/api/v1/plugins/…`).
47
+ */
48
+ export async function dispatchAs(c, user) {
46
49
  const id = c.req.param("id") ?? "";
47
50
  const plugin = (await pluginIdsOf(user.tenantId)).has(id) ? loadedPlugin(id) : undefined;
48
51
  if (!plugin) {
@@ -90,6 +93,7 @@ async function dispatch(c) {
90
93
  }
91
94
  return c.json({ error: "not found", code: "not_found" }, 404);
92
95
  }
96
+ const dispatch = (c) => dispatchAs(c, c.get("user"));
93
97
  const TYPES = {
94
98
  "client.js": { kind: "studio", type: "text/javascript; charset=utf-8" },
95
99
  "client.css": { kind: "styles", type: "text/css; charset=utf-8" },
@@ -1,4 +1,4 @@
1
- import { FORMATS, LIST_FORMATS } from "@engenty-wizards/shared/definition";
1
+ import { FORMATS, LIST_FORMATS, TEXT_CLASSES } from "@engenty-wizards/shared/definition";
2
2
  import { TableColumnValueError } from "@engenty-wizards/shared/engenty/data-tables";
3
3
  import { getConnInfo } from "@hono/node-server/conninfo";
4
4
  import { and, eq } from "drizzle-orm";
@@ -13,6 +13,7 @@ import { ConnectError, connectionViews, connectWithCredentials, disconnect, fini
13
13
  import { finishPluginOAuth, pluginStateTenant } from "../connectors/plugin-connections.js";
14
14
  import { db, schema, withTenant } from "../db/client.js";
15
15
  import { answerAsk, pendingAsk } from "../engine/asks.js";
16
+ import { answerDevice, offerDevice } from "../engine/device.js";
16
17
  import { emitEvent, signalChanged, subscribe } from "../engine/events.js";
17
18
  import { pushAvailable, setPushDevice } from "../engine/push.js";
18
19
  import { liveResources } from "../engine/resources.js";
@@ -57,6 +58,23 @@ export function clientIp(c) {
57
58
  * as good as the cookie.
58
59
  */
59
60
  const VISITOR_HEADER = "x-wizards-visitor";
61
+ /** An http(s) address without credentials or fragment, or null for anything else. */
62
+ function webAddress(raw) {
63
+ if (!raw) {
64
+ return null;
65
+ }
66
+ try {
67
+ const url = new URL(raw);
68
+ if (!(url.protocol === "http:" || url.protocol === "https:") || url.username || url.password) {
69
+ return null;
70
+ }
71
+ url.hash = "";
72
+ return url.toString();
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
60
78
  function visitorId(c, create, embedded = false) {
61
79
  let vid = c.req.header(VISITOR_HEADER) || getCookie(c, VISITOR_COOKIE) || null;
62
80
  if (!vid && create) {
@@ -226,7 +244,12 @@ export const publicRoutes = new Hono()
226
244
  return c.json({ error: reason }, 403);
227
245
  }
228
246
  const body = z
229
- .object({ turnstileToken: z.string().optional(), embedded: z.boolean().optional() })
247
+ .object({
248
+ turnstileToken: z.string().optional(),
249
+ embedded: z.boolean().optional(),
250
+ // The website page that embeds the wizard: shown with the result.
251
+ origin: z.string().max(2000).optional(),
252
+ })
230
253
  .parse(await c.req.json().catch(() => ({})));
231
254
  const ip = clientIp(c);
232
255
  if (!(await verifyTurnstile(body.turnstileToken, ip))) {
@@ -251,6 +274,7 @@ export const publicRoutes = new Hono()
251
274
  mode: "live",
252
275
  visitorId: vid,
253
276
  ipHash,
277
+ origin: body.embedded ? webAddress(body.origin) : null,
254
278
  });
255
279
  return c.json({ runId });
256
280
  }
@@ -367,7 +391,14 @@ export const runRoutes = new Hono()
367
391
  await stream.writeSSE({ event: "view", data: JSON.stringify(await viewOf(run)) });
368
392
  }
369
393
  };
370
- const unsubscribe = subscribe(id, () => {
394
+ const unsubscribe = subscribe(id, (signal) => {
395
+ if (signal.device) {
396
+ // The runtime asks the phone around the runner to think: not a change of the run.
397
+ if (!closed) {
398
+ void stream.writeSSE({ event: "device", data: JSON.stringify(signal.device) });
399
+ }
400
+ return;
401
+ }
371
402
  void push();
372
403
  });
373
404
  stream.onAbort(() => {
@@ -382,6 +413,37 @@ export const runRoutes = new Hono()
382
413
  }
383
414
  }
384
415
  });
416
+ })
417
+ // The runner says what the device around it offers the run (the app's Apple Intelligence):
418
+ // from then on short text calls go there first. Renewed on every connect; see engine/device.ts.
419
+ .post("/:id/device", async (c) => {
420
+ const run = await accessibleRun(c, c.req.param("id"));
421
+ if (!run) {
422
+ return c.json({ error: "not found" }, 404);
423
+ }
424
+ const offer = z
425
+ .object({
426
+ think: z
427
+ .object({
428
+ classes: z.array(z.enum(TEXT_CLASSES)).max(TEXT_CLASSES.length),
429
+ maxChars: z.number().int().min(500).max(50_000),
430
+ })
431
+ .optional(),
432
+ })
433
+ .parse(await c.req.json().catch(() => ({})));
434
+ offerDevice(run.id, offer);
435
+ return c.json({ ok: true });
436
+ })
437
+ // The device's answer to one call the stream carried as a `device` event.
438
+ .post("/:id/device/:reqId", async (c) => {
439
+ const run = await accessibleRun(c, c.req.param("id"));
440
+ if (!run) {
441
+ return c.json({ error: "not found" }, 404);
442
+ }
443
+ const answer = z
444
+ .object({ text: z.string().max(200_000).optional(), error: z.string().max(500).optional() })
445
+ .parse(await c.req.json().catch(() => ({})));
446
+ return c.json({ ok: answerDevice(run.id, c.req.param("reqId"), answer) });
385
447
  })
386
448
  .post("/:id/pages/:stepId", async (c) => {
387
449
  const run = await accessibleRun(c, c.req.param("id"));
@@ -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";
@@ -20,6 +23,7 @@ import { estimateRun } from "../credits/estimate.js";
20
23
  import { missingModels, stepsWithoutModel } from "../engine/requirements.js";
21
24
  import { env } from "../env.js";
22
25
  import { feature, features } from "../features.js";
26
+ import { appleStatus } from "../harness/apple.js";
23
27
  import { freshAuth, loginEnv } from "../harness/env.js";
24
28
  import { detectHarness, detectHarnesses, HARNESS_IDS, harness, installSpec, } from "../harness/index.js";
25
29
  import { closeTerminal, openTerminal, resizeTerminal, subscribeTerminal, writeTerminal, } from "../harness/terminal.js";
@@ -27,11 +31,12 @@ import { managed, tenantInfo, tenantMembers, userFeatures } from "../manage.js";
27
31
  import { seenApps } from "../mcp/seen.js";
28
32
  import { generateImageMedia, generateSpeechMedia, generateVideoMedia } from "../media/generate.js";
29
33
  import { transcribeAudio } from "../media/transcribe.js";
30
- import { checkKey, classProblem, embeddingModel, hasTextModel, LOCAL_KEYS, localModelSettings, ModelUnavailableError, modelSettings, saveLocalModels, saveModels, storedKey, textModel, } from "../models.js";
34
+ import { checkKey, classProblem, classWays, embeddingModel, hasTextModel, LOCAL_KEYS, localModelSettings, ModelUnavailableError, modelSettings, saveLocalModels, saveModels, storedKey, textModel, } from "../models.js";
31
35
  import { refreshPro } from "../plugins/pro.js";
32
36
  import { HTML_RESPONSE_CSP } from "../render/guard.js";
33
37
  import { isAdminRole, mayBuild, mayCreate, projectWritable, requireWritable, } from "../services/access.js";
34
38
  import { architectTurn } from "../services/architect.js";
39
+ import { addMessage, assistantLayout, currentChat, earlierChats, foldChat, newChat, openChat, readChat, turnHistory, } from "../services/assistant-chats.js";
35
40
  import { checkForCloud, cloudLinked, cloudSpaces, cloudState, forgetCloud, publishAndSync, pushSharing, removeFromCloud, replaceCloudSpaces, rotateInCloud, syncToCloud, } from "../services/cloud.js";
36
41
  import { notFound, ServiceError } from "../services/errors.js";
37
42
  import { deleteFile, listFiles, readFile, writeFile } from "../services/files.js";
@@ -223,6 +228,8 @@ export const studio = new Hono()
223
228
  }
224
229
  : null,
225
230
  models: managed ? null : localModelSettings(),
231
+ /** Apple Intelligence on this Mac: offered where the machine can run it (harness/apple.ts). */
232
+ apple: managed ? null : await appleStatus(),
226
233
  /** The AI clients this runtime can think with — installed or not, and how each is signed in. */
227
234
  harnesses: managed ? [] : await detectHarnesses(),
228
235
  /** Installed AI clients whose subscription can answer the studio chat. */
@@ -279,6 +286,118 @@ export const studio = new Hono()
279
286
  return c.json(await updateStatus());
280
287
  })
281
288
  .put("/profile", async (c) => c.json(await saveProfile(c.get("user"), profileSchema.parse(await c.req.json()))))
289
+ // --- the studio's assistant -------------------------------------------------
290
+ // One open chat per person and tenant, on every page; turns stream as SSE events shaped like
291
+ // AG-UI's (packages/shared/src/assistant.ts).
292
+ .get("/assistant/chat", async (c) => c.json(await currentChat(c.get("user"))))
293
+ .post("/assistant/chat/new", async (c) => c.json(await newChat(c.get("user"))))
294
+ .get("/assistant/chats", async (c) => c.json({ chats: await earlierChats(c.get("user")) }))
295
+ .get("/assistant/chats/:id", async (c) => c.json(await readChat(c.get("user"), c.req.param("id"))))
296
+ .get("/assistant/layout", async (c) => c.json({ layout: await assistantLayout(c.get("user")) }))
297
+ .put("/assistant/layout", async (c) => {
298
+ const { layout } = z.object({ layout: z.enum(ASSISTANT_LAYOUTS) }).parse(await c.req.json());
299
+ await writeSetting(`assistant-layout:${c.get("user").tenantId}:${c.get("user").id}`, layout);
300
+ return c.json({ layout });
301
+ })
302
+ // Live chat reads answers aloud with the speech model where one is set up; else the browser's voices.
303
+ .get("/assistant/voice", async (c) => c.json({ way: (await classWays()).speech.kind }))
304
+ .post("/assistant/speak", async (c) => {
305
+ const { text } = z.object({ text: z.string().min(1).max(4000) }).parse(await c.req.json());
306
+ if ((await classWays()).speech.kind === "none") {
307
+ throw new ServiceError("refused", "Hier spricht kein Sprachmodell.");
308
+ }
309
+ if (!(await canSpend())) {
310
+ throw new ServiceError("no_credits", "Dein Guthaben ist aufgebraucht.");
311
+ }
312
+ const voice = await generateSpeechMedia({ text, abortSignal: c.req.raw.signal });
313
+ return c.body(new Uint8Array(voice.bytes), 200, { "content-type": voice.mime });
314
+ })
315
+ // A browser tool's result: the turn that waits for it goes on.
316
+ .post("/assistant/tool/:callId", async (c) => {
317
+ const body = z.object({ result: z.unknown() }).parse(await c.req.json());
318
+ const taken = answerBrowser(c.get("user").id, c.req.param("callId"), body.result ?? null);
319
+ return c.json({ ok: taken }, taken ? 200 : 404);
320
+ })
321
+ .post("/assistant/turn", async (c) => {
322
+ const user = c.get("user");
323
+ const body = assistantTurnSchema
324
+ .extend({ lang: z.enum(["de", "en"]).default("de") })
325
+ .parse(await c.req.json());
326
+ if (!(await canSpend())) {
327
+ throw new ServiceError("no_credits", "Dein Guthaben ist aufgebraucht.");
328
+ }
329
+ const project = body.projectId ? await ownedProject(user.id, body.projectId) : null;
330
+ const writable = project ? await projectWritable(project) : false;
331
+ // The page's snapshot is cut, not refused: a page that says too much still gets an answer.
332
+ const page = body.page && JSON.stringify(body.page).length > ASSISTANT_PAGE_BYTES
333
+ ? { route: body.page.route, title: body.page.title, view: body.page.view }
334
+ : (body.page ?? null);
335
+ const chat = await openChat(user);
336
+ const history = await turnHistory(user, chat);
337
+ const runId = nanoid(10);
338
+ const userMessageId = await addMessage(chat.id, {
339
+ role: "user",
340
+ content: body.message,
341
+ page: page ? { route: page.route, title: page.title } : null,
342
+ });
343
+ return streamSSE(c, async (stream) => {
344
+ const abort = new AbortController();
345
+ stream.onAbort(() => abort.abort());
346
+ const send = (event, data) => stream.writeSSE({ event, data: JSON.stringify(data) });
347
+ const messageId = nanoid(14);
348
+ await send("run_started", { threadId: chat.id, runId, messageId: userMessageId });
349
+ let reply = "";
350
+ try {
351
+ const result = await runStudioAssistant({
352
+ user,
353
+ chat,
354
+ history,
355
+ project,
356
+ writable,
357
+ message: body.message,
358
+ page,
359
+ browserTools: body.tools,
360
+ lang: body.lang,
361
+ signal: abort.signal,
362
+ onText: (delta) => {
363
+ reply += delta;
364
+ void send("text", { messageId, delta });
365
+ },
366
+ onActivity: (label) => void send("activity", { label }),
367
+ onChanged: () => void send("changed", {}),
368
+ onCard: (card) => void send("card", card),
369
+ onToolCall: (call) => void send("tool_call", call),
370
+ onToolResult: (result) => void send("tool_result", result),
371
+ callBrowser: (call) => awaitBrowser(user.id, call.toolCallId, abort.signal),
372
+ });
373
+ reply =
374
+ result.reply || (result.changed ? (body.lang === "de" ? "Erledigt." : "Done.") : "");
375
+ const stored = await addMessage(chat.id, {
376
+ role: "assistant",
377
+ content: reply,
378
+ cards: result.cards,
379
+ toolCalls: result.toolCalls,
380
+ changed: result.changed,
381
+ });
382
+ await send("done", { messageId: stored, reply, changed: result.changed });
383
+ }
384
+ catch (err) {
385
+ console.error("[studio-assistant]", err);
386
+ if (reply.trim()) {
387
+ await addMessage(chat.id, { role: "assistant", content: reply.trim() }).catch(() => null);
388
+ }
389
+ await send("error", {
390
+ message: err instanceof ServiceError || err instanceof ModelUnavailableError
391
+ ? err.message
392
+ : body.lang === "de"
393
+ ? "Da ist etwas schiefgelaufen. Bitte noch einmal versuchen."
394
+ : "Something went wrong. Please try again.",
395
+ });
396
+ }
397
+ // Older messages fold into the chat's running summary once enough have piled up.
398
+ void foldChat(chat.id).catch((err) => console.error("[studio-assistant] fold:", err));
399
+ });
400
+ })
282
401
  // --- projects --------------------------------------------------------------
283
402
  .get("/projects", async (c) => {
284
403
  const projects = await listProjects(c.get("user").id);
@@ -398,71 +517,6 @@ export const studio = new Hono()
398
517
  .object({ query: z.string().min(1).max(400), where: whereSchema.optional() })
399
518
  .parse(await c.req.json());
400
519
  return c.json(await searchKnowledge(project.id, body.query, { where: body.where }));
401
- })
402
- // The assistant fills the project in: from a description, a website, the files given.
403
- .post("/projects/:id/assist", async (c) => {
404
- const user = c.get("user");
405
- const project = await ownedProject(user.id, c.req.param("id"));
406
- await requireWritable(project);
407
- const body = z
408
- .object({
409
- message: z.string().min(1).max(8000),
410
- history: z
411
- .array(z.object({ role: z.enum(["user", "assistant"]), content: z.string().max(8000) }))
412
- .max(24)
413
- .default([]),
414
- part: z.enum(["info", "knowledge"]).default("info"),
415
- plugin: z.string().regex(PLUGIN_ID).optional(),
416
- })
417
- .parse(await c.req.json());
418
- if (!(await canSpend())) {
419
- throw new ServiceError("no_credits", "Dein Guthaben ist aufgebraucht.");
420
- }
421
- return streamSSE(c, async (stream) => {
422
- const abort = new AbortController();
423
- stream.onAbort(() => abort.abort());
424
- try {
425
- const result = await runProjectAssistant({
426
- userId: user.id,
427
- projectId: project.id,
428
- message: body.message,
429
- history: body.history,
430
- part: body.part,
431
- plugin: body.plugin,
432
- signal: abort.signal,
433
- onText: (delta) => {
434
- void stream.writeSSE({ event: "text", data: JSON.stringify(delta) });
435
- },
436
- onActivity: (label) => {
437
- void stream.writeSSE({ event: "activity", data: JSON.stringify(label) });
438
- },
439
- onChanged: () => {
440
- void stream.writeSSE({ event: "changed", data: "1" });
441
- },
442
- onCard: (card) => {
443
- void stream.writeSSE({ event: "card", data: JSON.stringify(card) });
444
- },
445
- });
446
- await stream.writeSSE({
447
- event: "done",
448
- data: JSON.stringify({
449
- reply: result.reply || (result.changed ? "Erledigt." : ""),
450
- changed: result.changed,
451
- }),
452
- });
453
- }
454
- catch (err) {
455
- console.error("[project-assistant]", err);
456
- await stream.writeSSE({
457
- event: "error",
458
- data: JSON.stringify({
459
- message: err instanceof ServiceError || err instanceof ModelUnavailableError
460
- ? err.message
461
- : "Da ist etwas schiefgelaufen. Bitte noch einmal versuchen.",
462
- }),
463
- });
464
- }
465
- });
466
520
  })
467
521
  .delete("/projects/:id", async (c) => {
468
522
  await deleteProject(c.get("user").id, c.req.param("id"));
@@ -751,7 +805,14 @@ export const studio = new Hono()
751
805
  return c.json(await importWizard(c.get("user").id, c.req.param("id"), new Uint8Array(await file.arrayBuffer()), file.name));
752
806
  })
753
807
  .get("/wizards/:id/export", async (c) => {
754
- const { name, zip } = await exportWizard(c.get("user").id, c.req.param("id"));
808
+ const found = await exportWizard(c.get("user").id, c.req.param("id"), {
809
+ published: c.req.query("published") === "1",
810
+ knowledge: c.req.query("knowledge") === "1",
811
+ });
812
+ if (!found) {
813
+ return c.json({ error: "Der Wizard ist noch nicht veröffentlicht." }, 404);
814
+ }
815
+ const { name, zip } = found;
755
816
  return c.body(new Uint8Array(zip), 200, {
756
817
  "content-type": PACKAGE_MIME,
757
818
  "content-disposition": `attachment; filename="${name}"`,