@engenty/wizards-runtime 0.9.8 → 0.11.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 (102) hide show
  1. package/apps/runtime/dist/app.js +34 -1
  2. package/apps/runtime/dist/auth/index.js +10 -1
  3. package/apps/runtime/dist/db/client.js +9 -1
  4. package/apps/runtime/dist/db/live-triggers.js +144 -0
  5. package/apps/runtime/dist/db/migrations/tenant/0022_sync.sql +247 -0
  6. package/apps/runtime/dist/db/migrations/tenant/0023_live_change.sql +167 -0
  7. package/apps/runtime/dist/db/migrations/tenant/0024_live_presence.sql +28 -0
  8. package/apps/runtime/dist/db/migrations/tenant/meta/0022_snapshot.json +3792 -0
  9. package/apps/runtime/dist/db/migrations/tenant/meta/0023_snapshot.json +3860 -0
  10. package/apps/runtime/dist/db/migrations/tenant/meta/0024_snapshot.json +3967 -0
  11. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +21 -0
  12. package/apps/runtime/dist/db/schema.js +101 -0
  13. package/apps/runtime/dist/docs/user-guide/cloud-sync.md +85 -0
  14. package/apps/runtime/dist/docs/user-guide/data.md +4 -4
  15. package/apps/runtime/dist/docs/user-guide/meta.json +2 -0
  16. package/apps/runtime/dist/docs/user-guide/test-and-share.md +4 -14
  17. package/apps/runtime/dist/docs/user-guide/together.md +60 -0
  18. package/apps/runtime/dist/files/blobs.js +13 -0
  19. package/apps/runtime/dist/index.js +11 -1
  20. package/apps/runtime/dist/live/feed.js +34 -0
  21. package/apps/runtime/dist/live/hub.js +200 -0
  22. package/apps/runtime/dist/live/origin.js +53 -0
  23. package/apps/runtime/dist/live/views.js +146 -0
  24. package/apps/runtime/dist/mcp/handler.js +7 -1
  25. package/apps/runtime/dist/mcp/tools.js +51 -2
  26. package/apps/runtime/dist/plugins/jobs.js +7 -0
  27. package/apps/runtime/dist/routes/api.js +177 -1
  28. package/apps/runtime/dist/routes/live.js +85 -0
  29. package/apps/runtime/dist/routes/studio.js +109 -85
  30. package/apps/runtime/dist/services/cloud.js +39 -5
  31. package/apps/runtime/dist/services/presence.js +132 -0
  32. package/apps/runtime/dist/services/projects.js +11 -0
  33. package/apps/runtime/dist/services/space-data.js +33 -6
  34. package/apps/runtime/dist/sync/apply.js +43 -0
  35. package/apps/runtime/dist/sync/client.js +973 -0
  36. package/apps/runtime/dist/sync/hub.js +324 -0
  37. package/apps/runtime/dist/sync/log.js +74 -0
  38. package/apps/runtime/dist/sync/records.js +943 -0
  39. package/apps/runtime/dist/sync/state.js +17 -0
  40. package/apps/runtime/dist/texts.js +2 -0
  41. package/apps/web/dist/assets/AboutDialog-9VcgySrQ.js +1 -0
  42. package/apps/web/dist/assets/{ChangelogDialog-BpEIbAZ8.js → ChangelogDialog-BXvT2VMU.js} +1 -1
  43. package/apps/web/dist/assets/EditorPage-Cvzd0nah.js +4 -0
  44. package/apps/web/dist/assets/{FlowPreview-APXdRflR.js → FlowPreview-BV1NJ0rF.js} +1 -1
  45. package/apps/web/dist/assets/{Harness-BsGXMlLg.js → Harness-DYviBlHB.js} +2 -2
  46. package/apps/web/dist/assets/Marketplace-DTSg7_U7.js +2 -0
  47. package/apps/web/dist/assets/{NewWizardChannels-0JrRdUFd.js → NewWizardChannels-DiujJzOR.js} +1 -1
  48. package/apps/web/dist/assets/NewWizardPage-CngUh9g-.js +7 -0
  49. package/apps/web/dist/assets/OnboardingPage-DFKJnWtw.js +1 -0
  50. package/apps/web/dist/assets/PreviewPane-C0E9OLzB.js +9 -0
  51. package/apps/web/dist/assets/ProjectPage-CYDX-JYc.js +1 -0
  52. package/apps/web/dist/assets/PublicRunner-CkRO_Pw-.js +1 -0
  53. package/apps/web/dist/assets/{ReadOnly-BraZbEG_.js → ReadOnly-E-h9y_QO.js} +1 -1
  54. package/apps/web/dist/assets/SettingsPage-BMgP3aRV.js +2 -0
  55. package/apps/web/dist/assets/SetupPage-DBO_rzj7.js +1 -0
  56. package/apps/web/dist/assets/{SharePage-Dk7zC5Zo.js → SharePage-BvvmYB5N.js} +1 -1
  57. package/apps/web/dist/assets/changelog-zllICQ4q.js +1 -0
  58. package/apps/web/dist/assets/{coins-391m1e4_.js → coins-DQ91VJAB.js} +1 -1
  59. package/apps/web/dist/assets/index-Bjn557f1.js +20 -0
  60. package/apps/web/dist/assets/index-DN0VMwsS.css +1 -0
  61. package/apps/web/dist/assets/{phone-DvgrtyNO.js → phone-jIuRIwyg.js} +1 -1
  62. package/apps/web/dist/assets/{runners-4OBelIgF.js → runners-DloOxEbh.js} +1 -1
  63. package/apps/web/dist/assets/session-BpsCkDv6.js +2 -0
  64. package/apps/web/dist/assets/{settings-menu-xK9A-gaP.js → settings-menu-CoLUNJGQ.js} +1 -1
  65. package/apps/web/dist/assets/theme-2XjIQXH3.js +11 -0
  66. package/apps/web/dist/assets/{ui-BVQk2DtW.js → ui-BIWmkPh6.js} +3 -3
  67. package/apps/web/dist/assets/{upload-BgXbzG6C.js → upload-BcOvBWHS.js} +1 -1
  68. package/apps/web/dist/assets/{useMutation-DkwSQWoD.js → useMutation-CD7HmAxR.js} +1 -1
  69. package/apps/web/dist/assets/{volume-2-DHGoe3Cg.js → volume-2-D2To9w5D.js} +1 -1
  70. package/apps/web/dist/assets/{wrench-Cf_aE3O0.js → wrench-B98ubRvB.js} +1 -1
  71. package/apps/web/dist/index.html +8 -8
  72. package/apps/web/dist/mcp/flow.html +2 -2
  73. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
  74. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
  75. package/node_modules/@engenty/wizards-shared/dist/live.d.ts +46 -0
  76. package/node_modules/@engenty/wizards-shared/dist/live.js +9 -0
  77. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +7 -0
  78. package/node_modules/@engenty/wizards-shared/dist/run.js +14 -0
  79. package/node_modules/@engenty/wizards-shared/dist/sync-merge.d.ts +55 -0
  80. package/node_modules/@engenty/wizards-shared/dist/sync-merge.js +214 -0
  81. package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +166 -0
  82. package/node_modules/@engenty/wizards-shared/dist/sync.js +40 -0
  83. package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +14 -0
  84. package/node_modules/@engenty/wizards-shared/dist/text-merge.js +137 -0
  85. package/package.json +1 -1
  86. package/plugin/.claude-plugin/plugin.json +1 -1
  87. package/plugin/plugin.json +1 -1
  88. package/apps/web/dist/assets/AboutDialog-B_Ixp_Tb.js +0 -1
  89. package/apps/web/dist/assets/EditorPage-CKHY4hn4.js +0 -4
  90. package/apps/web/dist/assets/Marketplace-Dr-Qnb-F.js +0 -2
  91. package/apps/web/dist/assets/NewWizardPage-9igFL5O8.js +0 -7
  92. package/apps/web/dist/assets/OnboardingPage-BcK9FUnU.js +0 -1
  93. package/apps/web/dist/assets/PreviewPane-X4LBqA0D.js +0 -4
  94. package/apps/web/dist/assets/ProjectPage-CG0i-KhR.js +0 -1
  95. package/apps/web/dist/assets/PublicRunner-CZR1ziQ4.js +0 -1
  96. package/apps/web/dist/assets/SettingsPage-Bw4tdoV7.js +0 -2
  97. package/apps/web/dist/assets/SetupPage-CvkE2aKx.js +0 -1
  98. package/apps/web/dist/assets/changelog-DDXnAaHm.js +0 -1
  99. package/apps/web/dist/assets/index-BTUtot4r.js +0 -14
  100. package/apps/web/dist/assets/index-DcUL6teA.css +0 -1
  101. package/apps/web/dist/assets/session-DvnGHbDz.js +0 -2
  102. package/apps/web/dist/assets/theme-D3yDT4QT.js +0 -11
