wizards 0.2.56 → 0.2.58
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/db/control-schema.js +13 -0
- package/apps/runtime/dist/db/migrations/control/0008_runner.sql +8 -0
- package/apps/runtime/dist/db/migrations/control/meta/0008_snapshot.json +505 -0
- package/apps/runtime/dist/db/migrations/control/meta/_journal.json +7 -0
- package/apps/runtime/dist/db/migrations/tenant/0014_run_answer.sql +2 -0
- package/apps/runtime/dist/db/migrations/tenant/0015_device_calls.sql +13 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0014_snapshot.json +3154 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0015_snapshot.json +3243 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +14 -0
- package/apps/runtime/dist/db/schema.js +23 -0
- package/apps/runtime/dist/engine/asks.js +53 -33
- package/apps/runtime/dist/engine/device.js +61 -49
- package/apps/runtime/dist/engine/events.js +71 -4
- package/apps/runtime/dist/engine/owner.js +32 -0
- package/apps/runtime/dist/engine/runner.js +94 -79
- package/apps/runtime/dist/env.js +19 -0
- package/apps/runtime/dist/index.js +13 -2
- package/apps/runtime/dist/models.js +1 -1
- package/apps/runtime/dist/plugins/runs.js +5 -8
- package/apps/runtime/dist/routes/runs.js +31 -15
- package/apps/runtime/dist/services/runs.js +7 -8
- package/apps/runtime/dist/tenants/control.js +85 -7
- package/apps/web/dist/assets/{AboutDialog-Bv7p9iGr.js → AboutDialog-eIamCG0d.js} +1 -1
- package/apps/web/dist/assets/{ChangelogDialog-D4sBrhi-.js → ChangelogDialog-Cbv1DEkz.js} +1 -1
- package/apps/web/dist/assets/{ChatView-Bntm0u8V.js → ChatView-B1Thux1N.js} +1 -1
- package/apps/web/dist/assets/{EditorPage-DaVeNzHU.js → EditorPage-Ck1Hq5Ke.js} +1 -1
- package/apps/web/dist/assets/{FlowPreview-C0tTz51A.js → FlowPreview-D5W8dDxx.js} +1 -1
- package/apps/web/dist/assets/{Harness-De-PsLFA.js → Harness-Bhq2tE15.js} +1 -1
- package/apps/web/dist/assets/{Marketplace-7Bdv7Gd5.js → Marketplace-C-Nr-SaJ.js} +2 -2
- package/apps/web/dist/assets/{NewWizardPage-CV7jrSkz.js → NewWizardPage-DgSPRlcs.js} +1 -1
- package/apps/web/dist/assets/{ProjectPage-CBCd24oM.js → ProjectPage-xsMCXYyc.js} +1 -1
- package/apps/web/dist/assets/{PublicRunner-CVmkHSnC.js → PublicRunner-wW-52s2_.js} +1 -1
- package/apps/web/dist/assets/{RunDrawer-CvzuYc0d.js → RunDrawer-i9BHc1lO.js} +1 -1
- package/apps/web/dist/assets/{RunnerView-BtZp1FD6.js → RunnerView-DpVGsCA8.js} +1 -1
- package/apps/web/dist/assets/{SettingsPage--Zj2pTgf.js → SettingsPage-Ro_z_14X.js} +1 -1
- package/apps/web/dist/assets/{SetupPage-F_e8f1to.js → SetupPage-CXbXu-xu.js} +1 -1
- package/apps/web/dist/assets/{SharePage-DLivbYu6.js → SharePage-DwHMZwlW.js} +1 -1
- package/apps/web/dist/assets/changelog-BrLNXOV8.js +1 -0
- package/apps/web/dist/assets/{esm-BMtXxAe0.js → esm-CuG3O0f6.js} +1 -1
- package/apps/web/dist/assets/{index-MlQy_Qoy.js → index-BUUosGDd.js} +4 -4
- package/apps/web/dist/assets/{settings-menu-JtMfy9en.js → settings-menu-Bf9lWtfx.js} +1 -1
- package/apps/web/dist/index.html +2 -2
- package/node_modules/@engenty-wizards/shared/dist/definition.js +1 -0
- package/node_modules/@engenty-wizards/shared/dist/engenty/data-tables/columns.js +1 -0
- package/node_modules/@engenty-wizards/shared/dist/fit.js +1 -0
- package/node_modules/@engenty-wizards/shared/dist/store.js +1 -0
- package/node_modules/@engenty-wizards/shared/dist/surface.js +1 -0
- package/package.json +1 -1
- package/apps/web/dist/assets/changelog-CWualFcc.js +0 -1
|
@@ -18,10 +18,11 @@ import { runEnded } from "../plugins/events.js";
|
|
|
18
18
|
import { projectFiles } from "../services/project-files.js";
|
|
19
19
|
import { projectProfile } from "../services/projects.js";
|
|
20
20
|
import { listRows, scopeOf } from "../store/index.js";
|
|
21
|
-
import {
|
|
21
|
+
import { claimRun, disownRuns, heartbeatRuns, indexRun, restRun, waitingRuns, wakeRun, } from "../tenants/control.js";
|
|
22
22
|
import { currentTenant } from "../tenants/tenant.js";
|
|
23
|
-
import { askPerson, clearStaleAsk
|
|
23
|
+
import { askPerson, clearStaleAsk } from "./asks.js";
|
|
24
24
|
import { decide } from "./decide.js";
|
|
25
|
+
import { clearDeviceCalls } from "./device.js";
|
|
25
26
|
import { emitEvent, recentEvents, signalChanged } from "./events.js";
|
|
26
27
|
import { readPageInput } from "./input.js";
|
|
27
28
|
import { pushRun } from "./push.js";
|
|
@@ -45,10 +46,15 @@ export class NoCreditsError extends Error {
|
|
|
45
46
|
super("Dieser Wizard hat gerade kein Guthaben mehr. Bitte später erneut versuchen.");
|
|
46
47
|
}
|
|
47
48
|
}
|
|
49
|
+
/** The runs this process drives right now, with the handle that stops each. */
|
|
48
50
|
const active = new Map();
|
|
49
|
-
// ---
|
|
50
|
-
//
|
|
51
|
-
|
|
51
|
+
// --- the line ------------------------------------------------------------------
|
|
52
|
+
// A run that wants work is marked in the control database (`wakeRun`); a runner claims it there,
|
|
53
|
+
// so several processes share one line. A tenant's runs beyond its limit stay in line; nothing is
|
|
54
|
+
// refused. See docs/plans/runner-process.md.
|
|
55
|
+
/** How often a runner looks at the line, and how often it reports on the runs it holds. */
|
|
56
|
+
const POLL_MS = 2000;
|
|
57
|
+
const HEARTBEAT_MS = 10_000;
|
|
52
58
|
async function concurrencyLimit(tenant) {
|
|
53
59
|
if (!managed) {
|
|
54
60
|
return env.limits.concurrentRuns;
|
|
@@ -56,45 +62,6 @@ async function concurrencyLimit(tenant) {
|
|
|
56
62
|
const info = await tenantInfo(tenant).catch(() => null);
|
|
57
63
|
return info?.limits.concurrentRuns || env.limits.concurrentRuns;
|
|
58
64
|
}
|
|
59
|
-
async function acquireSlot(tenant, signal) {
|
|
60
|
-
const limit = await concurrencyLimit(tenant);
|
|
61
|
-
let slot = slots.get(tenant);
|
|
62
|
-
if (!slot) {
|
|
63
|
-
slot = { busy: 0, waiting: [] };
|
|
64
|
-
slots.set(tenant, slot);
|
|
65
|
-
}
|
|
66
|
-
if (slot.busy < limit) {
|
|
67
|
-
slot.busy++;
|
|
68
|
-
return true;
|
|
69
|
-
}
|
|
70
|
-
const queue = slot.waiting;
|
|
71
|
-
return new Promise((resolve) => {
|
|
72
|
-
const go = () => {
|
|
73
|
-
signal.removeEventListener("abort", stop);
|
|
74
|
-
resolve(true);
|
|
75
|
-
};
|
|
76
|
-
const stop = () => {
|
|
77
|
-
queue.splice(queue.indexOf(go), 1);
|
|
78
|
-
resolve(false);
|
|
79
|
-
};
|
|
80
|
-
queue.push(go);
|
|
81
|
-
signal.addEventListener("abort", stop, { once: true });
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
function releaseSlot(tenant) {
|
|
85
|
-
const slot = slots.get(tenant);
|
|
86
|
-
if (!slot) {
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
const next = slot.waiting.shift();
|
|
90
|
-
if (next) {
|
|
91
|
-
// The slot passes straight to the next run in line.
|
|
92
|
-
next();
|
|
93
|
-
}
|
|
94
|
-
else {
|
|
95
|
-
slot.busy--;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
65
|
async function loadRun(runId) {
|
|
99
66
|
return db.query.run.findFirst({ where: eq(schema.run.id, runId) });
|
|
100
67
|
}
|
|
@@ -198,6 +165,7 @@ export async function createRun(input) {
|
|
|
198
165
|
userId: input.userId ?? null,
|
|
199
166
|
ipHash: input.ipHash ?? null,
|
|
200
167
|
origin: input.origin ?? null,
|
|
168
|
+
unattended: input.unattended ?? false,
|
|
201
169
|
status: first.type === "page" ? "waiting_input" : "running",
|
|
202
170
|
cursor: first.id,
|
|
203
171
|
state,
|
|
@@ -212,37 +180,97 @@ export async function createRun(input) {
|
|
|
212
180
|
}
|
|
213
181
|
return id;
|
|
214
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* Puts the run to work: in line in the control database, and — when this process is a runner —
|
|
185
|
+
* taken at once if the tenant has a slot. The web alone leaves it for a runner's next look.
|
|
186
|
+
*/
|
|
215
187
|
export function kick(runId) {
|
|
188
|
+
const tenant = currentTenant();
|
|
189
|
+
void wakeRun(runId)
|
|
190
|
+
.then(() => {
|
|
191
|
+
if (env.role !== "web") {
|
|
192
|
+
return take(runId, tenant);
|
|
193
|
+
}
|
|
194
|
+
})
|
|
195
|
+
.catch((err) => console.error(`[run ${runId}]`, err));
|
|
196
|
+
}
|
|
197
|
+
/** Claims the run for this process and drives it; nothing when another holds it or the tenant is full. */
|
|
198
|
+
async function take(runId, tenant) {
|
|
216
199
|
if (active.has(runId)) {
|
|
217
200
|
return;
|
|
218
201
|
}
|
|
202
|
+
if (!(await claimRun(runId, tenant, await concurrencyLimit(tenant)))) {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
219
205
|
const abort = new AbortController();
|
|
220
206
|
active.set(runId, abort);
|
|
221
|
-
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
work()
|
|
207
|
+
// The heartbeat keeps the claim and hears of a cancel the web wrote while a step works.
|
|
208
|
+
const beat = setInterval(() => {
|
|
209
|
+
void heartbeatRuns([runId]).catch(() => undefined);
|
|
210
|
+
void withTenant(tenant, () => loadRun(runId))
|
|
211
|
+
.then((run) => {
|
|
212
|
+
if (run && run.status !== "running") {
|
|
213
|
+
abort.abort();
|
|
214
|
+
}
|
|
215
|
+
})
|
|
216
|
+
.catch(() => undefined);
|
|
217
|
+
}, HEARTBEAT_MS);
|
|
218
|
+
beat.unref();
|
|
219
|
+
await withTenant(tenant, () => drive(runId, abort.signal))
|
|
235
220
|
.catch(async (err) => {
|
|
236
221
|
console.error(`[run ${runId}]`, err);
|
|
237
|
-
await updateRun(runId, { status: "failed", error: friendly(err) }).catch(() => undefined);
|
|
222
|
+
await withTenant(tenant, () => updateRun(runId, { status: "failed", error: friendly(err) })).catch(() => undefined);
|
|
238
223
|
})
|
|
239
224
|
.finally(async () => {
|
|
225
|
+
clearInterval(beat);
|
|
240
226
|
active.delete(runId);
|
|
241
|
-
await
|
|
242
|
-
|
|
243
|
-
|
|
227
|
+
await withTenant(tenant, () => releaseResources(runId));
|
|
228
|
+
// A run the shutdown stopped goes back in line for the next runner; the rest is done for now.
|
|
229
|
+
if (!stopping) {
|
|
230
|
+
await restRun(runId).catch(() => undefined);
|
|
231
|
+
}
|
|
232
|
+
withTenant(tenant, () => signalChanged(runId));
|
|
233
|
+
// A slot came free: the next run of the line need not wait for the poll.
|
|
234
|
+
void lookAtLine();
|
|
244
235
|
});
|
|
245
236
|
}
|
|
237
|
+
let stopping = false;
|
|
238
|
+
let looking = false;
|
|
239
|
+
/** Takes what waits in line, run by run; each claim counts the tenant's limit by itself. */
|
|
240
|
+
async function lookAtLine() {
|
|
241
|
+
if (looking || stopping) {
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
looking = true;
|
|
245
|
+
try {
|
|
246
|
+
for (const r of await waitingRuns()) {
|
|
247
|
+
if (stopping) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
await take(r.runId, r.tenantId).catch((err) => console.error(`[line ${r.runId}]`, err));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
catch (err) {
|
|
254
|
+
console.error("[line]", err);
|
|
255
|
+
}
|
|
256
|
+
finally {
|
|
257
|
+
looking = false;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/** A runner: looks at the line every POLL_MS, from now on. Runs a stopped process left behind are in it. */
|
|
261
|
+
export function startRunner() {
|
|
262
|
+
const timer = setInterval(() => void lookAtLine(), POLL_MS);
|
|
263
|
+
timer.unref();
|
|
264
|
+
void lookAtLine();
|
|
265
|
+
}
|
|
266
|
+
/** Stops the runs this process holds and hands them back to the line. */
|
|
267
|
+
export async function stopRunner() {
|
|
268
|
+
stopping = true;
|
|
269
|
+
for (const abort of active.values()) {
|
|
270
|
+
abort.abort();
|
|
271
|
+
}
|
|
272
|
+
await disownRuns().catch(() => undefined);
|
|
273
|
+
}
|
|
246
274
|
/** What conditions read in this run: answers, outputs, and how many rows each stored list has. */
|
|
247
275
|
async function flowValues(run, state) {
|
|
248
276
|
const counts = {};
|
|
@@ -322,9 +350,7 @@ async function makeContext(run, project, state, signal) {
|
|
|
322
350
|
projectFiles: (await projectFiles(project.id)).filter((f) => f.status === "ready"),
|
|
323
351
|
signal,
|
|
324
352
|
resources,
|
|
325
|
-
ask: (ask) => unattended.
|
|
326
|
-
? Promise.resolve(null)
|
|
327
|
-
: askPerson(run.id, { ...ask, stepId }, signal),
|
|
353
|
+
ask: (ask) => run.unattended ? Promise.resolve(null) : askPerson(run.id, { ...ask, stepId }, signal),
|
|
328
354
|
emit: (type, message, asset) => emitEvent(run.id, run.cursor, type, message, asset),
|
|
329
355
|
call: { runId: run.id, stepId },
|
|
330
356
|
chargeUsd: (usd) => addLocalCost(run.id, stepId, usd),
|
|
@@ -476,7 +502,10 @@ async function decidePageFields(run, page, state, signal) {
|
|
|
476
502
|
.map((f) => f.id);
|
|
477
503
|
}
|
|
478
504
|
async function drive(runId, signal) {
|
|
505
|
+
// The step starts afresh here: a question or a device call another process left has no one
|
|
506
|
+
// waiting.
|
|
479
507
|
await clearStaleAsk(runId);
|
|
508
|
+
await clearDeviceCalls(runId);
|
|
480
509
|
while (!signal.aborted) {
|
|
481
510
|
const run = await loadRun(runId);
|
|
482
511
|
if (run?.status !== "running") {
|
|
@@ -575,20 +604,6 @@ async function drive(runId, signal) {
|
|
|
575
604
|
}
|
|
576
605
|
}
|
|
577
606
|
}
|
|
578
|
-
/** Runs a restart left mid-step go on where they were. */
|
|
579
|
-
export async function resumeInterruptedRuns() {
|
|
580
|
-
for (const r of await activeRuns()) {
|
|
581
|
-
await withTenant(r.tenantId, async () => {
|
|
582
|
-
const run = await loadRun(r.runId);
|
|
583
|
-
if (run?.status === "running") {
|
|
584
|
-
kick(r.runId);
|
|
585
|
-
}
|
|
586
|
-
else {
|
|
587
|
-
await markRunActive(r.runId, false);
|
|
588
|
-
}
|
|
589
|
-
}).catch((err) => console.error(`[resume ${r.runId}]`, err));
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
607
|
// --- commands ----------------------------------------------------------------
|
|
593
608
|
async function requireWaiting(runId, stepId) {
|
|
594
609
|
const run = await loadRun(runId);
|
package/apps/runtime/dist/env.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
3
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { hostname } from "node:os";
|
|
4
5
|
import { join, resolve } from "node:path";
|
|
5
6
|
import { findChrome } from "./render/browser-path.js";
|
|
6
7
|
/** Load `.env.local` then `.env` without overriding the real environment. */
|
|
@@ -92,6 +93,13 @@ const port = num("API_PORT", 24368);
|
|
|
92
93
|
/** From source the Vite dev server on :5181 serves the pages; built, this server does. */
|
|
93
94
|
const fromSource = import.meta.url.endsWith(".ts");
|
|
94
95
|
const sandboxImage = str("SANDBOX_IMAGE", "engenty-sandbox:latest");
|
|
96
|
+
function role() {
|
|
97
|
+
const given = str("RUNTIME_ROLE", "all");
|
|
98
|
+
if (given !== "web" && given !== "runner" && given !== "all") {
|
|
99
|
+
throw new Error(`RUNTIME_ROLE must be web, runner or all, not "${given}"`);
|
|
100
|
+
}
|
|
101
|
+
return given;
|
|
102
|
+
}
|
|
95
103
|
export const env = {
|
|
96
104
|
production: process.env.NODE_ENV === "production",
|
|
97
105
|
/** Running from source: Vite serves the pages, this server only `/api`. */
|
|
@@ -99,6 +107,17 @@ export const env = {
|
|
|
99
107
|
port,
|
|
100
108
|
/** Listen address; a runtime that runs alone stays on the loopback interface. */
|
|
101
109
|
host: str("API_HOST", manageUrl ? "0.0.0.0" : "127.0.0.1"),
|
|
110
|
+
/**
|
|
111
|
+
* What this process does: `web` serves the studio and the API and wakes runs, `runner` takes
|
|
112
|
+
* the runs that wait and drives them, `all` does both (a runtime that runs alone).
|
|
113
|
+
*/
|
|
114
|
+
role: role(),
|
|
115
|
+
runner: {
|
|
116
|
+
/** This runner's name in the control database; a new one each start. */
|
|
117
|
+
id: `${hostname()}-${randomBytes(3).toString("hex")}`,
|
|
118
|
+
/** Where the web reaches this runner (the browser's screen of a run it holds). */
|
|
119
|
+
url: str("RUNNER_URL").replace(/\/$/, ""),
|
|
120
|
+
},
|
|
102
121
|
/** The origin people open, e.g. https://wizards.localhost — auth callbacks and links use it. */
|
|
103
122
|
appUrl: str("APP_URL", fromSource ? "http://localhost:5181" : `http://localhost:${port}`).replace(/\/$/, ""),
|
|
104
123
|
/** More host names this server answers under, besides APP_URL's and the loopback names. */
|
|
@@ -2,7 +2,7 @@ import { serve } from "@hono/node-server";
|
|
|
2
2
|
import { localEntryUrl, purgeSessions } from "./auth/index.js";
|
|
3
3
|
import { adoptLegacyData } from "./db/adopt.js";
|
|
4
4
|
import { knownTenants, migrateAllTenants, migrateControlDb, openTenantDb, withTenant, } from "./db/client.js";
|
|
5
|
-
import {
|
|
5
|
+
import { startRunner, stopRunner } from "./engine/runner.js";
|
|
6
6
|
import { basePath, env } from "./env.js";
|
|
7
7
|
import { hookConsole } from "./log.js";
|
|
8
8
|
import { managed } from "./manage.js";
|
|
@@ -15,6 +15,7 @@ import { clearRunning, writeRunning } from "./running.js";
|
|
|
15
15
|
import { syncMarketplace } from "./services/marketplace.js";
|
|
16
16
|
import { purgeExpiredRuns } from "./services/shares.js";
|
|
17
17
|
import { purgeUnusedStores } from "./store/index.js";
|
|
18
|
+
import { forgetRunner, registerRunner } from "./tenants/control.js";
|
|
18
19
|
import { LOCAL_TENANT } from "./tenants/tenant.js";
|
|
19
20
|
import { onRestart, RESTART_EXIT } from "./update.js";
|
|
20
21
|
// Before anything prints: the last lines stay in memory for a look from afar (debug.ts).
|
|
@@ -68,7 +69,12 @@ const server = serve({ fetch: withoutBasePath, port: env.port, hostname: env.hos
|
|
|
68
69
|
});
|
|
69
70
|
}
|
|
70
71
|
});
|
|
71
|
-
|
|
72
|
+
// A runner takes the runs in line, those a stopped process left behind first (RUNTIME_ROLE).
|
|
73
|
+
if (env.role !== "web") {
|
|
74
|
+
await registerRunner();
|
|
75
|
+
setInterval(() => void registerRunner().catch(() => undefined), 10_000).unref();
|
|
76
|
+
startRunner();
|
|
77
|
+
}
|
|
72
78
|
// End-user results are kept RESULT_TTL_DAYS; expired runs and their files go once an hour.
|
|
73
79
|
// What a wizard keeps for a person goes once nobody used it for STORE_TTL_DAYS.
|
|
74
80
|
async function purge() {
|
|
@@ -88,6 +94,11 @@ if (!managed) {
|
|
|
88
94
|
async function shutdown(code = 0) {
|
|
89
95
|
clearRunning(env.dataDir);
|
|
90
96
|
server.close();
|
|
97
|
+
if (env.role !== "web") {
|
|
98
|
+
// The runs go back in line for another runner; their steps start afresh there.
|
|
99
|
+
await stopRunner();
|
|
100
|
+
await forgetRunner().catch(() => undefined);
|
|
101
|
+
}
|
|
91
102
|
await closeBrowser();
|
|
92
103
|
process.exit(code);
|
|
93
104
|
}
|
|
@@ -417,7 +417,7 @@ async function ownLanguageModel(cfg, ref, meta) {
|
|
|
417
417
|
*/
|
|
418
418
|
export async function textModel(cls, meta = {}) {
|
|
419
419
|
const resolved = await ownTextModel(cls, meta);
|
|
420
|
-
const device = meta.runId && isText(cls) ? deviceThinks(meta.runId, cls) : null;
|
|
420
|
+
const device = meta.runId && isText(cls) ? await deviceThinks(meta.runId, cls) : null;
|
|
421
421
|
return device
|
|
422
422
|
? { ...resolved, model: new DeviceModel(meta.runId, resolved.model, device.maxChars) }
|
|
423
423
|
: resolved;
|
|
@@ -4,7 +4,7 @@ import { noteText } from "@engenty-wizards/shared/run";
|
|
|
4
4
|
import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
|
|
5
5
|
import { db, schema, withTenant } from "../db/client.js";
|
|
6
6
|
import { answerAsk } from "../engine/asks.js";
|
|
7
|
-
import {
|
|
7
|
+
import { watchRun } from "../engine/events.js";
|
|
8
8
|
import { cancel, createRun, goBack, NoCreditsError, RunInputError, retry, reviewStep, submitPage, } from "../engine/runner.js";
|
|
9
9
|
import { saveAsset } from "../files/storage.js";
|
|
10
10
|
import { wizardUnavailable } from "../limits.js";
|
|
@@ -126,7 +126,7 @@ export function runsApiFor(pluginId) {
|
|
|
126
126
|
},
|
|
127
127
|
async answerAsk(runId, askId, answer) {
|
|
128
128
|
await pluginRun(runId);
|
|
129
|
-
if (!answerAsk(runId, askId, answer === "allow" ? { type: "done" } : { type: "skip" })) {
|
|
129
|
+
if (!(await answerAsk(runId, askId, answer === "allow" ? { type: "done" } : { type: "skip" }))) {
|
|
130
130
|
throw new ServiceError("refused", "This question is no longer open.");
|
|
131
131
|
}
|
|
132
132
|
},
|
|
@@ -138,14 +138,11 @@ export function runsApiFor(pluginId) {
|
|
|
138
138
|
subscribe(runId, listener) {
|
|
139
139
|
// The listener runs inside the tenant the subscription was made in, as the events do.
|
|
140
140
|
const tenantId = currentTenant();
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
if (signal.device) {
|
|
144
|
-
return;
|
|
145
|
-
}
|
|
141
|
+
// Changes the runner makes in another process reach the plugin too, each event once.
|
|
142
|
+
return watchRun(runId, (signal) => {
|
|
146
143
|
const event = signal.event;
|
|
147
144
|
const shaped = {
|
|
148
|
-
runId
|
|
145
|
+
runId,
|
|
149
146
|
event: event
|
|
150
147
|
? {
|
|
151
148
|
id: event.id,
|
|
@@ -14,8 +14,9 @@ import { ConnectError, connectionViews, connectWithCredentials, disconnect, fini
|
|
|
14
14
|
import { finishPluginOAuth, pluginStateTenant } from "../connectors/plugin-connections.js";
|
|
15
15
|
import { db, schema, withTenant } from "../db/client.js";
|
|
16
16
|
import { answerAsk, pendingAsk } from "../engine/asks.js";
|
|
17
|
-
import { answerDevice, offerDevice } from "../engine/device.js";
|
|
18
|
-
import { emitEvent, signalChanged,
|
|
17
|
+
import { answerDevice, offerDevice, openDeviceCalls } from "../engine/device.js";
|
|
18
|
+
import { emitEvent, signalChanged, watchRun } from "../engine/events.js";
|
|
19
|
+
import { fromOwner } from "../engine/owner.js";
|
|
19
20
|
import { pushAvailable, setPushDevice } from "../engine/push.js";
|
|
20
21
|
import { liveResources } from "../engine/resources.js";
|
|
21
22
|
import { cancel, createRun, goBack, NoCreditsError, projectIdOf, RunConflict, RunInputError, retry, reviewStep, runView, submitPage, talkAllowed, } from "../engine/runner.js";
|
|
@@ -403,13 +404,19 @@ export const runRoutes = new Hono()
|
|
|
403
404
|
await stream.writeSSE({ event: "view", data: JSON.stringify(await viewOf(run)) });
|
|
404
405
|
}
|
|
405
406
|
};
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
407
|
+
// Calls the runner put to the device the run is watched from, each sent once per stream.
|
|
408
|
+
const sent = new Set();
|
|
409
|
+
const sendDeviceCalls = async () => {
|
|
410
|
+
for (const call of await openDeviceCalls(id)) {
|
|
411
|
+
if (!(closed || sent.has(call.id))) {
|
|
412
|
+
sent.add(call.id);
|
|
413
|
+
await stream.writeSSE({ event: "device", data: JSON.stringify(call) });
|
|
411
414
|
}
|
|
412
|
-
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
const unsubscribe = watchRun(id, (signal) => {
|
|
418
|
+
if (!signal.event) {
|
|
419
|
+
void sendDeviceCalls().catch(() => undefined);
|
|
413
420
|
}
|
|
414
421
|
void push();
|
|
415
422
|
});
|
|
@@ -418,6 +425,7 @@ export const runRoutes = new Hono()
|
|
|
418
425
|
unsubscribe();
|
|
419
426
|
});
|
|
420
427
|
await stream.writeSSE({ event: "view", data: JSON.stringify(await viewOf(first)) });
|
|
428
|
+
await sendDeviceCalls();
|
|
421
429
|
while (!closed) {
|
|
422
430
|
await stream.sleep(20_000);
|
|
423
431
|
if (!closed) {
|
|
@@ -443,7 +451,7 @@ export const runRoutes = new Hono()
|
|
|
443
451
|
.optional(),
|
|
444
452
|
})
|
|
445
453
|
.parse(await c.req.json().catch(() => ({})));
|
|
446
|
-
offerDevice(run.id, offer);
|
|
454
|
+
await offerDevice(run.id, offer);
|
|
447
455
|
return c.json({ ok: true });
|
|
448
456
|
})
|
|
449
457
|
// The device's answer to one call the stream carried as a `device` event.
|
|
@@ -455,7 +463,7 @@ export const runRoutes = new Hono()
|
|
|
455
463
|
const answer = z
|
|
456
464
|
.object({ text: z.string().max(200_000).optional(), error: z.string().max(500).optional() })
|
|
457
465
|
.parse(await c.req.json().catch(() => ({})));
|
|
458
|
-
return c.json({ ok: answerDevice(run.id, c.req.param("reqId"), answer) });
|
|
466
|
+
return c.json({ ok: await answerDevice(run.id, c.req.param("reqId"), answer) });
|
|
459
467
|
})
|
|
460
468
|
.post("/:id/pages/:stepId", async (c) => {
|
|
461
469
|
const run = await accessibleRun(c, c.req.param("id"));
|
|
@@ -661,7 +669,7 @@ export const runRoutes = new Hono()
|
|
|
661
669
|
z.object({ type: z.literal("skip") }),
|
|
662
670
|
])
|
|
663
671
|
.parse(await c.req.json());
|
|
664
|
-
if (!answerAsk(run.id, c.req.param("askId"), answer)) {
|
|
672
|
+
if (!(await answerAsk(run.id, c.req.param("askId"), answer))) {
|
|
665
673
|
return refuse(c, { code: "askClosed" }, 409);
|
|
666
674
|
}
|
|
667
675
|
return c.json({ ok: true });
|
|
@@ -671,7 +679,8 @@ export const runRoutes = new Hono()
|
|
|
671
679
|
const run = await accessibleRun(c, c.req.param("id"));
|
|
672
680
|
const resources = run?.status === "running" ? liveResources(run.id) : null;
|
|
673
681
|
if (!resources?.openPage()) {
|
|
674
|
-
|
|
682
|
+
// The run may work in another process: its runner answers.
|
|
683
|
+
return (run && (await fromOwner(c, run.id))) || c.json({ error: "not found" }, 404);
|
|
675
684
|
}
|
|
676
685
|
return c.json({ seat: resources.seatHolder() });
|
|
677
686
|
})
|
|
@@ -681,7 +690,7 @@ export const runRoutes = new Hono()
|
|
|
681
690
|
const run = await accessibleRun(c, c.req.param("id"));
|
|
682
691
|
const resources = run?.status === "running" ? liveResources(run.id) : null;
|
|
683
692
|
if (!(run && resources?.openPage())) {
|
|
684
|
-
return refuse(c, { code: "noBrowser" }, 409);
|
|
693
|
+
return (run && (await fromOwner(c, run.id))) || refuse(c, { code: "noBrowser" }, 409);
|
|
685
694
|
}
|
|
686
695
|
const { to } = z.object({ to: z.enum(["person", "agent"]) }).parse(await c.req.json());
|
|
687
696
|
if (resources.seatHolder() !== to) {
|
|
@@ -699,7 +708,7 @@ export const runRoutes = new Hono()
|
|
|
699
708
|
const run = await accessibleRun(c, c.req.param("id"));
|
|
700
709
|
const resources = run?.status === "running" ? liveResources(run.id) : null;
|
|
701
710
|
if (!resources?.openPage()) {
|
|
702
|
-
return c.notFound();
|
|
711
|
+
return (run && (await fromOwner(c, run.id))) || c.notFound();
|
|
703
712
|
}
|
|
704
713
|
const boundary = "frame";
|
|
705
714
|
const encoder = new TextEncoder();
|
|
@@ -768,7 +777,14 @@ export const runRoutes = new Hono()
|
|
|
768
777
|
.post("/:id/browser/act", async (c) => {
|
|
769
778
|
const run = await accessibleRun(c, c.req.param("id"));
|
|
770
779
|
const resources = run ? liveResources(run.id) : null;
|
|
771
|
-
|
|
780
|
+
if (run?.status === "running" && !resources) {
|
|
781
|
+
// The run works in another process: its runner answers.
|
|
782
|
+
const answered = await fromOwner(c, run.id);
|
|
783
|
+
if (answered) {
|
|
784
|
+
return answered;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
const theirs = run && ((await pendingAsk(run.id)) || resources?.seatHolder() === "person");
|
|
772
788
|
const page = theirs ? resources?.openPage() : null;
|
|
773
789
|
if (!(run && resources && page)) {
|
|
774
790
|
return refuse(c, { code: "notWaiting" }, 409);
|
|
@@ -2,8 +2,8 @@ import { FIELD_WAYS, formatsFor, isDecidedField, shownFields, slotText, wizardLa
|
|
|
2
2
|
import { and, count, desc, eq, gte, inArray, max, or, sql } from "drizzle-orm";
|
|
3
3
|
import { canSpend, MICROS_PER_CREDIT } from "../credits/credits.js";
|
|
4
4
|
import { db, schema } from "../db/client.js";
|
|
5
|
-
import { answerAsk
|
|
6
|
-
import { emitEvent, recentEvents,
|
|
5
|
+
import { answerAsk } from "../engine/asks.js";
|
|
6
|
+
import { emitEvent, recentEvents, watchRun } from "../engine/events.js";
|
|
7
7
|
import { cancel, createRun, goBack, NoCreditsError, pageContext, RunConflict, RunInputError, retry, reviewStep, submitPage, } from "../engine/runner.js";
|
|
8
8
|
import { ModelUnavailableError } from "../model-errors.js";
|
|
9
9
|
import { signedUrl } from "../secrets/signing.js";
|
|
@@ -25,6 +25,7 @@ export async function startTestRun(userId, wizardId, autopilot) {
|
|
|
25
25
|
version: null,
|
|
26
26
|
mode: "test",
|
|
27
27
|
userId,
|
|
28
|
+
unattended: Boolean(autopilot),
|
|
28
29
|
}).catch((err) => {
|
|
29
30
|
throw err instanceof ModelUnavailableError ? new ServiceError("refused", err.message) : err;
|
|
30
31
|
});
|
|
@@ -35,12 +36,10 @@ export async function startTestRun(userId, wizardId, autopilot) {
|
|
|
35
36
|
}
|
|
36
37
|
function fly(runId, answers, acceptReviews) {
|
|
37
38
|
autopilots.add(runId);
|
|
38
|
-
unattended.add(runId);
|
|
39
39
|
let busy = false;
|
|
40
40
|
let again = false;
|
|
41
41
|
const land = () => {
|
|
42
42
|
autopilots.delete(runId);
|
|
43
|
-
unattended.delete(runId);
|
|
44
43
|
unsubscribe();
|
|
45
44
|
clearTimeout(timeout);
|
|
46
45
|
};
|
|
@@ -89,7 +88,7 @@ function fly(runId, answers, acceptReviews) {
|
|
|
89
88
|
busy = false;
|
|
90
89
|
}
|
|
91
90
|
};
|
|
92
|
-
const unsubscribe =
|
|
91
|
+
const unsubscribe = watchRun(runId, () => {
|
|
93
92
|
void step();
|
|
94
93
|
});
|
|
95
94
|
const timeout = setTimeout(land, 30 * 60_000);
|
|
@@ -131,7 +130,7 @@ export async function waitRun(load, seconds) {
|
|
|
131
130
|
let run = await load();
|
|
132
131
|
while (moving(run) && Date.now() < deadline) {
|
|
133
132
|
await new Promise((resolve) => {
|
|
134
|
-
const unsubscribe =
|
|
133
|
+
const unsubscribe = watchRun(run.id, () => {
|
|
135
134
|
unsubscribe();
|
|
136
135
|
clearTimeout(timer);
|
|
137
136
|
resolve();
|
|
@@ -150,7 +149,7 @@ async function waitWhileMoving(userId, runId, seconds, only) {
|
|
|
150
149
|
let run = await ownedRun(userId, runId, only);
|
|
151
150
|
while (moving(run) && Date.now() < deadline) {
|
|
152
151
|
await new Promise((resolve) => {
|
|
153
|
-
const unsubscribe =
|
|
152
|
+
const unsubscribe = watchRun(runId, () => {
|
|
154
153
|
unsubscribe();
|
|
155
154
|
clearTimeout(timer);
|
|
156
155
|
resolve();
|
|
@@ -422,7 +421,7 @@ export async function controlRun(userId, runId, action) {
|
|
|
422
421
|
/** Answers what a running step asks: allow a change in a connected account, or skip it. */
|
|
423
422
|
export async function answerRunAsk(userId, runId, askId, answer) {
|
|
424
423
|
await ownedRun(userId, runId);
|
|
425
|
-
if (!answerAsk(runId, askId, answer === "allow" ? { type: "done" } : { type: "skip" })) {
|
|
424
|
+
if (!(await answerAsk(runId, askId, answer === "allow" ? { type: "done" } : { type: "skip" }))) {
|
|
426
425
|
throw new ServiceError("refused", "This question is no longer open.");
|
|
427
426
|
}
|
|
428
427
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { and, count, eq, gte, inArray, or } from "drizzle-orm";
|
|
1
|
+
import { and, count, eq, gte, inArray, isNull, lt, or, sql } from "drizzle-orm";
|
|
2
2
|
import { control, controlDb } from "../db/client.js";
|
|
3
3
|
import { env } from "../env.js";
|
|
4
4
|
import { currentTenant } from "./tenant.js";
|
|
@@ -108,16 +108,94 @@ export async function dropRuns(runIds) {
|
|
|
108
108
|
.where(inArray(control.runIndex.runId, runIds.slice(i, i + 200)));
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
111
|
+
// --- the queue: which runner works on which run ---------------------------------
|
|
112
|
+
// `active` = the run wants a runner. `owner` = the one driving it, `seen` = its last heartbeat.
|
|
113
|
+
/** An owner silent this long has lost the run: another runner takes it. */
|
|
114
|
+
export const RUNNER_STALE_MS = 30_000;
|
|
115
|
+
/** Puts a run in line for a runner (again): active, owned by nobody. */
|
|
116
|
+
export async function wakeRun(runId) {
|
|
117
|
+
await controlDb
|
|
118
|
+
.update(control.runIndex)
|
|
119
|
+
.set({ active: true, owner: null, seen: null })
|
|
120
|
+
.where(eq(control.runIndex.runId, runId));
|
|
121
|
+
}
|
|
122
|
+
/** The run is done with runners for now: a page, a review or the end. */
|
|
123
|
+
export async function restRun(runId) {
|
|
124
|
+
await controlDb
|
|
125
|
+
.update(control.runIndex)
|
|
126
|
+
.set({ active: false, owner: null, seen: null })
|
|
127
|
+
.where(eq(control.runIndex.runId, runId));
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Takes a run for this runner, in one statement: only while nobody (alive) holds it and the
|
|
131
|
+
* tenant's owned runs stay under its limit. False: someone else has it, or the tenant is at its
|
|
132
|
+
* limit — the run stays in line.
|
|
133
|
+
*/
|
|
134
|
+
export async function claimRun(runId, tenantId, limit) {
|
|
135
|
+
const now = Date.now();
|
|
136
|
+
const stale = now - RUNNER_STALE_MS;
|
|
137
|
+
const result = await controlDb.run(sql `
|
|
138
|
+
UPDATE run_index SET owner = ${env.runner.id}, seen = ${now}
|
|
139
|
+
WHERE run_id = ${runId} AND active = 1
|
|
140
|
+
AND (owner IS NULL OR seen IS NULL OR seen < ${stale})
|
|
141
|
+
AND (SELECT count(*) FROM run_index
|
|
142
|
+
WHERE tenant_id = ${tenantId} AND owner IS NOT NULL AND seen >= ${stale}
|
|
143
|
+
AND run_id != ${runId}) < ${limit}`);
|
|
144
|
+
return result.rowsAffected > 0;
|
|
145
|
+
}
|
|
146
|
+
/** This runner still works on these runs. */
|
|
147
|
+
export async function heartbeatRuns(runIds) {
|
|
148
|
+
if (runIds.length) {
|
|
149
|
+
await controlDb
|
|
150
|
+
.update(control.runIndex)
|
|
151
|
+
.set({ seen: new Date() })
|
|
152
|
+
.where(and(eq(control.runIndex.owner, env.runner.id), inArray(control.runIndex.runId, runIds)));
|
|
153
|
+
}
|
|
114
154
|
}
|
|
115
|
-
/**
|
|
116
|
-
export async function
|
|
155
|
+
/** A runner that stops hands its runs back to the line; another takes them at once. */
|
|
156
|
+
export async function disownRuns() {
|
|
157
|
+
await controlDb
|
|
158
|
+
.update(control.runIndex)
|
|
159
|
+
.set({ owner: null, seen: null })
|
|
160
|
+
.where(eq(control.runIndex.owner, env.runner.id));
|
|
161
|
+
}
|
|
162
|
+
/** The runs in line: unowned, or whose owner fell silent. */
|
|
163
|
+
export async function waitingRuns() {
|
|
164
|
+
const stale = new Date(Date.now() - RUNNER_STALE_MS);
|
|
117
165
|
return controlDb
|
|
118
166
|
.select({ runId: control.runIndex.runId, tenantId: control.runIndex.tenantId })
|
|
119
167
|
.from(control.runIndex)
|
|
120
|
-
.where(eq(control.runIndex.active, true))
|
|
168
|
+
.where(and(eq(control.runIndex.active, true), or(isNull(control.runIndex.owner), isNull(control.runIndex.seen), lt(control.runIndex.seen, stale))))
|
|
169
|
+
.orderBy(control.runIndex.createdAt);
|
|
170
|
+
}
|
|
171
|
+
/** Where the runner holding a run is reached; null when none holds it or it named no address. */
|
|
172
|
+
export async function ownerUrl(runId) {
|
|
173
|
+
const row = await controlDb.query.runIndex.findFirst({
|
|
174
|
+
where: eq(control.runIndex.runId, runId),
|
|
175
|
+
});
|
|
176
|
+
if (!row?.owner || !row.seen || row.seen.getTime() < Date.now() - RUNNER_STALE_MS) {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
const who = await controlDb.query.runner.findFirst({ where: eq(control.runner.id, row.owner) });
|
|
180
|
+
return who?.url || null;
|
|
181
|
+
}
|
|
182
|
+
/** This process reports as a runner: its address, and that it is alive. */
|
|
183
|
+
export async function registerRunner() {
|
|
184
|
+
const now = new Date();
|
|
185
|
+
await controlDb
|
|
186
|
+
.insert(control.runner)
|
|
187
|
+
.values({ id: env.runner.id, url: env.runner.url || null, seen: now })
|
|
188
|
+
.onConflictDoUpdate({
|
|
189
|
+
target: control.runner.id,
|
|
190
|
+
set: { url: env.runner.url || null, seen: now },
|
|
191
|
+
});
|
|
192
|
+
// Runners gone for a day are forgotten.
|
|
193
|
+
await controlDb
|
|
194
|
+
.delete(control.runner)
|
|
195
|
+
.where(lt(control.runner.seen, new Date(now.getTime() - 86_400_000)));
|
|
196
|
+
}
|
|
197
|
+
export async function forgetRunner() {
|
|
198
|
+
await controlDb.delete(control.runner).where(eq(control.runner.id, env.runner.id));
|
|
121
199
|
}
|
|
122
200
|
/** A visitor's runs are counted across every wizard of every tenant. */
|
|
123
201
|
export async function visitorOverLimit(visitorId, ipHash) {
|