@engenty/wizards-runtime 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/apps/runtime/dist/app.js +18 -2
  2. package/apps/runtime/dist/db/live-triggers.js +144 -0
  3. package/apps/runtime/dist/db/migrations/tenant/0023_live_change.sql +167 -0
  4. package/apps/runtime/dist/db/migrations/tenant/0024_live_presence.sql +28 -0
  5. package/apps/runtime/dist/db/migrations/tenant/meta/0023_snapshot.json +3860 -0
  6. package/apps/runtime/dist/db/migrations/tenant/meta/0024_snapshot.json +3967 -0
  7. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +14 -0
  8. package/apps/runtime/dist/db/schema.js +41 -0
  9. package/apps/runtime/dist/docs/user-guide/meta.json +1 -0
  10. package/apps/runtime/dist/docs/user-guide/space.md +5 -1
  11. package/apps/runtime/dist/docs/user-guide/together.md +60 -0
  12. package/apps/runtime/dist/index.js +5 -1
  13. package/apps/runtime/dist/live/feed.js +34 -0
  14. package/apps/runtime/dist/live/hub.js +200 -0
  15. package/apps/runtime/dist/live/origin.js +53 -0
  16. package/apps/runtime/dist/live/views.js +146 -0
  17. package/apps/runtime/dist/mcp/handler.js +7 -1
  18. package/apps/runtime/dist/mcp/tools.js +51 -2
  19. package/apps/runtime/dist/routes/api.js +71 -2
  20. package/apps/runtime/dist/routes/live.js +85 -0
  21. package/apps/runtime/dist/routes/studio.js +47 -85
  22. package/apps/runtime/dist/services/presence.js +132 -0
  23. package/apps/runtime/dist/services/space-data.js +33 -6
  24. package/apps/runtime/dist/sync/apply.js +4 -0
  25. package/apps/runtime/dist/sync/client.js +146 -1
  26. package/apps/runtime/dist/texts.js +2 -0
  27. package/apps/web/dist/assets/AboutDialog-D2r8kBfV.js +1 -0
  28. package/apps/web/dist/assets/ChangelogDialog-j7Z1YhNv.js +1 -0
  29. package/apps/web/dist/assets/CodeEditor-BTCMfVFJ.js +2 -0
  30. package/apps/web/dist/assets/EditorPage-mx6XuEIw.js +3 -0
  31. package/apps/web/dist/assets/{FlowPreview-dc5C92kK.js → FlowPreview-BtVgtW7P.js} +1 -1
  32. package/apps/web/dist/assets/{Harness-D0nFOIVx.js → Harness-H4Ue1HOd.js} +2 -2
  33. package/apps/web/dist/assets/Marketplace-YEZDpGm9.js +2 -0
  34. package/apps/web/dist/assets/NewWizardChannels-K1HOzkXf.js +1 -0
  35. package/apps/web/dist/assets/NewWizardPage-DSHVwwnU.js +7 -0
  36. package/apps/web/dist/assets/OnboardingPage-CoBNtV_1.js +1 -0
  37. package/apps/web/dist/assets/PreviewPane-z0-Glj7p.js +10 -0
  38. package/apps/web/dist/assets/ProjectPage-DFaPSeda.js +1 -0
  39. package/apps/web/dist/assets/PublicRunner-DgT4CApp.js +1 -0
  40. package/apps/web/dist/assets/ReadOnly-Duk1YpNM.js +1 -0
  41. package/apps/web/dist/assets/SettingsPage-FimvOhQq.js +2 -0
  42. package/apps/web/dist/assets/SetupPage-BxEMrMtA.js +1 -0
  43. package/apps/web/dist/assets/SharePage-DvAUwrOl.js +1 -0
  44. package/apps/web/dist/assets/changelog-CS9GmnXd.js +1 -0
  45. package/apps/web/dist/assets/{coins-BGZKYmu6.js → coins-DSvwvqtQ.js} +1 -1
  46. package/apps/web/dist/assets/dist-BwhPmMDu.js +1 -0
  47. package/apps/web/dist/assets/dist-DVpDdhG9.js +1 -0
  48. package/apps/web/dist/assets/dist-DzdNG7Sf.js +10 -0
  49. package/apps/web/dist/assets/i18n-UTsgNY5M.js +55 -0
  50. package/apps/web/dist/assets/index-DHIXX69l.js +20 -0
  51. package/apps/web/dist/assets/index-Mt1sNdPx.css +1 -0
  52. package/apps/web/dist/assets/json-D2GVvTXK.js +1 -0
  53. package/apps/web/dist/assets/markdown-DwdMW7q0.js +29 -0
  54. package/apps/web/dist/assets/{oss-credits-C2JUsf2d.js → oss-credits-BLVLXRzs.js} +1 -1
  55. package/apps/web/dist/assets/{phone-BzHhwehj.js → phone-xIUU1ZFn.js} +1 -1
  56. package/apps/web/dist/assets/runners-CrSLA6HI.js +1 -0
  57. package/apps/web/dist/assets/session-CbWzkHl0.js +2 -0
  58. package/apps/web/dist/assets/{settings-menu-BZRGhsIO.js → settings-menu-DoRItnPf.js} +1 -1
  59. package/apps/web/dist/assets/theme-znovbShL.js +11 -0
  60. package/apps/web/dist/assets/ui-6AgUKJhQ.js +83 -0
  61. package/apps/web/dist/assets/{upload-CwT8oMz0.js → upload-C8WgcG1g.js} +1 -1
  62. package/apps/web/dist/assets/{useMutation-byk81dDj.js → useMutation-BdCg6qrc.js} +1 -1
  63. package/apps/web/dist/assets/{volume-2-B1Pz6Iwt.js → volume-2-jlgQapiz.js} +1 -1
  64. package/apps/web/dist/assets/{wrench-CvzXRbWN.js → wrench-Ca_TrBQk.js} +1 -1
  65. package/apps/web/dist/index.html +9 -8
  66. package/apps/web/dist/mcp/flow.html +2 -2
  67. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +6 -0
  68. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +6 -0
  69. package/node_modules/@engenty/wizards-shared/dist/live.d.ts +46 -0
  70. package/node_modules/@engenty/wizards-shared/dist/live.js +9 -0
  71. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +1 -0
  72. package/node_modules/@engenty/wizards-shared/dist/run.js +2 -0
  73. package/package.json +1 -1
  74. package/plugin/.claude-plugin/plugin.json +1 -1
  75. package/plugin/plugin.json +1 -1
  76. package/apps/web/dist/assets/AboutDialog-D1YHT0jc.js +0 -1
  77. package/apps/web/dist/assets/ChangelogDialog-Bv02g8av.js +0 -1
  78. package/apps/web/dist/assets/EditorPage-BThoZwqO.js +0 -4
  79. package/apps/web/dist/assets/Marketplace-Cnd8BF3q.js +0 -2
  80. package/apps/web/dist/assets/NewWizardChannels-i62Y_2DZ.js +0 -1
  81. package/apps/web/dist/assets/NewWizardPage-BcpRA1fx.js +0 -7
  82. package/apps/web/dist/assets/OnboardingPage-BcMDEXNq.js +0 -1
  83. package/apps/web/dist/assets/PreviewPane-GHcVV2Hu.js +0 -4
  84. package/apps/web/dist/assets/ProjectPage-TDywzUOd.js +0 -1
  85. package/apps/web/dist/assets/PublicRunner-B6JINLpR.js +0 -1
  86. package/apps/web/dist/assets/ReadOnly-Mv5M2OV9.js +0 -1
  87. package/apps/web/dist/assets/SettingsPage-B-F1dLgt.js +0 -2
  88. package/apps/web/dist/assets/SetupPage-CVdsdVBW.js +0 -1
  89. package/apps/web/dist/assets/SharePage-CBSRK0wF.js +0 -1
  90. package/apps/web/dist/assets/changelog-BR1lxaWv.js +0 -1
  91. package/apps/web/dist/assets/index-D3-kv1WF.js +0 -14
  92. package/apps/web/dist/assets/index-DcUL6teA.css +0 -1
  93. package/apps/web/dist/assets/runners-C1-zIlry.js +0 -1
  94. package/apps/web/dist/assets/session-B_JeZnJ0.js +0 -2
  95. package/apps/web/dist/assets/theme-HcCfZDzS.js +0 -11
  96. package/apps/web/dist/assets/ui-BI1RPFWT.js +0 -137