@@ -1,12 +1,12 @@
1
1
  import { mkdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { ASSISTANT_LAYOUTS, ASSISTANT_PAGE_BYTES, ASSISTANT_WIDTH, assistantSignalSchema, assistantTurnSchema, } from "@engenty/wizards-shared/assistant";
4
- import { LANGS, MODEL_CLASSES, TEXT_CLASSES, wizardLang, } from "@engenty/wizards-shared/definition";
4
+ import { LANGS, MODEL_CLASSES, TEXT_CLASSES, } from "@engenty/wizards-shared/definition";
5
5
  import { CATEGORY_TYPES, whereSchema } from "@engenty/wizards-shared/knowledge";
6
+ import { PRESENCE_KINDS } from "@engenty/wizards-shared/live";
6
7
  import { PROJECT_FILE_KINDS } from "@engenty/wizards-shared/projects";
7
8
  import { CLASS_NAMES, isCreditsRef, modelLabel } from "@engenty/wizards-shared/providers";
8
9
  import { note } from "@engenty/wizards-shared/run";
9
- import { wizardTexts } from "@engenty/wizards-shared/translation";
10
10
  import { PACKAGE_EXTENSION, PACKAGE_MAX_BYTES, PACKAGE_MIME, } from "@engenty/wizards-shared/wizard-package";
11
11
  import { generateText } from "ai";
12
12
  import { Hono } from "hono";
@@ -22,7 +22,7 @@ import { accountOverview, linkedAccount, startLink, unlink } from "../auth/accou
22
22
  import { createLocalKey, deleteLocalKey, listLocalKeys } from "../auth/keys.js";
23
23
  import { appStates, connectApps } from "../cli/connect.js";
24
24
  import { layout } from "../cli/home.js";
25
- import { connectorImportSchema, importConnector, listConnectors, previewSource, refreshConnector, registryService, removeConnector, searchRegistry, } from "../connectors/external.js";
25
+ import { connectorImportSchema, importConnector, previewSource, refreshConnector, registryService, removeConnector, searchRegistry, } from "../connectors/external.js";
26
26
  import { balanceCredits, canSpend } from "../credits/credits.js";
27
27
  import { estimateRun } from "../credits/estimate.js";
28
28
  import { missingModels, stepsWithoutModel } from "../engine/requirements.js";
@@ -32,12 +32,13 @@ import { appleStatus } from "../harness/apple.js";
32
32
  import { freshAuth, loginEnv } from "../harness/env.js";
33
33
  import { detectHarness, detectHarnesses, HARNESS_IDS, harness, installSpec, } from "../harness/index.js";
34
34
  import { closeTerminal, openTerminal, resizeTerminal, subscribeTerminal, writeTerminal, } from "../harness/terminal.js";
35
+ import { connectorsView, filesView, spacesView, translationsView, wizardsView, wizardView, } from "../live/views.js";
35
36
  import { installMail, managed, renameTenant, saveOrganizationProfile, tenantInfo, tenantMembers, userInfo, } from "../manage.js";
36
37
  import { seenApps } from "../mcp/seen.js";
37
38
  import { generateImageMedia, generateSpeechMedia, generateVideoMedia } from "../media/generate.js";
38
39
  import { transcribeAudio } from "../media/transcribe.js";
39
40
  import { errorText, saidOf } from "../model-errors.js";
40
- import { blockedBinding, CHAT_WAYS, checkKey, classProblem, classWays, embeddingModel, hasTextModel, LOCAL_KEYS, localModelSettings, ModelUnavailableError, modelSettings, saveLocalModels, saveModels, setUpKey, setUpOllama, storedKey, textModel, } from "../models.js";
41
+ import { blockedBinding, CHAT_WAYS, checkKey, classProblem, classWays, hasTextModel, LOCAL_KEYS, localModelSettings, ModelUnavailableError, modelSettings, saveLocalModels, saveModels, setUpKey, setUpOllama, storedKey, textModel, } from "../models.js";
41
42
  import { refreshPro } from "../plugins/pro.js";
42
43
  import { HTML_RESPONSE_CSP } from "../render/guard.js";
43
44
  import { isAdminRole, mayBuild, mayCreate, projectWritable, requireAdmin, requireWritable, } from "../services/access.js";
@@ -52,26 +53,38 @@ import { writeSummary } from "../services/knowledge-model.js";
52
53
  import { applyWebsite, finishOnboarding, needsOnboarding } from "../services/onboarding.js";
53
54
  import { exportWizard, importWizard } from "../services/package.js";
54
55
  import { pagePreview } from "../services/pages.js";
56
+ import { asAssistantIn, leave, markPresent, presentByItem, presentIn, } from "../services/presence.js";
55
57
  import { profileSchema, saveProfile, saveUserLang, userLang, userProfile, } from "../services/profile.js";
56
- import { addProjectFile, addProjectFileFromUrl, fileView, orderProjectFiles, projectFile, projectFileContent, projectFiles, reindexProjectFile, removeProjectFile, updateProjectFile, } from "../services/project-files.js";
58
+ import { addProjectFile, addProjectFileFromUrl, fileView, orderProjectFiles, projectFile, projectFileContent, reindexProjectFile, removeProjectFile, updateProjectFile, } from "../services/project-files.js";
57
59
  import { documentText, queueIndex, searchKnowledge } from "../services/project-index.js";
58
- import { createProject, deleteProject, gradientSchema, listProjects, maskedServers, ownedProject, projectLimitOrNull, projectPatchSchema, updateProject, } from "../services/projects.js";
60
+ import { createProject, deleteProject, gradientSchema, ownedProject, projectLimitOrNull, projectPatchSchema, updateProject, } from "../services/projects.js";
59
61
  import { runnersOf, wizardRunners } from "../services/runners.js";
60
62
  import { draftStepView, listResults, listRuns, startTestRun } from "../services/runs.js";
61
63
  import { addCategoryValue, categoryRow, categoryValue, deleteCategory, deleteCategoryValue, mergeCategoryValues, orderCategoryValues, putCategory, renameCategoryValue, setItemCategory, updateCategory, } from "../services/space-categories.js";
62
64
  import { addTableRow, createPage, createTable, deletePage, deleteTable, deleteTableRows, getPage, getTable, listSpaceData, orderSubPages, updatePage, updateTable, updateTableRow, } from "../services/space-data.js";
63
65
  import { deleteTheme, listThemes, saveTheme } from "../services/themes.js";
64
- import { deleteTranslation, editTranslation, isLangCode, publishedDefinition, translationsOf, } from "../services/translations.js";
66
+ import { deleteTranslation, editTranslation, isLangCode, publishedDefinition, } from "../services/translations.js";
65
67
  import { draftWidgetPreview } from "../services/widgets.js";
66
- import { createWizard, deleteWizard, draftChanges, duplicateWizard, listWizards, ownedWizard, rotateShareLink, updateWizardSettings, wizardMessages, wizardState, writableWizard, writeDraft, } from "../services/wizards.js";
68
+ import { createWizard, deleteWizard, draftChanges, duplicateWizard, ownedWizard, rotateShareLink, updateWizardSettings, writableWizard, writeDraft, } from "../services/wizards.js";
67
69
  import { deleteSetting, readSetting, writeSetting } from "../settings.js";
68
70
  import { projectShareTargets, sharePreview } from "../sharing/index.js";
71
+ import { keepCloudForAll, mergesSeen, proposeMerge, resolveConflict, startSpace, stopSpace, syncAll, syncView, undoMerge, } from "../sync/client.js";
69
72
  import { codeOf } from "../tenants/control.js";
70
73
  import { currentTenant } from "../tenants/tenant.js";
71
74
  import { serverText } from "../texts.js";
72
75
  import { applyUpdate, updateStatus } from "../update.js";
73
76
  import { bareMime, byteRange } from "./delivery.js";
74
77
  import { notFoundAnswer, requestLang, say } from "./lang.js";
78
+ const presenceSchema = z.object({
79
+ kind: z.enum(PRESENCE_KINDS),
80
+ item: z.string().min(1).max(100),
81
+ tab: z.string().max(40),
82
+ state: z.enum(["viewing", "editing"]),
83
+ place: z.string().max(200).nullish(),
84
+ placeLabel: z.string().max(120).nullish(),
85
+ });
86
+ /** Who reads, for the views the live stream sends too (live/views.ts). */
87
+ const reader = (c) => ({ userId: c.get("user").id, lang: requestLang(c) });
75
88
  /** The model sources a test call has worked on: the setup is done for those, not for the others. */
76
89
  async function testedSources() {
77
90
  const tested = await readSetting("setup-done");
@@ -216,6 +229,18 @@ const terminalSize = z.object({
216
229
  cols: z.number().int().min(10).max(500).optional(),
217
230
  rows: z.number().int().min(4).max(200).optional(),
218
231
  });
232
+ /** How the person settled a conflict: one side, a choice per place, or a version of their own. */
233
+ const resolutionSchema = z.union([
234
+ z.object({ take: z.enum(["local", "remote"]) }),
235
+ z.object({
236
+ choices: z.array(z.union([
237
+ z.object({ take: z.enum(["local", "remote"]) }),
238
+ z.object({ value: z.unknown() }),
239
+ z.null(),
240
+ ])),
241
+ }),
242
+ z.object({ record: z.record(z.string(), z.unknown()) }),
243
+ ]);
219
244
  export const studio = new Hono()
220
245
  .get("/me", async (c) => {
221
246
  const user = c.get("user");
@@ -532,24 +557,7 @@ export const studio = new Hono()
532
557
  });
533
558
  })
