@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.
- package/apps/runtime/dist/app.js +34 -1
- package/apps/runtime/dist/auth/index.js +10 -1
- package/apps/runtime/dist/db/client.js +9 -1
- package/apps/runtime/dist/db/live-triggers.js +144 -0
- package/apps/runtime/dist/db/migrations/tenant/0022_sync.sql +247 -0
- package/apps/runtime/dist/db/migrations/tenant/0023_live_change.sql +167 -0
- package/apps/runtime/dist/db/migrations/tenant/0024_live_presence.sql +28 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0022_snapshot.json +3792 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0023_snapshot.json +3860 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0024_snapshot.json +3967 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +21 -0
- package/apps/runtime/dist/db/schema.js +101 -0
- package/apps/runtime/dist/docs/user-guide/cloud-sync.md +85 -0
- package/apps/runtime/dist/docs/user-guide/data.md +4 -4
- package/apps/runtime/dist/docs/user-guide/meta.json +2 -0
- package/apps/runtime/dist/docs/user-guide/test-and-share.md +4 -14
- package/apps/runtime/dist/docs/user-guide/together.md +60 -0
- package/apps/runtime/dist/files/blobs.js +13 -0
- package/apps/runtime/dist/index.js +11 -1
- package/apps/runtime/dist/live/feed.js +34 -0
- package/apps/runtime/dist/live/hub.js +200 -0
- package/apps/runtime/dist/live/origin.js +53 -0
- package/apps/runtime/dist/live/views.js +146 -0
- package/apps/runtime/dist/mcp/handler.js +7 -1
- package/apps/runtime/dist/mcp/tools.js +51 -2
- package/apps/runtime/dist/plugins/jobs.js +7 -0
- package/apps/runtime/dist/routes/api.js +177 -1
- package/apps/runtime/dist/routes/live.js +85 -0
- package/apps/runtime/dist/routes/studio.js +109 -85
- package/apps/runtime/dist/services/cloud.js +39 -5
- package/apps/runtime/dist/services/presence.js +132 -0
- package/apps/runtime/dist/services/projects.js +11 -0
- package/apps/runtime/dist/services/space-data.js +33 -6
- package/apps/runtime/dist/sync/apply.js +43 -0
- package/apps/runtime/dist/sync/client.js +973 -0
- package/apps/runtime/dist/sync/hub.js +324 -0
- package/apps/runtime/dist/sync/log.js +74 -0
- package/apps/runtime/dist/sync/records.js +943 -0
- package/apps/runtime/dist/sync/state.js +17 -0
- package/apps/runtime/dist/texts.js +2 -0
- package/apps/web/dist/assets/AboutDialog-9VcgySrQ.js +1 -0
- package/apps/web/dist/assets/{ChangelogDialog-BpEIbAZ8.js → ChangelogDialog-BXvT2VMU.js} +1 -1
- package/apps/web/dist/assets/EditorPage-Cvzd0nah.js +4 -0
- package/apps/web/dist/assets/{FlowPreview-APXdRflR.js → FlowPreview-BV1NJ0rF.js} +1 -1
- package/apps/web/dist/assets/{Harness-BsGXMlLg.js → Harness-DYviBlHB.js} +2 -2
- package/apps/web/dist/assets/Marketplace-DTSg7_U7.js +2 -0
- package/apps/web/dist/assets/{NewWizardChannels-0JrRdUFd.js → NewWizardChannels-DiujJzOR.js} +1 -1
- package/apps/web/dist/assets/NewWizardPage-CngUh9g-.js +7 -0
- package/apps/web/dist/assets/OnboardingPage-DFKJnWtw.js +1 -0
- package/apps/web/dist/assets/PreviewPane-C0E9OLzB.js +9 -0
- package/apps/web/dist/assets/ProjectPage-CYDX-JYc.js +1 -0
- package/apps/web/dist/assets/PublicRunner-CkRO_Pw-.js +1 -0
- package/apps/web/dist/assets/{ReadOnly-BraZbEG_.js → ReadOnly-E-h9y_QO.js} +1 -1
- package/apps/web/dist/assets/SettingsPage-BMgP3aRV.js +2 -0
- package/apps/web/dist/assets/SetupPage-DBO_rzj7.js +1 -0
- package/apps/web/dist/assets/{SharePage-Dk7zC5Zo.js → SharePage-BvvmYB5N.js} +1 -1
- package/apps/web/dist/assets/changelog-zllICQ4q.js +1 -0
- package/apps/web/dist/assets/{coins-391m1e4_.js → coins-DQ91VJAB.js} +1 -1
- package/apps/web/dist/assets/index-Bjn557f1.js +20 -0
- package/apps/web/dist/assets/index-DN0VMwsS.css +1 -0
- package/apps/web/dist/assets/{phone-DvgrtyNO.js → phone-jIuRIwyg.js} +1 -1
- package/apps/web/dist/assets/{runners-4OBelIgF.js → runners-DloOxEbh.js} +1 -1
- package/apps/web/dist/assets/session-BpsCkDv6.js +2 -0
- package/apps/web/dist/assets/{settings-menu-xK9A-gaP.js → settings-menu-CoLUNJGQ.js} +1 -1
- package/apps/web/dist/assets/theme-2XjIQXH3.js +11 -0
- package/apps/web/dist/assets/{ui-BVQk2DtW.js → ui-BIWmkPh6.js} +3 -3
- package/apps/web/dist/assets/{upload-BgXbzG6C.js → upload-BcOvBWHS.js} +1 -1
- package/apps/web/dist/assets/{useMutation-DkwSQWoD.js → useMutation-CD7HmAxR.js} +1 -1
- package/apps/web/dist/assets/{volume-2-DHGoe3Cg.js → volume-2-D2To9w5D.js} +1 -1
- package/apps/web/dist/assets/{wrench-Cf_aE3O0.js → wrench-B98ubRvB.js} +1 -1
- package/apps/web/dist/index.html +8 -8
- package/apps/web/dist/mcp/flow.html +2 -2
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
- package/node_modules/@engenty/wizards-shared/dist/live.d.ts +46 -0
- package/node_modules/@engenty/wizards-shared/dist/live.js +9 -0
- package/node_modules/@engenty/wizards-shared/dist/run.d.ts +7 -0
- package/node_modules/@engenty/wizards-shared/dist/run.js +14 -0
- package/node_modules/@engenty/wizards-shared/dist/sync-merge.d.ts +55 -0
- package/node_modules/@engenty/wizards-shared/dist/sync-merge.js +214 -0
- package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +166 -0
- package/node_modules/@engenty/wizards-shared/dist/sync.js +40 -0
- package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +14 -0
- package/node_modules/@engenty/wizards-shared/dist/text-merge.js +137 -0
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/plugin.json +1 -1
- package/apps/web/dist/assets/AboutDialog-B_Ixp_Tb.js +0 -1
- package/apps/web/dist/assets/EditorPage-CKHY4hn4.js +0 -4
- package/apps/web/dist/assets/Marketplace-Dr-Qnb-F.js +0 -2
- package/apps/web/dist/assets/NewWizardPage-9igFL5O8.js +0 -7
- package/apps/web/dist/assets/OnboardingPage-BcK9FUnU.js +0 -1
- package/apps/web/dist/assets/PreviewPane-X4LBqA0D.js +0 -4
- package/apps/web/dist/assets/ProjectPage-CG0i-KhR.js +0 -1
- package/apps/web/dist/assets/PublicRunner-CZR1ziQ4.js +0 -1
- package/apps/web/dist/assets/SettingsPage-Bw4tdoV7.js +0 -2
- package/apps/web/dist/assets/SetupPage-CvkE2aKx.js +0 -1
- package/apps/web/dist/assets/changelog-DDXnAaHm.js +0 -1
- package/apps/web/dist/assets/index-BTUtot4r.js +0 -14
- package/apps/web/dist/assets/index-DcUL6teA.css +0 -1
- package/apps/web/dist/assets/session-DvnGHbDz.js +0 -2
- package/apps/web/dist/assets/theme-D3yDT4QT.js +0 -11
|
@@ -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
|
-
|
|
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
|
}
|
|
@@ -9,6 +9,7 @@ import { publishAndSync, pushSharing } from "../services/cloud.js";
|
|
|
9
9
|
import { ServiceError } from "../services/errors.js";
|
|
10
10
|
import { deleteFile, listFiles, readFileText, writeFile } from "../services/files.js";
|
|
11
11
|
import { marketplaceWizard, searchMarketplace } from "../services/marketplace.js";
|
|
12
|
+
import { markAgent, presentIn } from "../services/presence.js";
|
|
12
13
|
import { defaultProject, listProjects, ownedProject } from "../services/projects.js";
|
|
13
14
|
import { answerRunAsk, answerRunPage, controlRun, reviewRun, runReport, startRun, startTestRun, testRunReport, } from "../services/runs.js";
|
|
14
15
|
import { checkDraftWidget } from "../services/widgets.js";
|
|
@@ -63,8 +64,55 @@ function annotationsOf(config) {
|
|
|
63
64
|
openWorldHint: config.openWorld ?? false,
|
|
64
65
|
};
|
|
65
66
|
}
|
|
67
|
+
/** What a client tells its person when people edit the wizard it just changed. */
|
|
68
|
+
function presentNote(people) {
|
|
69
|
+
const who = people.map(([name, where]) => (where ? `${name} (${where})` : name)).join(", ");
|
|
70
|
+
return `${who} ${people.length > 1 ? "are" : "is"} editing this wizard in the studio right now. Your change is in; their editor merges it with what they type. Tell your user before larger changes.`;
|
|
71
|
+
}
|
|
66
72
|
export function registerTools(server, who) {
|
|
67
73
|
const writer = { source: "mcp", client: who.client };
|
|
74
|
+
/** This client, for this person: how the studio shows it among who is in a wizard. */
|
|
75
|
+
const agent = {
|
|
76
|
+
id: `mcp:${who.client}:${who.userId}`,
|
|
77
|
+
name: who.client,
|
|
78
|
+
client: who.name ?? null,
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* A tool on a wizard marks this client as present there (docs/plans/live-changes.md, 8), and
|
|
82
|
+
* its result says who else is: people and other agents, so the client can tell its person.
|
|
83
|
+
*/
|
|
84
|
+
const withPresence = async (args, readOnly, result) => {
|
|
85
|
+
const wizardId = args?.wizardId;
|
|
86
|
+
if (typeof wizardId !== "string" || !result || typeof result !== "object") {
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
await markAgent("wizard", wizardId, agent, readOnly ? "viewing" : "editing");
|
|
91
|
+
const present = (await presentIn("wizard", wizardId)).filter((e) => e.who !== agent.id);
|
|
92
|
+
if (!present.length) {
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
const editing = present.filter((e) => e.whoKind === "person" && e.state === "editing");
|
|
96
|
+
return {
|
|
97
|
+
...result,
|
|
98
|
+
present: present.map((e) => ({
|
|
99
|
+
name: e.name,
|
|
100
|
+
kind: e.whoKind,
|
|
101
|
+
state: e.state,
|
|
102
|
+
...(e.placeLabel ? { where: e.placeLabel } : {}),
|
|
103
|
+
...(e.client ? { via: e.client } : {}),
|
|
104
|
+
since: e.seenAt,
|
|
105
|
+
})),
|
|
106
|
+
...(editing.length && !readOnly
|
|
107
|
+
? { presentNote: presentNote(editing.map((e) => [e.name, e.placeLabel])) }
|
|
108
|
+
: {}),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
console.error("[mcp] presence:", err);
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
};
|
|
68
116
|
const tool = (name, scope, config, run) => {
|
|
69
117
|
if (!who.scopes.includes(scope)) {
|
|
70
118
|
return;
|
|
@@ -78,7 +126,7 @@ export function registerTools(server, who) {
|
|
|
78
126
|
// The SDK has parsed `args` with `input` before this runs.
|
|
79
127
|
(async (args) => {
|
|
80
128
|
try {
|
|
81
|
-
return ok(await run(args));
|
|
129
|
+
return ok(await withPresence(args, config.readOnly ?? false, await run(args)));
|
|
82
130
|
}
|
|
83
131
|
catch (err) {
|
|
84
132
|
return failure(err);
|
|
@@ -98,7 +146,8 @@ export function registerTools(server, who) {
|
|
|
98
146
|
_meta: flowAppMeta,
|
|
99
147
|
}, (async (args) => {
|
|
100
148
|
try {
|
|
101
|
-
const { result, view } = await run(args);
|
|
149
|
+
const { result: plain, view } = await run(args);
|
|
150
|
+
const result = (await withPresence(args, config.readOnly ?? false, plain));
|
|
102
151
|
return {
|
|
103
152
|
...ok(result),
|
|
104
153
|
structuredContent: result,
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { and, eq } from "drizzle-orm";
|
|
2
2
|
import { control, controlDb, withTenant } from "../db/client.js";
|
|
3
3
|
import { env } from "../env.js";
|
|
4
|
+
import { twoWayActive } from "../sync/state.js";
|
|
5
|
+
import { LOCAL_TENANT } from "../tenants/tenant.js";
|
|
4
6
|
import { loadedPlugins, pluginIdsOf } from "./registry.js";
|
|
5
7
|
/**
|
|
6
8
|
* Plugins' jobs (`server.every`). A tick looks once a minute which job is due for which tenant
|
|
@@ -21,6 +23,11 @@ export async function runDueJobs(now = new Date()) {
|
|
|
21
23
|
});
|
|
22
24
|
const started = [];
|
|
23
25
|
for (const tenant of tenants) {
|
|
26
|
+
// An install whose spaces sync both ways leaves the jobs to the cloud: both would write the
|
|
27
|
+
// same items of the same spaces (docs/plans/tenant-sync.md).
|
|
28
|
+
if (twoWayActive() && tenant.id === LOCAL_TENANT) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
24
31
|
const has = await pluginIdsOf(tenant.id);
|
|
25
32
|
for (const { plugin, name, job } of jobs) {
|
|
26
33
|
const id = plugin.source.id;
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import { note } from "@engenty/wizards-shared/run";
|
|
2
|
+
import { blobHash, missingBlobsSchema, pushSchema } from "@engenty/wizards-shared/sync";
|
|
2
3
|
import { PACKAGE_MIME } from "@engenty/wizards-shared/wizard-package";
|
|
3
4
|
import { Hono } from "hono";
|
|
4
5
|
import { bodyLimit } from "hono/body-limit";
|
|
6
|
+
import { streamSSE } from "hono/streaming";
|
|
5
7
|
import { z } from "zod";
|
|
6
8
|
import { balanceCredits } from "../credits/credits.js";
|
|
7
9
|
import { withTenant } from "../db/client.js";
|
|
8
10
|
import { env } from "../env.js";
|
|
11
|
+
import { feature, remoteFeatures } from "../features.js";
|
|
9
12
|
import { allowed } from "../limits.js";
|
|
13
|
+
import { newestSeq } from "../live/feed.js";
|
|
14
|
+
import { nudge } from "../live/hub.js";
|
|
15
|
+
import { followFor, notePush } from "../live/origin.js";
|
|
10
16
|
import { managed, tenantInfo } from "../manage.js";
|
|
11
17
|
import { authenticate, principalOf } from "../mcp/auth.js";
|
|
12
18
|
import { loadedPlugin, pluginIdsOf } from "../plugins/registry.js";
|
|
@@ -19,6 +25,7 @@ import { exportWizard } from "../services/package.js";
|
|
|
19
25
|
import { siteJob, siteSchema, startSiteJob } from "../services/site.js";
|
|
20
26
|
import { checkOnServer, checkSchema, listSyncedSpaces, patchSyncedWizard, removeSyncedSpace, removeSyncedWizard, rotateSyncedLink, syncDataSchema, syncSettingsSchema, syncSpaceData, syncWizard, syncWizardSchema, } from "../services/spaces.js";
|
|
21
27
|
import { createWizard, ownedWizard, publishWizard, writeDraft } from "../services/wizards.js";
|
|
28
|
+
import { adoptSpace, blobBytes, missingBlobs, publishSynced, pullChanges, pushChanges, rotateSynced, syncOverview, takeBlob, } from "../sync/hub.js";
|
|
22
29
|
import { codeOf, tenantStatus } from "../tenants/control.js";
|
|
23
30
|
import { notFoundAnswer, say } from "./lang.js";
|
|
24
31
|
import { dispatchAs } from "./plugins.js";
|
|
@@ -34,7 +41,14 @@ const importSchema = z.object({
|
|
|
34
41
|
publish: z.boolean().default(false),
|
|
35
42
|
});
|
|
36
43
|
/** Runs a call in the caller's tenant, as the caller's role. */
|
|
37
|
-
const inTenantAs = (who, fn) =>
|
|
44
|
+
const inTenantAs = async (who, fn) => {
|
|
45
|
+
try {
|
|
46
|
+
return await withTenant(who.tenantId, () => asRole(who.role, fn));
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
nudge(who.tenantId);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
38
52
|
const HOUR = 60 * 60 * 1000;
|
|
39
53
|
/** Where the account of a managed runtime is looked after: plan, credits, keys. */
|
|
40
54
|
const accountUrl = () => env.manage.url || null;
|
|
@@ -67,6 +81,21 @@ async function caller(c, scopes) {
|
|
|
67
81
|
}
|
|
68
82
|
return who;
|
|
69
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* The two-way sync follows the studio's saves: an install pushes a space at most every few
|
|
86
|
+
* seconds while someone edits, and pulls when a page opens.
|
|
87
|
+
*/
|
|
88
|
+
const TWO_WAY_LIMITS = { push: 1200, pull: 3600 };
|
|
89
|
+
function withinTwoWayLimit(c, who, what) {
|
|
90
|
+
return allowed(`two-way-${what}:${who.tenantId}`, TWO_WAY_LIMITS[what], HOUR)
|
|
91
|
+
? null
|
|
92
|
+
: c.json({ error: say(c, "tooManyTransfersTry"), code: "rate_limited" }, 429);
|
|
93
|
+
}
|
|
94
|
+
/** What one push carries: records, without the files' bytes (they go one by one). */
|
|
95
|
+
const twoWayBody = bodyLimit({
|
|
96
|
+
maxSize: 16 * 1024 * 1024,
|
|
97
|
+
onError: (c) => c.json({ error: "The request is too large.", code: "too_large" }, 413),
|
|
98
|
+
});
|
|
70
99
|
/** A local install sends when it publishes: more than this an hour is not an install at work. */
|
|
71
100
|
function withinSyncLimit(c, who) {
|
|
72
101
|
return allowed(`sync:${who.tenantId}`, 240, HOUR)
|
|
@@ -382,6 +411,153 @@ export const apiRoutes = new Hono()
|
|
|
382
411
|
return who;
|
|
383
412
|
}
|
|
384
413
|
return inTenantAs(who, async () => c.json(await removeSyncedSpace(c.req.param("spaceId"))));
|
|
414
|
+
})
|
|
415
|
+
// --- the two-way sync of a space (docs/manage-contract.md, "Two-way sync of a space") ---
|
|
416
|
+
.get("/sync", async (c) => {
|
|
417
|
+
const who = await caller(c, ["wizards:read"]);
|
|
418
|
+
if (who instanceof Response) {
|
|
419
|
+
return who;
|
|
420
|
+
}
|
|
421
|
+
return inTenantAs(who, async () => c.json(await syncOverview()));
|
|
422
|
+
})
|
|
423
|
+
// What changed in the organization's spaces, as it happens: an install pulls those spaces now
|
|
424
|
+
// instead of at its next round (docs/plans/live-changes.md, 7).
|
|
425
|
+
.get("/sync/live", async (c) => {
|
|
426
|
+
const who = await caller(c, ["wizards:read"]);
|
|
427
|
+
if (who instanceof Response) {
|
|
428
|
+
return who;
|
|
429
|
+
}
|
|
430
|
+
const on = await inTenantAs(who, async () => feature("liveChanges", await remoteFeatures().catch(() => null)));
|
|
431
|
+
if (!on) {
|
|
432
|
+
return c.json(notFoundAnswer(c), 404);
|
|
433
|
+
}
|
|
434
|
+
const install = c.req.header("x-wizards-install") ?? "";
|
|
435
|
+
const raw = c.req.header("last-event-id") ?? c.req.query("since");
|
|
436
|
+
const since = raw && /^\d+$/.test(raw) ? Number(raw) : null;
|
|
437
|
+
c.header("cache-control", "no-cache, no-transform");
|
|
438
|
+
c.header("x-accel-buffering", "no");
|
|
439
|
+
return streamSSE(c, async (stream) => {
|
|
440
|
+
let closed = false;
|
|
441
|
+
let writing = Promise.resolve();
|
|
442
|
+
const write = (event, data, id) => {
|
|
443
|
+
writing = writing.then(() => closed
|
|
444
|
+
? undefined
|
|
445
|
+
: stream.writeSSE({
|
|
446
|
+
event,
|
|
447
|
+
data: JSON.stringify(data),
|
|
448
|
+
...(id === undefined ? {} : { id: String(id) }),
|
|
449
|
+
}));
|
|
450
|
+
};
|
|
451
|
+
const stop = await followFor(who.tenantId, install, since, (e) => {
|
|
452
|
+
const { event, ...data } = e;
|
|
453
|
+
write(event, data, e.seq);
|
|
454
|
+
});
|
|
455
|
+
stream.onAbort(() => {
|
|
456
|
+
closed = true;
|
|
457
|
+
stop();
|
|
458
|
+
});
|
|
459
|
+
const until = Date.now() + 30 * 60_000;
|
|
460
|
+
while (!closed && Date.now() < until) {
|
|
461
|
+
await stream.sleep(Math.min(20_000, until - Date.now()));
|
|
462
|
+
if (!closed) {
|
|
463
|
+
await writing;
|
|
464
|
+
await stream.writeSSE({ event: "ping", data: "" });
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
closed = true;
|
|
468
|
+
stop();
|
|
469
|
+
});
|
|
470
|
+
})
|
|
471
|
+
.get("/sync/spaces/:spaceId/changes", async (c) => {
|
|
472
|
+
const who = await caller(c, ["wizards:read"]);
|
|
473
|
+
if (who instanceof Response) {
|
|
474
|
+
return who;
|
|
475
|
+
}
|
|
476
|
+
const limited = withinTwoWayLimit(c, who, "pull");
|
|
477
|
+
if (limited) {
|
|
478
|
+
return limited;
|
|
479
|
+
}
|
|
480
|
+
const since = Math.max(0, Number.parseInt(c.req.query("since") ?? "0", 10) || 0);
|
|
481
|
+
const cursor = c.req.query("cursor") || undefined;
|
|
482
|
+
return inTenantAs(who, async () => c.json(await pullChanges(c.req.param("spaceId"), since, cursor)));
|
|
483
|
+
})
|
|
484
|
+
.post("/sync/spaces/:spaceId/changes", twoWayBody, async (c) => {
|
|
485
|
+
const who = await caller(c, ["wizards:write"]);
|
|
486
|
+
if (who instanceof Response) {
|
|
487
|
+
return who;
|
|
488
|
+
}
|
|
489
|
+
const limited = withinTwoWayLimit(c, who, "push");
|
|
490
|
+
if (limited) {
|
|
491
|
+
return limited;
|
|
492
|
+
}
|
|
493
|
+
const body = pushSchema.parse(await c.req.json());
|
|
494
|
+
return inTenantAs(who, async () => {
|
|
495
|
+
// The feed numbers this push writes: the live call does not send them back to this install.
|
|
496
|
+
const push = notePush(who.tenantId, c.req.header("x-wizards-install"), await newestSeq());
|
|
497
|
+
try {
|
|
498
|
+
return c.json(await pushChanges(c.req.param("spaceId"), body));
|
|
499
|
+
}
|
|
500
|
+
finally {
|
|
501
|
+
push.done(await newestSeq());
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
})
|
|
505
|
+
.post("/sync/spaces/:spaceId/blobs/missing", async (c) => {
|
|
506
|
+
const who = await caller(c, ["wizards:write"]);
|
|
507
|
+
if (who instanceof Response) {
|
|
508
|
+
return who;
|
|
509
|
+
}
|
|
510
|
+
const body = missingBlobsSchema.parse(await c.req.json());
|
|
511
|
+
return inTenantAs(who, async () => c.json({ missing: await missingBlobs(body.hashes) }));
|
|
512
|
+
})
|
|
513
|
+
.put("/sync/spaces/:spaceId/blobs/:hash", tooLarge, async (c) => {
|
|
514
|
+
const who = await caller(c, ["wizards:write"]);
|
|
515
|
+
if (who instanceof Response) {
|
|
516
|
+
return who;
|
|
517
|
+
}
|
|
518
|
+
const hash = blobHash.parse(c.req.param("hash"));
|
|
519
|
+
const data = new Uint8Array(await c.req.arrayBuffer());
|
|
520
|
+
return inTenantAs(who, async () => {
|
|
521
|
+
await takeBlob(hash, data).catch(() => {
|
|
522
|
+
throw new ServiceError("invalid", "The bytes do not match their hash.");
|
|
523
|
+
});
|
|
524
|
+
return c.json({ ok: true });
|
|
525
|
+
});
|
|
526
|
+
})
|
|
527
|
+
.get("/sync/spaces/:spaceId/blobs/:hash", async (c) => {
|
|
528
|
+
const who = await caller(c, ["wizards:read"]);
|
|
529
|
+
if (who instanceof Response) {
|
|
530
|
+
return who;
|
|
531
|
+
}
|
|
532
|
+
const hash = blobHash.parse(c.req.param("hash"));
|
|
533
|
+
return inTenantAs(who, async () => {
|
|
534
|
+
const data = await blobBytes(hash).catch(() => null);
|
|
535
|
+
if (!data) {
|
|
536
|
+
return c.json({ error: "There are no such bytes here.", code: "not_found" }, 404);
|
|
537
|
+
}
|
|
538
|
+
return c.body(new Uint8Array(data), 200, { "content-type": "application/octet-stream" });
|
|
539
|
+
});
|
|
540
|
+
})
|
|
541
|
+
.post("/sync/spaces/:spaceId/wizards/:wizardId/publish", async (c) => {
|
|
542
|
+
const who = await caller(c, ["wizards:write", "wizards:publish"]);
|
|
543
|
+
if (who instanceof Response) {
|
|
544
|
+
return who;
|
|
545
|
+
}
|
|
546
|
+
return inTenantAs(who, async () => c.json(await publishSynced(who.userId, c.req.param("spaceId"), c.req.param("wizardId"))));
|
|
547
|
+
})
|
|
548
|
+
.post("/sync/spaces/:spaceId/wizards/:wizardId/rotate-link", async (c) => {
|
|
549
|
+
const who = await caller(c, ["wizards:publish"]);
|
|
550
|
+
if (who instanceof Response) {
|
|
551
|
+
return who;
|
|
552
|
+
}
|
|
553
|
+
return inTenantAs(who, async () => c.json(await rotateSynced(who.userId, c.req.param("spaceId"), c.req.param("wizardId"))));
|
|
554
|
+
})
|
|
555
|
+
.post("/sync/spaces/:spaceId/adopt", async (c) => {
|
|
556
|
+
const who = await caller(c, ["wizards:write"]);
|
|
557
|
+
if (who instanceof Response) {
|
|
558
|
+
return who;
|
|
559
|
+
}
|
|
560
|
+
return inTenantAs(who, async () => c.json(await adoptSpace(c.req.param("spaceId"))));
|
|
385
561
|
})
|
|
386
562
|
.post("/wizards/import", tooLarge, async (c) => {
|
|
387
563
|
const authInfo = await authenticate(c.req.raw);
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { streamSSE } from "hono/streaming";
|
|
3
|
+
import { feature, remoteFeatures } from "../features.js";
|
|
4
|
+
import { openStreams, subscribe } from "../live/hub.js";
|
|
5
|
+
import { itemView } from "../live/views.js";
|
|
6
|
+
import { asRole } from "../services/access.js";
|
|
7
|
+
import { requestLang, say } from "./lang.js";
|
|
8
|
+
/** At most this many streams per person and per tenant in one process. */
|
|
9
|
+
export const STREAM_LIMITS = { person: 20, tenant: 200 };
|
|
10
|
+
/** A stream ends after this long; the browser reconnects, and the session is checked again. */
|
|
11
|
+
const LIFETIME_MS = 30 * 60_000;
|
|
12
|
+
const PING_MS = 20_000;
|
|
13
|
+
const perPerson = new Map();
|
|
14
|
+
/**
|
|
15
|
+
* What changed in the tenant while the studio is open (docs/plans/live-changes.md, 3): ids, by
|
|
16
|
+
* the feed's numbers. `Last-Event-ID` or `?since=` resumes after a drop.
|
|
17
|
+
*/
|
|
18
|
+
export const liveRoutes = new Hono().get("/", async (c) => {
|
|
19
|
+
if (!feature("liveChanges", await remoteFeatures().catch(() => null))) {
|
|
20
|
+
return c.json({ error: say(c, "notFound"), code: "not_found" }, 404);
|
|
21
|
+
}
|
|
22
|
+
const user = c.get("user");
|
|
23
|
+
const person = `${user.tenantId}|${user.id}`;
|
|
24
|
+
if ((perPerson.get(person) ?? 0) >= STREAM_LIMITS.person ||
|
|
25
|
+
openStreams(user.tenantId) >= STREAM_LIMITS.tenant) {
|
|
26
|
+
return c.json({ error: say(c, "tooManyStreams"), code: "too_many_streams" }, 429);
|
|
27
|
+
}
|
|
28
|
+
const raw = c.req.header("last-event-id") ?? c.req.query("since");
|
|
29
|
+
const since = raw && /^\d+$/.test(raw) ? Number(raw) : null;
|
|
30
|
+
c.header("cache-control", "no-cache, no-transform");
|
|
31
|
+
c.header("x-accel-buffering", "no");
|
|
32
|
+
perPerson.set(person, (perPerson.get(person) ?? 0) + 1);
|
|
33
|
+
return streamSSE(c, async (stream) => {
|
|
34
|
+
let closed = false;
|
|
35
|
+
const queue = [];
|
|
36
|
+
let writing = Promise.resolve();
|
|
37
|
+
const send = (e) => {
|
|
38
|
+
if (closed) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
queue.push(e);
|
|
42
|
+
writing = writing.then(async () => {
|
|
43
|
+
const next = queue.shift();
|
|
44
|
+
if (!next || closed) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const { event, ...data } = next;
|
|
48
|
+
await stream.writeSSE({
|
|
49
|
+
event,
|
|
50
|
+
data: JSON.stringify(data),
|
|
51
|
+
...("seq" in next ? { id: String(next.seq) } : {}),
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
const reader = { userId: user.id, lang: requestLang(c) };
|
|
56
|
+
const unsubscribe = await subscribe(user.tenantId, since, send, {
|
|
57
|
+
key: `${user.role}|${reader.lang}`,
|
|
58
|
+
read: (x) => asRole(user.role, () => itemView(reader, x)),
|
|
59
|
+
});
|
|
60
|
+
const end = () => {
|
|
61
|
+
if (closed) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
closed = true;
|
|
65
|
+
unsubscribe();
|
|
66
|
+
const left = (perPerson.get(person) ?? 1) - 1;
|
|
67
|
+
if (left > 0) {
|
|
68
|
+
perPerson.set(person, left);
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
perPerson.delete(person);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
stream.onAbort(end);
|
|
75
|
+
const until = Date.now() + LIFETIME_MS;
|
|
76
|
+
while (!closed && Date.now() < until) {
|
|
77
|
+
await stream.sleep(Math.min(PING_MS, until - Date.now()));
|
|
78
|
+
if (!closed) {
|
|
79
|
+
await writing;
|
|
80
|
+
await stream.writeSSE({ event: "ping", data: "" });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
end();
|
|
84
|
+
});
|
|
85
|
+
});
|