@@ -162,6 +162,20 @@
162
162
  "when": 1792580809821,
163
163
  "tag": "0022_sync",
164
164
  "breakpoints": true
165
+ },
166
+ {
167
+ "idx": 23,
168
+ "version": "6",
169
+ "when": 1792647499005,
170
+ "tag": "0023_live_change",
171
+ "breakpoints": true
172
+ },
173
+ {
174
+ "idx": 24,
175
+ "version": "6",
176
+ "when": 1792649943526,
177
+ "tag": "0024_live_presence",
178
+ "breakpoints": true
165
179
  }
166
180
  ]
167
181
  }
@@ -640,6 +640,47 @@ export const syncChange = sqliteTable("sync_change", {
640
640
  index("sync_change_item").on(t.kind, t.item),
641
641
  index("sync_change_project").on(t.projectId, t.seq),
642
642
  ]);
643
+ /**
644
+ * Live changes (docs/plans/live-changes.md): triggers (`db/live-triggers.ts`) number every write
645
+ * to an item a studio shows, pulled ones too, so an open studio hears of it. Kept 15 minutes.
646
+ */
647
+ export const liveChange = sqliteTable("live_change", {
648
+ seq: integer("seq").primaryKey({ autoIncrement: true }),
649
+ projectId: text("project_id"),
650
+ kind: text("kind").notNull(),
651
+ /** `put` or `del`. */
652
+ op: text("op").notNull(),
653
+ item: text("item").notNull(),
654
+ parent: text("parent"),
655
+ at: integer("at", { mode: "timestamp_ms" }).notNull().default(now),
656
+ }, (t) => [index("live_change_at").on(t.at)]);
657
+ /**
658
+ * Who is in a wizard, page or table right now (docs/plans/live-changes.md, 8): a person in an
659
+ * editor, the studio assistant during its turn, an MCP client or API key for a minute after it
660
+ * read or wrote. A signal, never a lock. A row unseen for 45 seconds is gone.
661
+ */
662
+ export const livePresence = sqliteTable("live_presence", {
663
+ kind: text("kind").notNull(),
664
+ item: text("item").notNull(),
665
+ /** The person's id, or the client's for an agent. */
666
+ who: text("who").notNull(),
667
+ /** One editor of that person: a tab. */
668
+ tab: text("tab").notNull().default(""),
669
+ /** `person`, `agent` (MCP, API), `assistant`, `run`. */
670
+ whoKind: text("who_kind").notNull(),
671
+ name: text("name").notNull(),
672
+ /** The app an agent acts through; for the assistant, whom it acts for. */
673
+ client: text("client"),
674
+ /** Where in the item: a step, a section, a row; and how to say it. */
675
+ place: text("place"),
676
+ placeLabel: text("place_label"),
677
+ /** `viewing` or `editing`. */
678
+ state: text("state").notNull(),
679
+ seenAt: integer("seen_at", { mode: "timestamp_ms" }).notNull().default(now),
680
+ }, (t) => [
681
+ primaryKey({ columns: [t.kind, t.item, t.who, t.tab] }),
682
+ index("live_presence_seen").on(t.seenAt),
683
+ ]);
643
684
  /** One row: `applying` is 1 while an install writes what it pulled, so the triggers note none of it. */