534
559
  // --- projects --------------------------------------------------------------
535
- .get("/projects", async (c) => {
536
- const projects = await listProjects(c.get("user").id, requestLang(c));
537
- const build = await mayBuild();
538
- return c.json(projects.map((p) => ({
539
- id: p.id,
540
- name: p.name,
541
- brand: p.brand,
542
- facts: p.facts,
543
- /** The space's public page; null until it is set up. */
544
- page: p.page ?? null,
545
- mcpServers: maskedServers(p),
546
- wizardCount: p.wizardCount,
547
- /** `local`: synced from a local install, where it is changed. */
548
- origin: p.origin,
549
- syncedAt: p.syncedAt?.toISOString() ?? null,
550
- readOnly: p.origin === "local" || !build,
551
- })));
552
- })
560
+ .get("/projects", async (c) => c.json(await spacesView(reader(c))))
553
561
  .post("/projects", async (c) => {
554
562
  const body = z.object({ name: z.string().min(1).max(80) }).parse(await c.req.json());
555
563
  return c.json(await createProject(c.get("user").id, body.name));
@@ -572,14 +580,7 @@ export const studio = new Hono()
572
580
  return c.json({ ok: true });
573
581
  })
574
582
  // --- what a project holds for all its wizards: logos, assets, documents -------
