@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.
- package/apps/runtime/dist/app.js +18 -2
- package/apps/runtime/dist/db/live-triggers.js +144 -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/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 +14 -0
- package/apps/runtime/dist/db/schema.js +41 -0
- package/apps/runtime/dist/docs/user-guide/meta.json +1 -0
- package/apps/runtime/dist/docs/user-guide/space.md +5 -1
- package/apps/runtime/dist/docs/user-guide/together.md +60 -0
- package/apps/runtime/dist/index.js +5 -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/routes/api.js +71 -2
- package/apps/runtime/dist/routes/live.js +85 -0
- package/apps/runtime/dist/routes/studio.js +47 -85
- package/apps/runtime/dist/services/presence.js +132 -0
- package/apps/runtime/dist/services/space-data.js +33 -6
- package/apps/runtime/dist/sync/apply.js +4 -0
- package/apps/runtime/dist/sync/client.js +146 -1
- package/apps/runtime/dist/texts.js +2 -0
- package/apps/web/dist/assets/AboutDialog-D2r8kBfV.js +1 -0
- package/apps/web/dist/assets/ChangelogDialog-j7Z1YhNv.js +1 -0
- package/apps/web/dist/assets/CodeEditor-BTCMfVFJ.js +2 -0
- package/apps/web/dist/assets/EditorPage-mx6XuEIw.js +3 -0
- package/apps/web/dist/assets/{FlowPreview-dc5C92kK.js → FlowPreview-BtVgtW7P.js} +1 -1
- package/apps/web/dist/assets/{Harness-D0nFOIVx.js → Harness-H4Ue1HOd.js} +2 -2
- package/apps/web/dist/assets/Marketplace-YEZDpGm9.js +2 -0
- package/apps/web/dist/assets/NewWizardChannels-K1HOzkXf.js +1 -0
- package/apps/web/dist/assets/NewWizardPage-DSHVwwnU.js +7 -0
- package/apps/web/dist/assets/OnboardingPage-CoBNtV_1.js +1 -0
- package/apps/web/dist/assets/PreviewPane-z0-Glj7p.js +10 -0
- package/apps/web/dist/assets/ProjectPage-DFaPSeda.js +1 -0
- package/apps/web/dist/assets/PublicRunner-DgT4CApp.js +1 -0
- package/apps/web/dist/assets/ReadOnly-Duk1YpNM.js +1 -0
- package/apps/web/dist/assets/SettingsPage-FimvOhQq.js +2 -0
- package/apps/web/dist/assets/SetupPage-BxEMrMtA.js +1 -0
- package/apps/web/dist/assets/SharePage-DvAUwrOl.js +1 -0
- package/apps/web/dist/assets/changelog-CS9GmnXd.js +1 -0
- package/apps/web/dist/assets/{coins-BGZKYmu6.js → coins-DSvwvqtQ.js} +1 -1
- package/apps/web/dist/assets/dist-BwhPmMDu.js +1 -0
- package/apps/web/dist/assets/dist-DVpDdhG9.js +1 -0
- package/apps/web/dist/assets/dist-DzdNG7Sf.js +10 -0
- package/apps/web/dist/assets/i18n-UTsgNY5M.js +55 -0
- package/apps/web/dist/assets/index-DHIXX69l.js +20 -0
- package/apps/web/dist/assets/index-Mt1sNdPx.css +1 -0
- package/apps/web/dist/assets/json-D2GVvTXK.js +1 -0
- package/apps/web/dist/assets/markdown-DwdMW7q0.js +29 -0
- package/apps/web/dist/assets/{oss-credits-C2JUsf2d.js → oss-credits-BLVLXRzs.js} +1 -1
- package/apps/web/dist/assets/{phone-BzHhwehj.js → phone-xIUU1ZFn.js} +1 -1
- package/apps/web/dist/assets/runners-CrSLA6HI.js +1 -0
- package/apps/web/dist/assets/session-CbWzkHl0.js +2 -0
- package/apps/web/dist/assets/{settings-menu-BZRGhsIO.js → settings-menu-DoRItnPf.js} +1 -1
- package/apps/web/dist/assets/theme-znovbShL.js +11 -0
- package/apps/web/dist/assets/ui-6AgUKJhQ.js +83 -0
- package/apps/web/dist/assets/{upload-CwT8oMz0.js → upload-C8WgcG1g.js} +1 -1
- package/apps/web/dist/assets/{useMutation-byk81dDj.js → useMutation-BdCg6qrc.js} +1 -1
- package/apps/web/dist/assets/{volume-2-B1Pz6Iwt.js → volume-2-jlgQapiz.js} +1 -1
- package/apps/web/dist/assets/{wrench-CvzXRbWN.js → wrench-Ca_TrBQk.js} +1 -1
- package/apps/web/dist/index.html +9 -8
- package/apps/web/dist/mcp/flow.html +2 -2
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +6 -0
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +6 -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 +1 -0
- package/node_modules/@engenty/wizards-shared/dist/run.js +2 -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-D1YHT0jc.js +0 -1
- package/apps/web/dist/assets/ChangelogDialog-Bv02g8av.js +0 -1
- package/apps/web/dist/assets/EditorPage-BThoZwqO.js +0 -4
- package/apps/web/dist/assets/Marketplace-Cnd8BF3q.js +0 -2
- package/apps/web/dist/assets/NewWizardChannels-i62Y_2DZ.js +0 -1
- package/apps/web/dist/assets/NewWizardPage-BcpRA1fx.js +0 -7
- package/apps/web/dist/assets/OnboardingPage-BcMDEXNq.js +0 -1
- package/apps/web/dist/assets/PreviewPane-GHcVV2Hu.js +0 -4
- package/apps/web/dist/assets/ProjectPage-TDywzUOd.js +0 -1
- package/apps/web/dist/assets/PublicRunner-B6JINLpR.js +0 -1
- package/apps/web/dist/assets/ReadOnly-Mv5M2OV9.js +0 -1
- package/apps/web/dist/assets/SettingsPage-B-F1dLgt.js +0 -2
- package/apps/web/dist/assets/SetupPage-CVdsdVBW.js +0 -1
- package/apps/web/dist/assets/SharePage-CBSRK0wF.js +0 -1
- package/apps/web/dist/assets/changelog-BR1lxaWv.js +0 -1
- package/apps/web/dist/assets/index-D3-kv1WF.js +0 -14
- package/apps/web/dist/assets/index-DcUL6teA.css +0 -1
- package/apps/web/dist/assets/runners-C1-zIlry.js +0 -1
- package/apps/web/dist/assets/session-B_JeZnJ0.js +0 -2
- package/apps/web/dist/assets/theme-HcCfZDzS.js +0 -11
- package/apps/web/dist/assets/ui-BI1RPFWT.js +0 -137
|
@@ -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,
|
|
@@ -3,11 +3,16 @@ import { blobHash, missingBlobsSchema, pushSchema } from "@engenty/wizards-share
|
|
|
3
3
|
import { PACKAGE_MIME } from "@engenty/wizards-shared/wizard-package";
|
|
4
4
|
import { Hono } from "hono";
|
|
5
5
|
import { bodyLimit } from "hono/body-limit";
|
|
6
|
+
import { streamSSE } from "hono/streaming";
|
|
6
7
|
import { z } from "zod";
|
|
7
8
|
import { balanceCredits } from "../credits/credits.js";
|
|
8
9
|
import { withTenant } from "../db/client.js";
|
|
9
10
|
import { env } from "../env.js";
|
|
11
|
+
import { feature, remoteFeatures } from "../features.js";
|
|
10
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";
|
|
11
16
|
import { managed, tenantInfo } from "../manage.js";
|
|
12
17
|
import { authenticate, principalOf } from "../mcp/auth.js";
|
|
13
18
|
import { loadedPlugin, pluginIdsOf } from "../plugins/registry.js";
|
|
@@ -36,7 +41,14 @@ const importSchema = z.object({
|
|
|
36
41
|
publish: z.boolean().default(false),
|
|
37
42
|
});
|
|
38
43
|
/** Runs a call in the caller's tenant, as the caller's role. */
|
|
39
|
-
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
|
+
};
|
|
40
52
|
const HOUR = 60 * 60 * 1000;
|
|
41
53
|
/** Where the account of a managed runtime is looked after: plan, credits, keys. */
|
|
42
54
|
const accountUrl = () => env.manage.url || null;
|
|
@@ -407,6 +419,54 @@ export const apiRoutes = new Hono()
|
|
|
407
419
|
return who;
|
|
408
420
|
}
|
|
409
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
|
+
});
|
|
410
470
|
})
|
|
411
471
|
.get("/sync/spaces/:spaceId/changes", async (c) => {
|
|
412
472
|
const who = await caller(c, ["wizards:read"]);
|
|
@@ -431,7 +491,16 @@ export const apiRoutes = new Hono()
|
|
|
431
491
|
return limited;
|
|
432
492
|
}
|
|
433
493
|
const body = pushSchema.parse(await c.req.json());
|
|
434
|
-
return inTenantAs(who, async () =>
|
|
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
|
+
});
|
|
435
504
|
})
|
|
436
505
|
.post("/sync/spaces/:spaceId/blobs/missing", async (c) => {
|
|
437
506
|
const who = await caller(c, ["wizards:write"]);
|
|
@@ -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
|
+
});
|
|
@@ -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,
|
|
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,
|
|
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,
|
|
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,18 +53,19 @@ 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,
|
|
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,
|
|
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,
|
|
66
|
+
import { deleteTranslation, editTranslation, isLangCode, publishedDefinition, } from "../services/translations.js";
|
|
65
67
|
import { draftWidgetPreview } from "../services/widgets.js";
|
|
66
|
-
import { createWizard, deleteWizard, draftChanges, duplicateWizard,
|
|
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";
|
|
69
71
|
import { keepCloudForAll, mergesSeen, proposeMerge, resolveConflict, startSpace, stopSpace, syncAll, syncView, undoMerge, } from "../sync/client.js";
|
|
@@ -73,6 +75,16 @@ import { serverText } from "../texts.js";
|
|
|
73
75
|
import { applyUpdate, updateStatus } from "../update.js";
|
|
74
76
|
import { bareMime, byteRange } from "./delivery.js";
|
|
75
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) });
|
|
76
88
|
/** The model sources a test call has worked on: the setup is done for those, not for the others. */
|
|
77
89
|
async function testedSources() {
|
|
78
90
|
const tested = await readSetting("setup-done");
|
|
@@ -545,24 +557,7 @@ export const studio = new Hono()
|
|
|
545
557
|
});
|
|
546
558
|
})
|
|
547
559
|
// --- projects --------------------------------------------------------------
|
|
548
|
-
.get("/projects", async (c) =>
|
|
549
|
-
const projects = await listProjects(c.get("user").id, requestLang(c));
|
|
550
|
-
const build = await mayBuild();
|
|
551
|
-
return c.json(projects.map((p) => ({
|
|
552
|
-
id: p.id,
|
|
553
|
-
name: p.name,
|
|
554
|
-
brand: p.brand,
|
|
555
|
-
facts: p.facts,
|
|
556
|
-
/** The space's public page; null until it is set up. */
|
|
557
|
-
page: p.page ?? null,
|
|
558
|
-
mcpServers: maskedServers(p),
|
|
559
|
-
wizardCount: p.wizardCount,
|
|
560
|
-
/** `local`: synced from a local install, where it is changed. */
|
|
561
|
-
origin: p.origin,
|
|
562
|
-
syncedAt: p.syncedAt?.toISOString() ?? null,
|
|
563
|
-
readOnly: p.origin === "local" || !build,
|
|
564
|
-
})));
|
|
565
|
-
})
|
|
560
|
+
.get("/projects", async (c) => c.json(await spacesView(reader(c))))
|
|
566
561
|
.post("/projects", async (c) => {
|
|
567
562
|
const body = z.object({ name: z.string().min(1).max(80) }).parse(await c.req.json());
|
|
568
563
|
return c.json(await createProject(c.get("user").id, body.name));
|
|
@@ -585,14 +580,7 @@ export const studio = new Hono()
|
|
|
585
580
|
return c.json({ ok: true });
|
|
586
581
|
})
|
|
587
582
|
// --- what a project holds for all its wizards: logos, assets, documents -------
|
|
588
|
-
.get("/projects/:id/files", async (c) =>
|
|
589
|
-
const project = await ownedProject(c.get("user").id, c.req.param("id"));
|
|
590
|
-
return c.json({
|
|
591
|
-
files: (await projectFiles(project.id)).map(fileView),
|
|
592
|
-
/** Whether documents get vectors, or the index works on keywords alone. */
|
|
593
|
-
embeddings: Boolean(await embeddingModel().catch(() => null)),
|
|
594
|
-
});
|
|
595
|
-
})
|
|
583
|
+
.get("/projects/:id/files", async (c) => c.json(await filesView(reader(c), c.req.param("id"))))
|
|
596
584
|
.post("/projects/:id/files", async (c) => {
|
|
597
585
|
const project = await ownedProject(c.get("user").id, c.req.param("id"));
|
|
598
586
|
const kind = z.enum(PROJECT_FILE_KINDS).parse(c.req.query("kind"));
|
|
@@ -759,10 +747,7 @@ export const studio = new Hono()
|
|
|
759
747
|
.parse(await c.req.json());
|
|
760
748
|
return c.json(await previewSource(body));
|
|
761
749
|
})
|
|
762
|
-
.get("/projects/:id/connectors", async (c) =>
|
|
763
|
-
const project = await ownedProject(c.get("user").id, c.req.param("id"));
|
|
764
|
-
return c.json(await listConnectors(project.id));
|
|
765
|
-
})
|
|
750
|
+
.get("/projects/:id/connectors", async (c) => c.json(await connectorsView(reader(c), c.req.param("id"))))
|
|
766
751
|
.post("/projects/:id/connectors", async (c) => {
|
|
767
752
|
const user = c.get("user");
|
|
768
753
|
const project = await ownedProject(user.id, c.req.param("id"));
|
|
@@ -983,10 +968,10 @@ export const studio = new Hono()
|
|
|
983
968
|
parentId: z.string().nullish(),
|
|
984
969
|
markdown: z.string().optional(),
|
|
985
970
|
review: z.null().optional(),
|
|
971
|
+
baseUpdatedAt: z.string().max(40).optional(),
|
|
986
972
|
})
|
|
987
973
|
.parse(await c.req.json());
|
|
988
|
-
await updatePage(c.get("user").id, c.req.param("id"), body);
|
|
989
|
-
return c.json({ ok: true });
|
|
974
|
+
return c.json({ ok: true, ...(await updatePage(c.get("user").id, c.req.param("id"), body)) });
|
|
990
975
|
})
|
|
991
976
|
.put("/pages/:id/order", async (c) => {
|
|
992
977
|
const { ids } = z.object({ ids: z.array(z.string()).max(5000) }).parse(await c.req.json());
|
|
@@ -998,14 +983,7 @@ export const studio = new Hono()
|
|
|
998
983
|
return c.json({ ok: true });
|
|
999
984
|
})
|
|
1000
985
|
// --- wizards ---------------------------------------------------------------
|
|
1001
|
-
.get("/projects/:id/wizards", async (c) =>
|
|
1002
|
-
const user = c.get("user");
|
|
1003
|
-
await ownedProject(user.id, c.req.param("id"));
|
|
1004
|
-
const wizards = await listWizards(user.id, c.req.param("id"));
|
|
1005
|
-
// A local install with an account: where each wizard stands in its cloud, for the cards.
|
|
1006
|
-
const linked = await cloudLinked();
|
|
1007
|
-
return c.json(await Promise.all(wizards.map(async (w) => ({ ...w, cloud: linked ? await cloudState(w.id) : null }))));
|
|
1008
|
-
})
|
|
986
|
+
.get("/projects/:id/wizards", async (c) => c.json(await wizardsView(reader(c), c.req.param("id"))))
|
|
1009
987
|
.post("/wizards", async (c) => {
|
|
1010
988
|
const body = z
|
|
1011
989
|
.object({
|
|
@@ -1053,27 +1031,7 @@ export const studio = new Hono()
|
|
|
1053
1031
|
const w = await ownedWizard(user.id, c.req.param("id"));
|
|
1054
1032
|
return c.json(await sharePreview(w, user.id, c.req.query("step") || null, c.req.query("as") === "owner", requestLang(c)));
|
|
1055
1033
|
})
|
|
1056
|
-
.get("/wizards/:id", async (c) =>
|
|
1057
|
-
const user = c.get("user");
|
|
1058
|
-
const w = await ownedWizard(user.id, c.req.param("id"));
|
|
1059
|
-
const messages = await wizardMessages(w.id);
|
|
1060
|
-
const project = await ownedProject(user.id, w.projectId);
|
|
1061
|
-
return c.json({
|
|
1062
|
-
...(await wizardState(w)),
|
|
1063
|
-
/** Shown and run here, changed elsewhere: a local install's wizard, or nothing is built here. */
|
|
1064
|
-
readOnly: !(await projectWritable(project)),
|
|
1065
|
-
blank: messages.length === 0 && !w.starter,
|
|
1066
|
-
messages: messages.map((m) => ({
|
|
1067
|
-
id: m.id,
|
|
1068
|
-
role: m.role,
|
|
1069
|
-
content: m.content,
|
|
1070
|
-
changed: m.changed,
|
|
1071
|
-
source: m.source,
|
|
1072
|
-
client: m.client,
|
|
1073
|
-
})),
|
|
1074
|
-
mcpServers: project.mcpServers.map((s) => ({ id: s.id, name: s.name })),
|
|
1075
|
-
});
|
|
1076
|
-
})
|
|
1034
|
+
.get("/wizards/:id", async (c) => c.json(await wizardView(reader(c), c.req.param("id"))))
|
|
1077
1035
|
.put("/wizards/:id/draft", async (c) => {
|
|
1078
1036
|
const body = z
|
|
1079
1037
|
.object({ definition: z.unknown(), baseRevision: z.number().int().min(0) })
|
|
@@ -1102,20 +1060,7 @@ export const studio = new Hono()
|
|
|
1102
1060
|
return c.json({ ok: true });
|
|
1103
1061
|
})
|
|
1104
1062
|
// The languages the published wizard is kept in, each original text with its translation.
|
|
1105
|
-
.get("/wizards/:id/translations", async (c) =>
|
|
1106
|
-
const w = await ownedWizard(c.get("user").id, c.req.param("id"));
|
|
1107
|
-
const def = await publishedDefinition(w);
|
|
1108
|
-
const kept = await translationsOf(w.id);
|
|
1109
|
-
return c.json({
|
|
1110
|
-
lang: def ? wizardLang(def) : wizardLang(w.draft),
|
|
1111
|
-
texts: def ? wizardTexts(def) : [],
|
|
1112
|
-
translations: kept.map((t) => ({
|
|
1113
|
-
lang: t.lang,
|
|
1114
|
-
texts: t.texts,
|
|
1115
|
-
updatedAt: t.updatedAt.toISOString(),
|
|
1116
|
-
})),
|
|
1117
|
-
});
|
|
1118
|
-
})
|
|
1063
|
+
.get("/wizards/:id/translations", async (c) => c.json(await translationsView(reader(c), c.req.param("id"))))
|
|
1119
1064
|
// The author's own lines for a language: they replace what a model wrote.
|
|
1120
1065
|
.put("/wizards/:id/translations/:lang", async (c) => {
|
|
1121
1066
|
const w = await writableWizard(c.get("user").id, c.req.param("id"));
|
|
@@ -1210,6 +1155,23 @@ export const studio = new Hono()
|
|
|
1210
1155
|
return c.json(await checkForCloud(c.get("user").id, c.req.param("id")));
|
|
1211
1156
|
})
|
|
1212
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
|
+
})
|
|
1213
1175
|
.get("/sync", async (c) => (managed ? c.notFound() : c.json(await syncView())))
|
|
1214
1176
|
.post("/sync/now", async (c) => {
|
|
1215
1177
|
if (managed) {
|
|
@@ -1286,7 +1248,7 @@ export const studio = new Hono()
|
|
|
1286
1248
|
const abort = new AbortController();
|
|
1287
1249
|
stream.onAbort(() => abort.abort());
|
|
1288
1250
|
try {
|
|
1289
|
-
const result = await architectTurn(user.id, wizardId, message, requestLang(c), {
|
|
1251
|
+
const result = await asAssistantIn(wizardId, user, () => architectTurn(user.id, wizardId, message, requestLang(c), {
|
|
1290
1252
|
signal: abort.signal,
|
|
1291
1253
|
onText: (delta) => {
|
|
1292
1254
|
void stream.writeSSE({ event: "text", data: JSON.stringify(delta) });
|
|
@@ -1300,7 +1262,7 @@ export const studio = new Hono()
|
|
|
1300
1262
|
onBuilding: () => {
|
|
1301
1263
|
void stream.writeSSE({ event: "building", data: "1" });
|
|
1302
1264
|
},
|
|
1303
|
-
});
|
|
1265
|
+
}));
|
|
1304
1266
|
await stream.writeSSE({ event: "done", data: JSON.stringify(result) });
|
|
1305
1267
|
}
|
|
1306
1268
|
catch (err) {
|
|
@@ -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
|
+
}
|