644
685
  export const syncGuard = sqliteTable("sync_guard", {
645
686
  id: integer("id").primaryKey(),
@@ -16,6 +16,7 @@
16
16
  "run",
17
17
  "space",
18
18
  "cloud-sync",
19
+ "together",
19
20
  "---Settings---",
20
21
  "connectors",
21
22
  "models",
@@ -90,7 +90,11 @@ wizard. The buttons “Table” and “Page” add one to a wizard.
90
90
  marked and not saved. The heading of a column changes its name and type, and the plus beside
91
91
  the headings adds a column.
92
92
  - **Page**: a title and text in Markdown. “Write” edits it, and “Preview” shows it. It is saved
93
- as you type.
93
+ as you type. While you write, headings show large and bold text bold, and the Markdown marks
94
+ stay visible in a lighter colour. ⌘/Ctrl+B and ⌘/Ctrl+I make bold and italic text, ⌘/Ctrl+K
95
+ makes a link, and ⌘/Ctrl+F searches the page. Enter continues a list, and Enter on an empty
96
+ item ends it. Inside a link’s address, after `](`, the editor offers the space’s pages, tables
97
+ and files by title. ⌘/Ctrl+click on a link opens what it names.
94
98
 
95
99
  ### On your computer and in the cloud
96
100
 
@@ -0,0 +1,60 @@
1
+ ---
2
+ title: Working together
3
+ description: How the studio shows what others change while you work, merges it with what you type, and shows who else is in a wizard, page or table.
4
+ version: 0.10.0
5
+ ---
6
+
7
+ The studio shows changes made elsewhere as they happen. You don’t reload anything. That holds
8
+ whoever made the change:
9
+
10
+ - another member of your organization, or you in another window;
11
+ - the AI: the assistant in the editor, or an app like Claude Code over MCP;
12
+ - a run that adds rows to a table;
13
+ - the cloud, when your computer keeps its spaces the same as there
14
+ ([Spaces in the cloud](cloud-sync)).
15
+
16
+ A row, a card or a page that changed elsewhere lights up for a moment.
17
+
18
+ ## While you type
19
+
20
+ What you type is never replaced. engenty wizards saves a moment after you stop typing:
21
+
22
+ | Your editor | A change from elsewhere |
23
+ |---|---|
24
+ | Nothing typed since the last save | Shows at once. The cursor stays where it was |
25
+ | Something typed, not saved yet | Waits. Nothing moves while you type. The next save merges both, and the editor shows “Merged with changes from …” |
26
+ | You and someone else changed the same place | The editor asks: “Keep mine” or “Take the other version”. Until you choose, your text stays and isn’t saved over theirs |
27
+
28
+ In a table each cell saves on its own. The cell you type in keeps what you type, and the other
29
+ cells of the row change as they come.
30
+
31
+ ## Who else is here
32
+
33
+ The header of a wizard, page or table shows who else has it open, with a colour each:
34
+
35
+ - a person’s initials: they look at it, or edit it if their initials have a ring;
36
+ - a robot for the AI: the assistant for someone, or an app over MCP. An app counts as here for a
37
+ minute after it read or changed the wizard.
38
+
39
+ Hold the pointer over a face to see what they do and where: a step of the wizard, a section of a
40
+ page, a row of a table. A row someone else edits has an edge in their colour, and a wizard card
41
+ shows a dot for each person in it. When you type where someone else types, the editor says
42
+ “Anna is editing this too”.
43
+
44
+ This is for your awareness only. Anyone can still edit, and nothing is locked.
45
+
46
+ ## The AI knows too
47
+
48
+ An app over MCP learns who else is in a wizard when it reads or changes it. When a person edits
49
+ the same wizard, the app hears that their editor merges its change, and it tells you before
50
+ larger changes.
51
+
52
+ ## Switch it off
53
+
54
+ To turn live changes off on your computer, add this line to `~/.engenty/wizards/.features`:
55
+
56
+ ```bash
57
+ liveChanges=off
58
+ ```
59
+
60
+ The studio then shows what changed when you open a page again.
@@ -7,6 +7,7 @@ import { adoptLegacyData } from "./db/adopt.js";
7
7
  import { knownTenants, migrateAllTenants, migrateControlDb, openTenantDb, withTenant, } from "./db/client.js";
8
8
  import { startRunner, stopRunner } from "./engine/runner.js";
9
9
  import { basePath, env } from "./env.js";
10
+ import { pruneLive } from "./live/feed.js";
10
11
  import { hookConsole } from "./log.js";
11
12
  import { managed } from "./manage.js";
12
13
  import { checkModelsAtStart, loadCatalog, loadLocalModels } from "./models.js";
@@ -94,7 +95,7 @@ if (env.serves.runner) {
94
95
  async function purge() {
95
96
  await purgeSessions();
96
97
  for (const id of await knownTenants()) {
97
- await withTenant(id, () => Promise.all([purgeExpiredRuns(), purgeUnusedStores(), compactLog()])).catch((err) => console.error(`[retention ${id}]`, err));
98
+ await withTenant(id, () => Promise.all([purgeExpiredRuns(), purgeUnusedStores(), compactLog(), pruneLive()])).catch((err) => console.error(`[retention ${id}]`, err));
98
99
  }
99
100
  }
100
101
  void purge().catch((err) => console.error("[retention]", err));
@@ -109,6 +110,9 @@ if (!managed) {
109
110
  const twoWay = () => withTenant(LOCAL_TENANT, () => syncAll()).catch((err) => console.error("[sync]", err));
110
111
  setTimeout(() => void twoWay(), 5_000).unref();
111
112
  setInterval(() => void twoWay(), 60_000).unref();
113
+ // And between the rounds: what changes in the cloud, as it happens.
114
+ const { followCloud } = await import("./sync/client.js");
115
+ void withTenant(LOCAL_TENANT, () => followCloud(new AbortController().signal)).catch((err) => console.error("[sync] following the cloud:", err));
112
116
  }
113
117
  async function shutdown(code = 0) {
114
118
  clearRunning(env.dataDir);
@@ -0,0 +1,34 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { db } from "../db/client.js";
3
+ /**
4
+ * The tenant's live feed (`live_change`, docs/plans/live-changes.md): numbered writes to the
5
+ * items a studio shows. These read it in the current tenant's context.
6
+ */
7
+ /** How long a change stays readable: a reconnect within it catches up, a later one resets. */
8
+ export const LIVE_KEEP_MS = 15 * 60_000;
9
+ /** The newest number in the feed, 0 when it never had a row. */
10
+ export async function newestSeq() {
11
+ const rows = await db.all(sql `SELECT seq FROM sqlite_sequence WHERE name = 'live_change'`);
12
+ return rows[0]?.seq ?? 0;
13
+ }
14
+ /** The oldest number still kept, or null when the feed is empty. */
15
+ export async function oldestSeq() {
16
+ const rows = await db.all(sql `SELECT MIN(seq) AS seq FROM live_change`);
17
+ return rows[0]?.seq ?? null;
18
+ }
19
+ /** The changes after `since`, oldest first, at most `limit`. */
20
+ export async function changesAfter(since, limit) {
21
+ const rows = await db.all(sql `SELECT seq, project_id, kind, op, item, parent FROM live_change WHERE seq > ${since} ORDER BY seq LIMIT ${limit}`);
22
+ return rows.map((r) => ({
23
+ seq: r.seq,
24
+ projectId: r.project_id,
25
+ kind: r.kind,
26
+ op: r.op,
27
+ item: r.item,
28
+ parent: r.parent,
29
+ }));
30
+ }
31
+ /** Deletes changes older than what a reconnect may catch up on. */
32
+ export async function pruneLive(now = Date.now()) {
33
+ await db.run(sql `DELETE FROM live_change WHERE at < ${now - LIVE_KEEP_MS}`);
34
+ }
@@ -0,0 +1,200 @@
1
+ import { withTenant } from "../db/client.js";
2
+ import { expirePresence } from "../services/presence.js";
3
+ import { changesAfter, newestSeq, oldestSeq, pruneLive } from "./feed.js";
4
+ /** More changes than this in one go and the browser reloads what is open instead. */
5
+ export const BURST = 1000;
6
+ const FAST_MS = 1000;
7
+ const SLOW_MS = 3000;
8
+ /** Ticks stay fast this long after the last change. */
9
+ const BUSY_MS = 60_000;
10
+ const PRUNE_EVERY_MS = 5 * 60_000;
11
+ const EXPIRE_EVERY_MS = 10_000;
12
+ /** Views a batch carries at most, in characters of JSON; the items after it go without. */
13
+ export const BATCH_VIEWS_MAX = 512 * 1024;
14
+ /** Above this a view isn't sent: the browser fetches that item. */
15
+ export const VIEW_MAX = 64 * 1024;
16
+ const feeds = new Map();
17
+ /**
18
+ * Starts sending the tenant's changes after `since` (null: from now on). Answers `hello`, or
19
+ * `reset` when the changes after `since` are no longer kept or `since` is of another database.
20
+ */
21
+ export async function subscribe(tenantId, since, send, views) {
22
+ const { newest, gap } = await withTenant(tenantId, async () => {
23
+ const newest = await newestSeq();
24
+ if (since === null || since === newest) {
25
+ return { newest, gap: false };
26
+ }
27
+ if (since > newest) {
28
+ return { newest, gap: true };
29
+ }
30
+ const oldest = await oldestSeq();
31
+ return { newest, gap: oldest === null || oldest > since + 1 };
32
+ });
33
+ const sub = { since: since === null || gap ? newest : since, send, views };
34
+ send(gap ? { event: "reset", seq: newest } : { event: "hello", seq: newest });
35
+ let feed = feeds.get(tenantId);
36
+ if (!feed) {
37
+ feed = {
38
+ id: tenantId,
39
+ subs: new Set(),
40
+ timer: null,
41
+ ticking: false,
42
+ again: false,
43
+ changedAt: 0,
44
+ prunedAt: 0,
45
+ expiredAt: 0,
46
+ };
47
+ feeds.set(tenantId, feed);
48
+ }
49
+ feed.subs.add(sub);
50
+ // A catch-up is the next tick's work.
51
+ schedule(feed, sub.since < newest ? 0 : FAST_MS);
52
+ return () => {
53
+ const f = feeds.get(tenantId);
54
+ if (!f) {
55
+ return;
56
+ }
57
+ f.subs.delete(sub);
58
+ if (!f.subs.size) {
59
+ if (f.timer) {
60
+ clearTimeout(f.timer);
61
+ }
62
+ feeds.delete(tenantId);
63
+ }
64
+ };
65
+ }
66
+ /** A write in this process: read the tenant's feed now, if anyone listens. */
67
+ export function nudge(tenantId) {
68
+ const feed = tenantId ? feeds.get(tenantId) : undefined;
69
+ if (feed) {
70
+ schedule(feed, 0);
71
+ }
72
+ }
73
+ /** Something only this process knows changed, such as the two-way sync's state. */
74
+ export function signal(tenantId, event) {
75
+ const feed = tenantId ? feeds.get(tenantId) : undefined;
76
+ for (const sub of feed?.subs ?? []) {
77
+ sub.send({ event });
78
+ }
79
+ }
80
+ /** Streams open in this process, for limits and tests. */
81
+ export function openStreams(tenantId) {
82
+ return feeds.get(tenantId)?.subs.size ?? 0;
83
+ }
84
+ function schedule(feed, ms) {
85
+ if (feed.ticking) {
86
+ feed.again = true;
87
+ return;
88
+ }
89
+ if (feed.timer) {
90
+ clearTimeout(feed.timer);
91
+ }
92
+ feed.timer = setTimeout(() => void tick(feed), ms);
93
+ feed.timer.unref?.();
94
+ }
95
+ async function tick(feed) {
96
+ feed.timer = null;
97
+ if (feeds.get(feed.id) !== feed) {
98
+ return;
99
+ }
100
+ feed.ticking = true;
101
+ feed.again = false;
102
+ try {
103
+ await withTenant(feed.id, () => read(feed));
104
+ }
105
+ catch (err) {
106
+ console.error(`[live ${feed.id}]`, err);
107
+ }
108
+ finally {
109
+ feed.ticking = false;
110
+ }
111
+ if (feeds.get(feed.id) === feed) {
112
+ const quiet = Date.now() - feed.changedAt > BUSY_MS;
113
+ schedule(feed, feed.again ? 0 : quiet ? SLOW_MS : FAST_MS);
114
+ }
115
+ }
116
+ async function read(feed) {
117
+ const subs = [...feed.subs];
118
+ if (!subs.length) {
119
+ return;
120
+ }
121
+ const from = Math.min(...subs.map((s) => s.since));
122
+ const rows = await changesAfter(from, BURST + 1);
123
+ if (rows.length) {
124
+ feed.changedAt = Date.now();
125
+ }
126
+ if (rows.length > BURST) {
127
+ const seq = await newestSeq();
128
+ for (const sub of subs) {
129
+ sub.since = seq;
130
+ sub.send({ event: "reset", seq });
131
+ }
132
+ }
133
+ else if (rows.length) {
134
+ const read = new Map();
135
+ for (const sub of subs) {
136
+ const mine = rows.filter((r) => r.seq > sub.since);
137
+ if (!mine.length) {
138
+ continue;
139
+ }
140
+ const seq = mine[mine.length - 1].seq;
141
+ sub.since = seq;
142
+ sub.send({ event: "changes", seq, items: await withViews(dedupe(mine), sub.views, read) });
143
+ }
144
+ }
145
+ if (Date.now() - feed.prunedAt > PRUNE_EVERY_MS) {
146
+ feed.prunedAt = Date.now();
147
+ await pruneLive();
148
+ }
149
+ // Who left without saying so: their entries go, and the open studios hear of it.
150
+ if (Date.now() - feed.expiredAt > EXPIRE_EVERY_MS) {
151
+ feed.expiredAt = Date.now();
152
+ await expirePresence();
153
+ }
154
+ }
155
+ /**
156
+ * The views of a batch's `put` items, read once per item and kind of reader. A put whose item
157
+ * is gone by now goes as a `del`; a view too big, or over the batch's budget, is left out.
158
+ */
159
+ async function withViews(items, views, read) {
160
+ if (!views) {
161
+ return items;
162
+ }
163
+ let budget = BATCH_VIEWS_MAX;
164
+ const out = [];
165
+ for (const x of items) {
166
+ if (x.op === "del") {
167
+ out.push(x);
168
+ continue;
169
+ }
170
+ const key = `${views.key}|${x.kind}|${x.item}`;
171
+ let view = read.get(key);
172
+ if (!view) {
173
+ view = views.read(x).catch(() => undefined);
174
+ read.set(key, view);
175
+ }
176
+ const v = await view;
177
+ if (v === null) {
178
+ out.push({ ...x, op: "del" });
179
+ continue;
180
+ }
181
+ const size = v === undefined ? 0 : JSON.stringify(v).length;
182
+ if (v === undefined || size > VIEW_MAX || size > budget) {
183
+ out.push(x);
184
+ continue;
185
+ }
186
+ budget -= size;
187
+ out.push({ ...x, view: v });
188
+ }
189
+ return out;
190
+ }
191
+ /** One entry per item, in the order of its last change, with its last op and number. */
192
+ export function dedupe(rows) {
193
+ const last = new Map();
194
+ for (const item of rows) {
195
+ const key = `${item.kind}|${item.item}`;
196
+ last.delete(key);
197
+ last.set(key, item);
198
+ }
199
+ return [...last.values()];
200
+ }
@@ -0,0 +1,53 @@
1
+ import { subscribe } from "./hub.js";
2
+ /**
3
+ * Which install wrote what (docs/plans/live-changes.md, 7): the feed numbers a push of an install
4
+ * wrote. The cloud's live call leaves those out for that install, else every push would come
5
+ * back to it as a pull of nothing. A change by someone else, even of the same item, has its own
6
+ * number and goes through. Kept in memory for a minute.
7
+ */
8
+ const KEEP_MS = 60_000;
9
+ const pushes = new Map();
10
+ /**
11
+ * A push of `install` starts writing after the feed's number `from`. Until `done` gives its last
12
+ * number, everything after `from` counts as the push's: a tick in between can't send it back.
13
+ */
14
+ export function notePush(tenant, install, from) {
15
+ if (!install) {
16
+ return { done: (_to) => undefined };
17
+ }
18
+ const now = Date.now();
19
+ const entry = { install, from, to: Number.POSITIVE_INFINITY, at: now };
20
+ const kept = (pushes.get(tenant) ?? []).filter((p) => now - p.at < KEEP_MS);
21
+ kept.push(entry);
22
+ pushes.set(tenant, kept);
23
+ return {
24
+ done: (to) => {
25
+ entry.to = to;
26
+ },
27
+ };
28
+ }
29
+ /** Whether `install` itself wrote the change numbered `seq`. */
30
+ export function pushedBy(tenant, install, seq) {
31
+ return (pushes.get(tenant) ?? []).some((p) => p.install === install && seq > p.from && seq <= p.to);
32
+ }
33
+ /**
34
+ * The cloud's live call for one install: the spaces with changes, without what the install
35
+ * pushed itself. `hear` gets hello, reset and changes; the answer stops it.
36
+ */
37
+ export async function followFor(tenantId, install, since, hear) {
38
+ return subscribe(tenantId, since, (e) => {
39
+ if (e.event === "changes") {
40
+ const spaces = new Set();
41
+ for (const x of e.items) {
42
+ if (x.projectId && !(x.seq !== undefined && pushedBy(tenantId, install, x.seq))) {
43
+ spaces.add(x.projectId);
44
+ }
45
+ }
46
+ // Its own push only: the number moves on, nothing to pull.
47
+ hear({ event: "changes", seq: e.seq, spaces: [...spaces] });
48
+ }
49
+ else if (e.event === "hello" || e.event === "reset") {
50
+ hear(e);
51
+ }
52
+ });
53
+ }
@@ -0,0 +1,146 @@
1
+ import { wizardLang } from "@engenty/wizards-shared/definition";
2
+ import { wizardTexts } from "@engenty/wizards-shared/translation";
3
+ import { eq } from "drizzle-orm";
4
+ import { listConnectors } from "../connectors/external.js";
5
+ import { db, schema } from "../db/client.js";
6
+ import { embeddingModel } from "../models.js";
7
+ import { mayBuild, projectWritable } from "../services/access.js";
8
+ import { cloudLinked, cloudState } from "../services/cloud.js";
9
+ import { ServiceError } from "../services/errors.js";
10
+ import { presentIn } from "../services/presence.js";
11
+ import { fileView, projectFiles } from "../services/project-files.js";
12
+ import { listProjects, maskedServers, ownedProject } from "../services/projects.js";
13
+ import { getPage, getRow, getTableHeader } from "../services/space-data.js";
14
+ import { publishedDefinition, translationsOf } from "../services/translations.js";
15
+ import { listWizards, ownedWizard, wizardMessages, wizardState } from "../services/wizards.js";
16
+ /** The spaces, as the studio lists them. */
17
+ export async function spacesView(r) {
18
+ const projects = await listProjects(r.userId, r.lang);
19
+ const build = await mayBuild();
20
+ return projects.map((p) => ({
21
+ id: p.id,
22
+ name: p.name,
23
+ brand: p.brand,
24
+ facts: p.facts,
25
+ /** The space's public page; null until it is set up. */
26
+ page: p.page ?? null,
27
+ mcpServers: maskedServers(p),
28
+ wizardCount: p.wizardCount,
29
+ /** `local`: synced from a local install, where it is changed. */
30
+ origin: p.origin,
31
+ syncedAt: p.syncedAt?.toISOString() ?? null,
32
+ readOnly: p.origin === "local" || !build,
33
+ }));
34
+ }
35
+ /** A space's wizards, as its cards show them. */
36
+ export async function wizardsView(r, projectId) {
37
+ await ownedProject(r.userId, projectId);
38
+ const wizards = await listWizards(r.userId, projectId);
39
+ // A local install with an account: where each wizard stands in its cloud, for the cards.
40
+ const linked = await cloudLinked();
41
+ return Promise.all(wizards.map(async (w) => ({ ...w, cloud: linked ? await cloudState(w.id) : null })));
42
+ }
43
+ /** A wizard, as the editor opens it. */
44
+ export async function wizardView(r, id) {
45
+ const w = await ownedWizard(r.userId, id);
46
+ const messages = await wizardMessages(w.id);
47
+ const project = await ownedProject(r.userId, w.projectId);
48
+ return {
49
+ ...(await wizardState(w)),
50
+ /** Shown and run here, changed elsewhere: a local install's wizard, or nothing is built here. */
51
+ readOnly: !(await projectWritable(project)),
52
+ blank: messages.length === 0 && !w.starter,
53
+ messages: messages.map((m) => ({
54
+ id: m.id,
55
+ role: m.role,
56
+ content: m.content,
57
+ changed: m.changed,
58
+ source: m.source,
59
+ client: m.client,
60
+ })),
61
+ mcpServers: project.mcpServers.map((s) => ({ id: s.id, name: s.name })),
62
+ };
63
+ }
64
+ /** The languages the published wizard is kept in, each original text with its translation. */
65
+ export async function translationsView(r, wizardId) {
66
+ const w = await ownedWizard(r.userId, wizardId);
67
+ const def = await publishedDefinition(w);
68
+ const kept = await translationsOf(w.id);
69
+ return {
70
+ lang: def ? wizardLang(def) : wizardLang(w.draft),
71
+ texts: def ? wizardTexts(def) : [],
72
+ translations: kept.map((t) => ({
73
+ lang: t.lang,
74
+ texts: t.texts,
75
+ updatedAt: t.updatedAt.toISOString(),
76
+ })),
77
+ };
78
+ }
79
+ /** What a space holds for all its wizards. */
80
+ export async function filesView(r, projectId) {
81
+ const project = await ownedProject(r.userId, projectId);
82
+ return {
83
+ files: (await projectFiles(project.id)).map(fileView),
84
+ /** Whether documents get vectors, or the index works on keywords alone. */
85
+ embeddings: Boolean(await embeddingModel().catch(() => null)),
86
+ };
87
+ }
88
+ /** The connectors a space's wizards can name. */
89
+ export async function connectorsView(r, projectId) {
90
+ const project = await ownedProject(r.userId, projectId);
91
+ return listConnectors(project.id);
92
+ }
93
+ // --- one item, for the live stream ------------------------------------------------------------
94
+ const gone = (err) => err instanceof ServiceError && err.code === "not_found";
95
+ /**
96
+ * One changed item's view, as it travels with a change. `null`: the item is gone. `undefined`:
97
+ * the kind has no view, and the browser fetches what shows it.
98
+ */
99
+ const ITEM_VIEWS = {
100
+ space: async (r, x) => (await spacesView(r)).find((s) => s.id === x.item) ?? null,
101
+ wizard: async (r, x) => {
102
+ const summary = x.projectId
103
+ ? (await wizardsView(r, x.projectId)).find((w) => w.id === x.item)
104
+ : undefined;
105
+ return summary ? { summary, detail: await wizardView(r, x.item) } : null;
106
+ },
107
+ translation: async (r, x) => (x.parent ? translationsView(r, x.parent) : null),
108
+ message: null,
109
+ page: (r, x) => getPage(r.userId, x.item),
110
+ table: (r, x) => getTableHeader(r.userId, x.item),
111
+ row: async (r, x) => {
112
+ const row = x.parent ? await getRow(r.userId, x.parent, x.item) : null;
113
+ return row ? { ...row, tableId: x.parent } : null;
114
+ },
115
+ category: null,
116
+ presence: async (_r, x) => x.parent ? presentIn(x.parent, x.item.slice(x.parent.length + 1)) : [],
117
+ file: async (_r, x) => {
118
+ const row = await db.query.projectFile.findFirst({ where: eq(schema.projectFile.id, x.item) });
119
+ return row ? fileView(row) : null;
120
+ },
121
+ connector: async (r, x) => {
122
+ if (!x.projectId) {
123
+ return null;
124
+ }
125
+ const id = x.item.slice(x.projectId.length + 1);
126
+ return (await connectorsView(r, x.projectId)).find((c) => c.id === id) ?? null;
127
+ },
128
+ };
129
+ export async function itemView(r, x) {
130
+ const read = ITEM_VIEWS[x.kind];
131
+ if (!read) {
132
+ return undefined;
133
+ }
134
+ try {
135
+ return await read(r, x);
136
+ }
137
+ catch (err) {
138
+ if (gone(err)) {
139
+ return null;
140
+ }
141
+ console.error(`[live] the view of ${x.kind} ${x.item}:`, err);
142
+ return undefined;
143
+ }
144
+ }
145
+ /** Every kind has an entry, a view or none: a test reads this. */
146
+ export const viewKinds = Object.keys(ITEM_VIEWS);
@@ -1,6 +1,7 @@
1
1
  import { createMcpHandler, McpServer, originValidationResponse, } from "@modelcontextprotocol/server";
2
2
  import { withTenant } from "../db/client.js";
3
3
  import { env } from "../env.js";
4
+ import { nudge } from "../live/hub.js";
4
5
  import { asRole } from "../services/access.js";
5
6
  import { tenantStatus } from "../tenants/control.js";
6
7
  import { authenticate, principalOf } from "./auth.js";
@@ -10,6 +11,7 @@ import { registerPrompts, registerTools } from "./tools.js";
10
11
  const INSTRUCTIONS = `engenty wizards: page-by-page AI wizards — the person answers pages, AI steps write, research and make images or videos, the person reviews, the result is files.
11
12
  Use one: list_wizards, then run_wizard straight away — its widget shows the wizard itself (show_wizard only when the person wants to see a wizard before running it), then follow waitingFor (answer_page, review_step, answer_ask, get_run with waitSeconds). Runs spend credits.
12
13
  Build one: get_authoring_guide (schema + design rules), a close starter with get_starter, create_wizard, edit_wizard until "issues" is empty, check with start_test_run + get_test_run. Publish only when the person asks.
14
+ A result on a wizard may list "present": people and other agents in that wizard now. Nobody is locked out; when people are editing, tell your user before larger changes.
13
15
  When a run needs the browser, hand over its browserUrl, the wizard's own run page. The studioUrl is for building only: never send someone who uses a wizard to the studio.
14
16
  Projects are called spaces in the studio. Ids are for the tools only: name wizards and spaces by their titles and names, and where two spaces share a name, by where each comes from.`;
15
17
  /** A wizard definition is a few KB; this leaves room and refuses anything far beyond it. */
@@ -49,6 +51,10 @@ export function mcpHandler() {
49
51
  .catch(() => null);
50
52
  noteRequest(who.tenantId, authInfo.clientId, who.client, body);
51
53
  }
52
- return withTenant(who.tenantId, () => asRole(who.role, () => handler.fetch(request, { authInfo })));
54
+ const answer = await withTenant(who.tenantId, () => asRole(who.role, () => handler.fetch(request, { authInfo })));
55
+ if (request.method === "POST") {
56
+ nudge(who.tenantId);
57
+ }
58
+ return answer;
53
59
  };
54
60
  }