575
- .get("/projects/:id/files", async (c) => {
576
- const project = await ownedProject(c.get("user").id, c.req.param("id"));
577
- return c.json({
578
- files: (await projectFiles(project.id)).map(fileView),
579
- /** Whether documents get vectors, or the index works on keywords alone. */
580
- embeddings: Boolean(await embeddingModel().catch(() => null)),
581
- });
582
- })
583
+ .get("/projects/:id/files", async (c) => c.json(await filesView(reader(c), c.req.param("id"))))
583
584
  .post("/projects/:id/files", async (c) => {
584
585
  const project = await ownedProject(c.get("user").id, c.req.param("id"));
585
586
  const kind = z.enum(PROJECT_FILE_KINDS).parse(c.req.query("kind"));
@@ -746,10 +747,7 @@ export const studio = new Hono()
746
747
  .parse(await c.req.json());
747
748
  return c.json(await previewSource(body));
748
749
  })
749
- .get("/projects/:id/connectors", async (c) => {
750
- const project = await ownedProject(c.get("user").id, c.req.param("id"));
751
- return c.json(await listConnectors(project.id));
752
- })
750
+ .get("/projects/:id/connectors", async (c) => c.json(await connectorsView(reader(c), c.req.param("id"))))
753
751
  .post("/projects/:id/connectors", async (c) => {
754
752
  const user = c.get("user");
755
753
  const project = await ownedProject(user.id, c.req.param("id"));
@@ -970,10 +968,10 @@ export const studio = new Hono()
970
968
  parentId: z.string().nullish(),
971
969
  markdown: z.string().optional(),
972
970
  review: z.null().optional(),
971
+ baseUpdatedAt: z.string().max(40).optional(),
973
972
  })
974
973
  .parse(await c.req.json());
975
- await updatePage(c.get("user").id, c.req.param("id"), body);
976
- return c.json({ ok: true });
974
+ return c.json({ ok: true, ...(await updatePage(c.get("user").id, c.req.param("id"), body)) });
977
975
  })
978
976
  .put("/pages/:id/order", async (c) => {
979
977
  const { ids } = z.object({ ids: z.array(z.string()).max(5000) }).parse(await c.req.json());
@@ -985,14 +983,7 @@ export const studio = new Hono()
985
983
  return c.json({ ok: true });
986
984
  })
987
985
  // --- wizards ---------------------------------------------------------------
988
- .get("/projects/:id/wizards", async (c) => {
989
- const user = c.get("user");
990
- await ownedProject(user.id, c.req.param("id"));
991
- const wizards = await listWizards(user.id, c.req.param("id"));
992
- // A local install with an account: where each wizard stands in its cloud, for the cards.
993
- const linked = await cloudLinked();
994
- return c.json(await Promise.all(wizards.map(async (w) => ({ ...w, cloud: linked ? await cloudState(w.id) : null }))));
995
- })
986
+ .get("/projects/:id/wizards", async (c) => c.json(await wizardsView(reader(c), c.req.param("id"))))
996
987
  .post("/wizards", async (c) => {
997
988
  const body = z
998
989
  .object({
@@ -1040,27 +1031,7 @@ export const studio = new Hono()
1040
1031
  const w = await ownedWizard(user.id, c.req.param("id"));
1041
1032
  return c.json(await sharePreview(w, user.id, c.req.query("step") || null, c.req.query("as") === "owner", requestLang(c)));
1042
1033
  })
1043
- .get("/wizards/:id", async (c) => {
1044
- const user = c.get("user");
1045
- const w = await ownedWizard(user.id, c.req.param("id"));
1046
- const messages = await wizardMessages(w.id);
1047
- const project = await ownedProject(user.id, w.projectId);
1048
- return c.json({
1049
- ...(await wizardState(w)),
1050
- /** Shown and run here, changed elsewhere: a local install's wizard, or nothing is built here. */
1051
- readOnly: !(await projectWritable(project)),
1052
- blank: messages.length === 0 && !w.starter,
1053
- messages: messages.map((m) => ({
1054
- id: m.id,
1055
- role: m.role,
1056
- content: m.content,
1057
- changed: m.changed,
1058
- source: m.source,
1059
- client: m.client,
1060
- })),
1061
- mcpServers: project.mcpServers.map((s) => ({ id: s.id, name: s.name })),
1062
- });
1063
- })
1034
+ .get("/wizards/:id", async (c) => c.json(await wizardView(reader(c), c.req.param("id"))))
1064
1035
  .put("/wizards/:id/draft", async (c) => {
1065
1036
  const body = z
1066
1037
  .object({ definition: z.unknown(), baseRevision: z.number().int().min(0) })
@@ -1089,20 +1060,7 @@ export const studio = new Hono()
1089
1060
  return c.json({ ok: true });
1090
1061
  })
1091
1062
  // The languages the published wizard is kept in, each original text with its translation.
1092
- .get("/wizards/:id/translations", async (c) => {
1093
- const w = await ownedWizard(c.get("user").id, c.req.param("id"));
1094
- const def = await publishedDefinition(w);
1095
- const kept = await translationsOf(w.id);
1096
- return c.json({
1097
- lang: def ? wizardLang(def) : wizardLang(w.draft),
1098
- texts: def ? wizardTexts(def) : [],
1099
- translations: kept.map((t) => ({
1100
- lang: t.lang,
1101
- texts: t.texts,
1102
- updatedAt: t.updatedAt.toISOString(),
1103
- })),
1104
- });
1105
- })
1063
+ .get("/wizards/:id/translations", async (c) => c.json(await translationsView(reader(c), c.req.param("id"))))
1106
1064
  // The author's own lines for a language: they replace what a model wrote.
1107
1065
  .put("/wizards/:id/translations/:lang", async (c) => {
1108
1066
  const w = await writableWizard(c.get("user").id, c.req.param("id"));
@@ -1195,6 +1153,72 @@ export const studio = new Hono()
1195
1153
  return c.notFound();
1196
1154
  }
1197
1155
  return c.json(await checkForCloud(c.get("user").id, c.req.param("id")));
1156
+ })
1157
+ // --- the two-way sync of the spaces with the account's organization (sync/client.ts) ---
1158
+ // --- who is in a wizard, page or table: a signal, never a lock (docs/plans/live-changes.md, 8) ---
1159
+ .get("/presence/:kind", async (c) => c.json(await presentByItem(z.enum(PRESENCE_KINDS).parse(c.req.param("kind")))))
1160
+ .get("/presence/:kind/:item", async (c) => c.json(await presentIn(z.enum(PRESENCE_KINDS).parse(c.req.param("kind")), c.req.param("item"))))
1161
+ .put("/presence", async (c) => {
1162
+ const user = c.get("user");
1163
+ const body = presenceSchema.parse(await c.req.json());
1164
+ await markPresent({ ...body, who: user.id, whoKind: "person", name: user.name });
1165
+ return c.json({ ok: true });
1166
+ })
1167
+ // `navigator.sendBeacon` posts when a tab closes.
1168
+ .post("/presence/leave", async (c) => {
1169
+ const body = presenceSchema
1170
+ .pick({ kind: true, item: true, tab: true })
1171
+ .parse(JSON.parse(await c.req.text()));
1172
+ await leave(body.kind, body.item, c.get("user").id, body.tab);
1173
+ return c.json({ ok: true });
1174
+ })
1175
+ .get("/sync", async (c) => (managed ? c.notFound() : c.json(await syncView())))
1176
+ .post("/sync/now", async (c) => {
1177
+ if (managed) {
1178
+ return c.notFound();
1179
+ }
1180
+ await syncAll();
1181
+ return c.json(await syncView());
1182
+ })
1183
+ .put("/sync/spaces/:id", async (c) => {
1184
+ if (managed) {
1185
+ return c.notFound();
1186
+ }
1187
+ const { on } = z.object({ on: z.boolean() }).parse(await c.req.json());
1188
+ await (on ? startSpace(c.req.param("id")) : stopSpace(c.req.param("id")));
1189
+ return c.json(await syncView());
1190
+ })
1191
+ .post("/sync/spaces/:id/keep-cloud", async (c) => {
1192
+ if (managed) {
1193
+ return c.notFound();
1194
+ }
1195
+ await keepCloudForAll(c.req.param("id"));
1196
+ return c.json(await syncView());
1197
+ })
1198
+ .post("/sync/conflicts/:id/resolve", async (c) => {
1199
+ if (managed) {
1200
+ return c.notFound();
1201
+ }
1202
+ const body = resolutionSchema.parse(await c.req.json());
1203
+ await resolveConflict(c.req.param("id"), body);
1204
+ return c.json(await syncView());
1205
+ })
1206
+ .post("/sync/conflicts/:id/propose", async (c) => managed ? c.notFound() : c.json(await proposeMerge(c.req.param("id"))))
1207
+ .post("/sync/merges/:id/undo", async (c) => {
1208
+ if (managed) {
1209
+ return c.notFound();
1210
+ }
1211
+ const { take } = z.object({ take: z.enum(["local", "remote"]) }).parse(await c.req.json());
1212
+ await undoMerge(c.req.param("id"), take);
1213
+ return c.json(await syncView());
1214
+ })
1215
+ .post("/sync/merges/seen", async (c) => {
1216
+ if (managed) {
1217
+ return c.notFound();
1218
+ }
1219
+ const { ids } = z.object({ ids: z.array(z.string()).max(200) }).parse(await c.req.json());
1220
+ await mergesSeen(ids);
1221
+ return c.json({ ok: true });
1198
1222
  })
1199
1223
  // The projects of local installs the account's cloud holds.
1200
1224
  .get("/cloud/spaces", async (c) => {
@@ -1224,7 +1248,7 @@ export const studio = new Hono()
1224
1248
  const abort = new AbortController();
1225
1249
  stream.onAbort(() => abort.abort());
1226
1250
  try {
1227
- const result = await architectTurn(user.id, wizardId, message, requestLang(c), {
1251
+ const result = await asAssistantIn(wizardId, user, () => architectTurn(user.id, wizardId, message, requestLang(c), {
1228
1252
  signal: abort.signal,
1229
1253
  onText: (delta) => {
1230
1254
  void stream.writeSSE({ event: "text", data: JSON.stringify(delta) });
@@ -1238,7 +1262,7 @@ export const studio = new Hono()
1238
1262
  onBuilding: () => {
1239
1263
  void stream.writeSSE({ event: "building", data: "1" });
1240
1264
  },
1241
- });
1265
+ }));
1242
1266
  await stream.writeSSE({ event: "done", data: JSON.stringify(result) });
1243
1267
  }
1244
1268
  catch (err) {
@@ -7,6 +7,7 @@ import { env } from "../env.js";
7
7
  import { getBlob } from "../files/blobs.js";
8
8
  import { managed } from "../manage.js";
9
9
  import { deleteSetting, readSetting, writeSetting } from "../settings.js";
10
+ import { forgetTwoWay, publishInCloud, rotateInCloudSpace, spaceSyncs } from "../sync/client.js";
10
11
  import { currentTenant } from "../tenants/tenant.js";
11
12
  import { mainLogoId } from "./brand.js";
12
13
  import { ServiceError } from "./errors.js";
@@ -218,7 +219,26 @@ export async function syncToCloud(userId, wizardId) {
218
219
  throw new ServiceError("refused", note("publishWizardFirst"));
219
220
  }
220
221
  const before = await cloudState(w.id);
222
+ const twoWay = await spaceSyncs(w.projectId);
221
223
  try {
224
+ if (twoWay) {
225
+ // The space syncs both ways: its draft goes up with the space, then the cloud publishes it.
226
+ const published = await publishInCloud(w.projectId, w.id);
227
+ const state = {
228
+ copy: {
229
+ shareUrl: published.shareUrl,
230
+ code: published.code,
231
+ version: version.version,
232
+ publishedVersion: published.publishedVersion,
233
+ runnable: true,
234
+ problems: [],
235
+ syncedAt: new Date().toISOString(),
236
+ },
237
+ error: null,
238
+ };
239
+ await writeSetting(key(w.id), state);
240
+ return state;
241
+ }
222
242
  const files = await Promise.all(version.files.map(async (f) => ({
223
243
  path: f.path,
224
244
  mime: f.mime,
@@ -286,6 +306,11 @@ export async function pushSharing(userId, wizardId) {
286
306
  if (!(await cloudLinked())) {
287
307
  return;
288
308
  }
309
+ // A space that syncs both ways takes the settings along with the wizard.
310
+ const own = await ownedWizard(userId, wizardId).catch(() => null);
311
+ if (own && (await spaceSyncs(own.projectId))) {
312
+ return;
313
+ }
289
314
  const state = await cloudState(wizardId);
290
315
  if (!state.copy) {
291
316
  return;
@@ -311,13 +336,20 @@ export async function rotateInCloud(userId, wizardId) {
311
336
  return state;
312
337
  }
313
338
  const w = await ownedWizard(userId, wizardId);
314
- const answer = await call("POST", `/spaces/${w.projectId}/wizards/${w.id}/rotate-link`);
315
- if (!answer.ok || !answer.body.shareUrl) {
316
- throw refusal(answer, "The link in the cloud could not be renewed.");
339
+ let link;
340
+ if (await spaceSyncs(w.projectId)) {
341
+ link = await rotateInCloudSpace(w.projectId, w.id);
342
+ }
343
+ else {
344
+ const answer = await call("POST", `/spaces/${w.projectId}/wizards/${w.id}/rotate-link`);
345
+ if (!answer.ok || !answer.body.shareUrl) {
346
+ throw refusal(answer, "The link in the cloud could not be renewed.");
347
+ }
348
+ link = answer.body;
317
349
  }
318
350
  const next = {
319
351
  ...state,
320
- copy: { ...state.copy, shareUrl: answer.body.shareUrl, code: answer.body.code },
352
+ copy: { ...state.copy, shareUrl: link.shareUrl, code: link.code },
321
353
  };
322
354
  await writeSetting(key(w.id), next);
323
355
  return next;
@@ -330,7 +362,8 @@ export async function removeFromCloud(userId, wizardId) {
330
362
  }
331
363
  const w = await ownedWizard(userId, wizardId).catch(() => null);
332
364
  await deleteSetting(key(wizardId));
333
- if (!w || !state.copy || !(await cloudLinked())) {
365
+ // A space that syncs both ways deletes the copy with the next push.
366
+ if (!w || !state.copy || !(await cloudLinked()) || (await spaceSyncs(w.projectId))) {
334
367
  return;
335
368
  }
336
369
  await call("DELETE", `/spaces/${w.projectId}/wizards/${w.id}`).catch((err) => console.error("[cloud] copy not removed:", err.message));
@@ -370,6 +403,7 @@ export async function retryFailedSends(userId) {
370
403
  export async function forgetCloud() {
371
404
  await controlDb.delete(control.setting).where(like(control.setting.key, "cloud:%"));
372
405
  await forgetSentData();
406
+ await forgetTwoWay();
373
407
  }
374
408
  /** The space's data counts as not sent: the next wizard takes it along again. */
375
409
  async function forgetSentData() {
@@ -0,0 +1,132 @@
1
+ import { and, eq, gt, lt, sql } from "drizzle-orm";
2
+ import { db, schema } from "../db/client.js";
3
+ /**
4
+ * Who is in a wizard, page or table (docs/plans/live-changes.md, 8). A signal for people and AI:
5
+ * it never stops anyone from editing. Rows go through the live feed (`presence`), so every open
6
+ * studio, in every process, sees them.
7
+ */
8
+ /** Unseen this long, an entry is gone. */
9
+ export const PRESENCE_GONE_MS = 45_000;
10
+ /** An agent (MCP, API) counts as present this long after it read or wrote. */
11
+ export const AGENT_PRESENT_MS = 60_000;
12
+ /** Here, now. Again within 20 s keeps it; a new state or place goes out to every studio. */
13
+ export async function markPresent(p, at = new Date()) {
14
+ const row = {
15
+ kind: p.kind,
16
+ item: p.item,
17
+ who: p.who,
18
+ tab: p.tab ?? "",
19
+ whoKind: p.whoKind,
20
+ name: p.name,
21
+ client: p.client ?? null,
22
+ place: p.place ?? null,
23
+ placeLabel: p.placeLabel ?? null,
24
+ state: p.state,
25
+ seenAt: at,
26
+ };
27
+ await db
28
+ .insert(schema.livePresence)
29
+ .values(row)
30
+ .onConflictDoUpdate({
31
+ target: [
32
+ schema.livePresence.kind,
33
+ schema.livePresence.item,
34
+ schema.livePresence.who,
35
+ schema.livePresence.tab,
36
+ ],
37
+ set: {
38
+ name: row.name,
39
+ client: row.client,
40
+ place: row.place,
41
+ placeLabel: row.placeLabel,
42
+ state: row.state,
43
+ seenAt: row.seenAt,
44
+ },
45
+ });
46
+ }
47
+ /** Gone from the item: the editor closed, the turn ended. */
48
+ export async function leave(kind, item, who, tab = "") {
49
+ await db
50
+ .delete(schema.livePresence)
51
+ .where(and(eq(schema.livePresence.kind, kind), eq(schema.livePresence.item, item), eq(schema.livePresence.who, who), eq(schema.livePresence.tab, tab)));
52
+ }
53
+ /** Who is in the item now, the longest there first. */
54
+ export async function presentIn(kind, item, now = Date.now()) {
55
+ const rows = await db
56
+ .select()
57
+ .from(schema.livePresence)
58
+ .where(and(eq(schema.livePresence.kind, kind), eq(schema.livePresence.item, item), gt(schema.livePresence.seenAt, sql `${now} - ${keptFor}`)))
59
+ .orderBy(schema.livePresence.seenAt);
60
+ return rows.map((r) => ({
61
+ who: r.who,
62
+ tab: r.tab,
63
+ whoKind: r.whoKind,
64
+ name: r.name,
65
+ client: r.client,
66
+ place: r.place,
67
+ placeLabel: r.placeLabel,
68
+ state: r.state,
69
+ seenAt: r.seenAt.toISOString(),
70
+ }));
71
+ }
72
+ /** Who is in each item of a kind now: for the lists (a dot on a card). */
73
+ export async function presentByItem(kind, now = Date.now()) {
74
+ const rows = await db
75
+ .select({ item: schema.livePresence.item })
76
+ .from(schema.livePresence)
77
+ .where(and(eq(schema.livePresence.kind, kind), gt(schema.livePresence.seenAt, sql `${now} - ${keptFor}`)))
78
+ .groupBy(schema.livePresence.item);
79
+ const out = {};
80
+ for (const { item } of rows) {
81
+ out[item] = await presentIn(kind, item, now);
82
+ }
83
+ return out;
84
+ }
85
+ /** Deletes who is gone; each delete tells the open studios. */
86
+ export async function expirePresence(now = Date.now()) {
87
+ await db
88
+ .delete(schema.livePresence)
89
+ .where(lt(schema.livePresence.seenAt, sql `${now} - ${keptFor}`));
90
+ }
91
+ /** How long an entry stays without being seen again: an agent's a minute, else 45 seconds. */
92
+ const keptFor = sql `CASE WHEN ${schema.livePresence.whoKind} = 'agent' THEN ${AGENT_PRESENT_MS} ELSE ${PRESENCE_GONE_MS} END`;
93
+ /** An agent's mark: present, and gone a minute later unless it comes back (no heartbeats). */
94
+ export async function markAgent(kind, item, agent, state) {
95
+ await markPresent({
96
+ kind,
97
+ item,
98
+ who: agent.id,
99
+ whoKind: "agent",
100
+ name: agent.name,
101
+ client: agent.client,
102
+ state,
103
+ });
104
+ }
105
+ /** For tests and the hourly purge. */
106
+ export const presenceCount = async () => (await db.select({ n: sql `count(*)` }).from(schema.livePresence))[0]?.n ?? 0;
107
+ /**
108
+ * The studio assistant in a wizard while `work` runs, for the person it works for: a heartbeat
109
+ * keeps a long turn present, the end takes it away.
110
+ */
111
+ export async function asAssistantIn(wizardId, person, work) {
112
+ const who = `assistant:${person.id}`;
113
+ const mark = () => markPresent({
114
+ kind: "wizard",
115
+ item: wizardId,
116
+ who,
117
+ whoKind: "assistant",
118
+ name: "Studio assistant",
119
+ client: person.name,
120
+ state: "editing",
121
+ }).catch((err) => console.error("[presence]", err));
122
+ await mark();
123
+ const beat = setInterval(() => void mark(), 20_000);
124
+ beat.unref?.();
125
+ try {
126
+ return await work();
127
+ }
128
+ finally {
129
+ clearInterval(beat);
130
+ await leave("wizard", wizardId, who).catch(() => undefined);
131
+ }
132
+ }
@@ -7,6 +7,7 @@ import { db, schema } from "../db/client.js";
7
7
  import { env } from "../env.js";
8
8
  import { managed, tenantInfo } from "../manage.js";
9
9
  import { spaceChanged } from "../plugins/events.js";
10
+ import { cloudSpaceLimit, twoWayActive } from "../sync/state.js";
10
11
  import { putLink } from "../tenants/control.js";
11
12
  import { currentTenant } from "../tenants/tenant.js";
12
13
  import { serverText } from "../texts.js";
@@ -162,6 +163,16 @@ export async function projectLimit() {
162
163
  return info.limits.projects;
163
164
  }
164
165
  }
166
+ // A local install that syncs both ways has the organization's spaces: its number counts.
167
+ if (twoWayActive()) {
168
+ const limit = cloudSpaceLimit();
169
+ if (limit === null) {
170
+ return Number.POSITIVE_INFINITY;
171
+ }
172
+ if (limit !== undefined) {
173
+ return Math.max(1, limit);
174
+ }
175
+ }
165
176
  return Math.max(1, env.limits.projects);
166
177
  }
167
178
  /** The number for the studio: null where there is no limit (JSON has no infinity). */
@@ -161,12 +161,17 @@ async function tableKnowledge(table) {
161
161
  };
162
162
  }
163
163
  export async function getTable(userId, tableId) {
164
- const table = await tableRow(tableId);
165
- const project = await ownedProject(userId, table.projectId);
164
+ const header = await getTableHeader(userId, tableId);
166
165
  const rows = await db.query.spaceTableRow.findMany({
167
- where: eq(schema.spaceTableRow.tableId, table.id),
166
+ where: eq(schema.spaceTableRow.tableId, header.id),
168
167
  orderBy: [asc(schema.spaceTableRow.createdAt), asc(schema.spaceTableRow.id)],
169
168
  });
169
+ return { ...header, rows: rows.map(rowView) };
170
+ }
171
+ /** A table without its rows: what a change of its title or columns needs (live/views.ts). */
172
+ export async function getTableHeader(userId, tableId) {
173
+ const table = await tableRow(tableId);
174
+ const project = await ownedProject(userId, table.projectId);
170
175
  return {
171
176
  id: table.id,
172
177
  projectId: table.projectId,
@@ -175,11 +180,23 @@ export async function getTable(userId, tableId) {
175
180
  title: table.title,
176
181
  format: table.format,
177
182
  columns: table.columns,
178
- rows: rows.map((r) => ({ id: r.id, cells: r.cells, updatedAt: r.updatedAt.toISOString() })),
179
183
  readOnly: !(await projectWritable(project)),
180
184
  knowledge: await tableKnowledge(table),
181
185
  };
182
186
  }
187
+ /** One row of a table, as the table shows it; null when it is gone. */
188
+ export async function getRow(_userId, tableId, rowId) {
189
+ await tableRow(tableId);
190
+ const row = await db.query.spaceTableRow.findFirst({
191
+ where: and(eq(schema.spaceTableRow.id, rowId), eq(schema.spaceTableRow.tableId, tableId)),
192
+ });
193
+ return row ? rowView(row) : null;
194
+ }
195
+ const rowView = (r) => ({
196
+ id: r.id,
197
+ cells: r.cells,
198
+ updatedAt: r.updatedAt.toISOString(),
199
+ });
183
200
  /**
184
201
  * A new title, owner or columns. Rows keep their cells: a removed column's cells are dropped
185
202
  * the next time the row changes, and are not shown before. `review: null`: a person looked.
@@ -284,7 +301,10 @@ export async function addTableRow(_userId, tableId, cells = {}) {
284
301
  await db.insert(schema.spaceTableRow).values(row);
285
302
  await touchTable(table);
286
303
  await rowChanged(table, row.id);
287
- return { id: row.id, cells: value };
304
+ const saved = await db.query.spaceTableRow.findFirst({
305
+ where: eq(schema.spaceTableRow.id, row.id),
306
+ });
307
+ return { id: row.id, cells: value, updatedAt: (saved?.updatedAt ?? new Date()).toISOString() };
288
308
  }
289
309
  /** Changes the cells named in `cells`; the others stay. */
290
310
  export async function updateTableRow(_userId, tableId, rowId, cells) {
@@ -423,6 +443,11 @@ export async function getPage(userId, pageId) {
423
443
  export async function updatePage(_userId, pageId, patch) {
424
444
  const page = await pageRow(pageId);
425
445
  await requireWritableProject(page.projectId);
446
+ if (patch.baseUpdatedAt && page.updatedAt.getTime() > Date.parse(patch.baseUpdatedAt)) {
447
+ throw new ServiceError("revision_conflict", note("itemChangedMeantime"), {
448
+ page: await getPage(_userId, pageId),
449
+ });
450
+ }
426
451
  const title = patch.title !== undefined ? patch.title.trim() || page.title : page.title;
427
452
  const wizardId = patch.wizardId !== undefined ? await ownerOf(page.projectId, patch.wizardId) : page.wizardId;
428
453
  const parentId = wizardId !== null
@@ -432,6 +457,7 @@ export async function updatePage(_userId, pageId, patch) {
432
457
  : page.parentId;
433
458
  const moved = title !== page.title || wizardId !== page.wizardId || parentId !== page.parentId;
434
459
  const edited = moved || (patch.markdown !== undefined && patch.markdown !== page.markdown);
460
+ const at = new Date();
435
461
  await db
436
462
  .update(schema.spacePage)
437
463
  .set({
@@ -449,7 +475,7 @@ export async function updatePage(_userId, pageId, patch) {
449
475
  ...(patch.markdown !== undefined ? { markdown: checkMarkdown(patch.markdown) } : {}),
450
476
  ...(patch.review === null ? { review: null } : {}),
451
477
  ...(edited && page.origin ? { kept: true } : {}),
452
- updatedAt: new Date(),
478
+ updatedAt: at,
453
479
  })
454
480
  .where(eq(schema.spacePage.id, page.id));
455
481
  if (moved) {
@@ -458,6 +484,7 @@ export async function updatePage(_userId, pageId, patch) {
458
484
  else if (edited) {
459
485
  queueIndex(`p:${page.id}`);
460
486
  }
487
+ return { updatedAt: at.toISOString() };
461
488
  }
462
489
  export async function deletePage(_userId, pageId) {
463
490
  const page = await pageRow(pageId);