wizards 0.2.56 → 0.2.57
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/meta/0014_snapshot.json +3154 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +7 -0
- package/apps/runtime/dist/db/schema.js +4 -0
- package/apps/runtime/dist/engine/asks.js +53 -33
- package/apps/runtime/dist/engine/events.js +45 -1
- package/apps/runtime/dist/engine/owner.js +32 -0
- package/apps/runtime/dist/engine/runner.js +91 -79
- package/apps/runtime/dist/env.js +19 -0
- package/apps/runtime/dist/index.js +13 -2
- package/apps/runtime/dist/plugins/runs.js +7 -6
- package/apps/runtime/dist/routes/runs.js +17 -8
- 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-DEZCEQlN.js} +1 -1
- package/apps/web/dist/assets/{ChangelogDialog-D4sBrhi-.js → ChangelogDialog-CgnnJj4G.js} +1 -1
- package/apps/web/dist/assets/{ChatView-Bntm0u8V.js → ChatView-BnnKdwk4.js} +1 -1
- package/apps/web/dist/assets/{EditorPage-DaVeNzHU.js → EditorPage-CeDWjq4z.js} +1 -1
- package/apps/web/dist/assets/{FlowPreview-C0tTz51A.js → FlowPreview-Du028FI3.js} +1 -1
- package/apps/web/dist/assets/{Harness-De-PsLFA.js → Harness-CEPy4MEp.js} +1 -1
- package/apps/web/dist/assets/{Marketplace-7Bdv7Gd5.js → Marketplace-ms58DQJ9.js} +2 -2
- package/apps/web/dist/assets/{NewWizardPage-CV7jrSkz.js → NewWizardPage-CEQSNXeZ.js} +1 -1
- package/apps/web/dist/assets/{ProjectPage-CBCd24oM.js → ProjectPage-CXDpKoK2.js} +1 -1
- package/apps/web/dist/assets/{PublicRunner-CVmkHSnC.js → PublicRunner-DMmtmzBX.js} +1 -1
- package/apps/web/dist/assets/{RunDrawer-CvzuYc0d.js → RunDrawer-BIojYB0g.js} +1 -1
- package/apps/web/dist/assets/{RunnerView-BtZp1FD6.js → RunnerView-D8OGEoMl.js} +1 -1
- package/apps/web/dist/assets/{SettingsPage--Zj2pTgf.js → SettingsPage-BlMZL4_d.js} +1 -1
- package/apps/web/dist/assets/{SetupPage-F_e8f1to.js → SetupPage-Doz9T3kv.js} +1 -1
- package/apps/web/dist/assets/{SharePage-DLivbYu6.js → SharePage-DOJXdsyi.js} +1 -1
- package/apps/web/dist/assets/changelog-B1jhC7Fv.js +1 -0
- package/apps/web/dist/assets/{esm-BMtXxAe0.js → esm-D6fM9MdG.js} +1 -1
- package/apps/web/dist/assets/{index-MlQy_Qoy.js → index-nfRuCdVt.js} +4 -4
- package/apps/web/dist/assets/{settings-menu-JtMfy9en.js → settings-menu-BGfn4LJE.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
|
@@ -115,6 +115,10 @@ export const run = sqliteTable("run", {
|
|
|
115
115
|
error: text("error"),
|
|
116
116
|
/** What a running step is asking the person right now (a login, a code); null = nothing. */
|
|
117
117
|
ask: text("ask", { mode: "json" }).$type(),
|
|
118
|
+
/** The person's answer to `ask`, written by the web for the runner that waits on it. */
|
|
119
|
+
answer: text("answer", { mode: "json" }).$type(),
|
|
120
|
+
/** An autopilot drives this test run (an MCP client fills its pages): it asks nobody. */
|
|
121
|
+
unattended: integer("unattended", { mode: "boolean" }).notNull().default(false),
|
|
118
122
|
costMicros: integer("cost_micros").notNull().default(0),
|
|
119
123
|
/** Set once the result is shared: `/s/<token>` shows it read-only. */
|
|
120
124
|
shareToken: text("share_token"),
|
|
@@ -1,62 +1,82 @@
|
|
|
1
|
-
import { eq } from "drizzle-orm";
|
|
1
|
+
import { eq, sql } from "drizzle-orm";
|
|
2
2
|
import { nanoid } from "nanoid";
|
|
3
3
|
import { db, schema } from "../db/client.js";
|
|
4
4
|
import { signalChanged } from "./events.js";
|
|
5
5
|
import { pushRun } from "./push.js";
|
|
6
6
|
/** How long a step waits for the person before it goes on without them. */
|
|
7
7
|
const ASK_TIMEOUT_MS = 15 * 60_000;
|
|
8
|
-
/**
|
|
9
|
-
|
|
10
|
-
const waiting = new Map();
|
|
8
|
+
/** How often the waiting step looks for the answer in the row. */
|
|
9
|
+
const ASK_POLL_MS = 1000;
|
|
11
10
|
async function setAsk(runId, ask) {
|
|
12
|
-
await db
|
|
11
|
+
await db
|
|
12
|
+
.update(schema.run)
|
|
13
|
+
.set({ ask, answer: null, updatedAt: new Date() })
|
|
14
|
+
.where(eq(schema.run.id, runId));
|
|
13
15
|
signalChanged(runId);
|
|
14
16
|
}
|
|
15
17
|
/**
|
|
16
18
|
* Puts a question to the person and waits. The run stays "running": the step is in the middle
|
|
17
|
-
* of its work and goes on with the answer. One question per run at a time.
|
|
19
|
+
* of its work and goes on with the answer. One question per run at a time. The question and the
|
|
20
|
+
* answer go through the run's row: the web that takes the answer need not be the process that
|
|
21
|
+
* asked.
|
|
18
22
|
*/
|
|
19
23
|
export async function askPerson(runId, ask, signal) {
|
|
20
|
-
|
|
24
|
+
const open = await db.query.run.findFirst({
|
|
25
|
+
where: eq(schema.run.id, runId),
|
|
26
|
+
columns: { ask: true },
|
|
27
|
+
});
|
|
28
|
+
if (open?.ask) {
|
|
21
29
|
throw new Error("The wizard is already waiting for the person.");
|
|
22
30
|
}
|
|
23
31
|
const full = { ...ask, id: nanoid(10), at: new Date().toISOString() };
|
|
24
|
-
const result = new Promise((resolve) => {
|
|
25
|
-
const finish = (r) => {
|
|
26
|
-
clearTimeout(timer);
|
|
27
|
-
signal.removeEventListener("abort", onAbort);
|
|
28
|
-
resolve(r);
|
|
29
|
-
};
|
|
30
|
-
const onAbort = () => finish({ type: "skip" });
|
|
31
|
-
const timer = setTimeout(() => finish({ type: "timeout" }), ASK_TIMEOUT_MS);
|
|
32
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
33
|
-
waiting.set(runId, { ask: full, settle: finish });
|
|
34
|
-
});
|
|
35
32
|
await setAsk(runId, full);
|
|
36
33
|
void pushRun(runId, "asks");
|
|
34
|
+
const until = Date.now() + ASK_TIMEOUT_MS;
|
|
37
35
|
try {
|
|
38
|
-
|
|
36
|
+
while (!signal.aborted) {
|
|
37
|
+
if (Date.now() >= until) {
|
|
38
|
+
return { type: "timeout" };
|
|
39
|
+
}
|
|
40
|
+
const row = await db.query.run.findFirst({
|
|
41
|
+
where: eq(schema.run.id, runId),
|
|
42
|
+
columns: { answer: true },
|
|
43
|
+
});
|
|
44
|
+
if (row?.answer?.askId === full.id) {
|
|
45
|
+
return row.answer.answer;
|
|
46
|
+
}
|
|
47
|
+
await new Promise((resolve) => {
|
|
48
|
+
const timer = setTimeout(done, ASK_POLL_MS);
|
|
49
|
+
function done() {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
signal.removeEventListener("abort", done);
|
|
52
|
+
resolve();
|
|
53
|
+
}
|
|
54
|
+
signal.addEventListener("abort", done, { once: true });
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
return { type: "skip" };
|
|
39
58
|
}
|
|
40
59
|
finally {
|
|
41
|
-
waiting.delete(runId);
|
|
42
60
|
await setAsk(runId, null).catch(() => undefined);
|
|
43
61
|
}
|
|
44
62
|
}
|
|
45
63
|
/** The question a run is waiting on, if any. */
|
|
46
|
-
export function pendingAsk(runId) {
|
|
47
|
-
|
|
64
|
+
export async function pendingAsk(runId) {
|
|
65
|
+
const row = await db.query.run.findFirst({
|
|
66
|
+
where: eq(schema.run.id, runId),
|
|
67
|
+
columns: { ask: true },
|
|
68
|
+
});
|
|
69
|
+
return row?.ask ?? null;
|
|
48
70
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
return
|
|
71
|
+
/** Leaves the answer for the waiting step; false when that question is no longer open. */
|
|
72
|
+
export async function answerAsk(runId, askId, answer) {
|
|
73
|
+
const result = await db
|
|
74
|
+
.update(schema.run)
|
|
75
|
+
.set({ answer: { askId, answer } })
|
|
76
|
+
.where(sql `${schema.run.id} = ${runId} AND json_extract(${schema.run.ask}, '$.id') = ${askId}`);
|
|
77
|
+
return result.rowsAffected > 0;
|
|
56
78
|
}
|
|
57
|
-
/** A
|
|
79
|
+
/** A run a runner takes starts its step afresh: a question left in the row has no one waiting. */
|
|
58
80
|
export async function clearStaleAsk(runId) {
|
|
59
|
-
|
|
60
|
-
await db.update(schema.run).set({ ask: null }).where(eq(schema.run.id, runId));
|
|
61
|
-
}
|
|
81
|
+
await db.update(schema.run).set({ ask: null, answer: null }).where(eq(schema.run.id, runId));
|
|
62
82
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AsyncResource } from "node:async_hooks";
|
|
2
2
|
import { EventEmitter } from "node:events";
|
|
3
3
|
import { noteText } from "@engenty-wizards/shared/run";
|
|
4
|
-
import { and, desc, eq, gt } from "drizzle-orm";
|
|
4
|
+
import { and, desc, eq, gt, sql } from "drizzle-orm";
|
|
5
5
|
import { db, schema } from "../db/client.js";
|
|
6
6
|
const bus = new EventEmitter();
|
|
7
7
|
bus.setMaxListeners(0);
|
|
@@ -42,6 +42,50 @@ export function subscribe(runId, listener) {
|
|
|
42
42
|
bus.on(runId, bound);
|
|
43
43
|
return () => bus.off(runId, bound);
|
|
44
44
|
}
|
|
45
|
+
/** How often a watcher looks at the row for what another process changed. */
|
|
46
|
+
const WATCH_POLL_MS = 1000;
|
|
47
|
+
/**
|
|
48
|
+
* Tells of every change on a run: at once when this process made it, within a second when the
|
|
49
|
+
* runner (another process) wrote to the row or added an event. Call it in the run's tenant.
|
|
50
|
+
*/
|
|
51
|
+
export function watchRun(runId, listener) {
|
|
52
|
+
const unsubscribe = subscribe(runId, listener);
|
|
53
|
+
let last = null;
|
|
54
|
+
let busy = false;
|
|
55
|
+
const look = async () => {
|
|
56
|
+
if (busy) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
busy = true;
|
|
60
|
+
try {
|
|
61
|
+
const [row] = await db
|
|
62
|
+
.select({
|
|
63
|
+
updatedAt: schema.run.updatedAt,
|
|
64
|
+
event: sql `(select max(${schema.runEvent.id}) from ${schema.runEvent} where ${schema.runEvent.runId} = ${runId})`,
|
|
65
|
+
})
|
|
66
|
+
.from(schema.run)
|
|
67
|
+
.where(eq(schema.run.id, runId));
|
|
68
|
+
const mark = row ? `${row.updatedAt.getTime()}:${row.event ?? 0}` : null;
|
|
69
|
+
if (last !== null && mark !== last) {
|
|
70
|
+
listener();
|
|
71
|
+
}
|
|
72
|
+
last = mark;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// The next look tells.
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
busy = false;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
const timer = setInterval(() => void look(), WATCH_POLL_MS);
|
|
82
|
+
timer.unref();
|
|
83
|
+
void look();
|
|
84
|
+
return () => {
|
|
85
|
+
clearInterval(timer);
|
|
86
|
+
unsubscribe();
|
|
87
|
+
};
|
|
88
|
+
}
|
|
45
89
|
export async function recentEvents(runId, afterId = 0, limit = 40) {
|
|
46
90
|
const rows = await db
|
|
47
91
|
.select()
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { ownerUrl } from "../tenants/control.js";
|
|
2
|
+
/**
|
|
3
|
+
* Hands a request on to the runner holding the run — what only the process with the run's
|
|
4
|
+
* browser can answer. The runner serves the same routes and checks the same cookie; the caller's
|
|
5
|
+
* headers go along. Null: nobody holds the run, or the runner named no address (RUNNER_URL).
|
|
6
|
+
*/
|
|
7
|
+
export async function fromOwner(c, runId) {
|
|
8
|
+
const base = await ownerUrl(runId);
|
|
9
|
+
if (!base) {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
const here = new URL(c.req.url);
|
|
13
|
+
const headers = new Headers(c.req.raw.headers);
|
|
14
|
+
headers.delete("host");
|
|
15
|
+
headers.delete("content-length");
|
|
16
|
+
const method = c.req.method;
|
|
17
|
+
const body = method === "GET" || method === "HEAD" ? undefined : await c.req.raw.arrayBuffer();
|
|
18
|
+
try {
|
|
19
|
+
const res = await fetch(`${base}${here.pathname}${here.search}`, {
|
|
20
|
+
method,
|
|
21
|
+
headers,
|
|
22
|
+
body,
|
|
23
|
+
redirect: "manual",
|
|
24
|
+
signal: AbortSignal.timeout(15_000),
|
|
25
|
+
});
|
|
26
|
+
return new Response(res.body, { status: res.status, headers: res.headers });
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
console.error(`[run ${runId}] the runner did not answer:`, err);
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -18,9 +18,9 @@ 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
25
|
import { emitEvent, recentEvents, signalChanged } from "./events.js";
|
|
26
26
|
import { readPageInput } from "./input.js";
|
|
@@ -45,10 +45,15 @@ export class NoCreditsError extends Error {
|
|
|
45
45
|
super("Dieser Wizard hat gerade kein Guthaben mehr. Bitte später erneut versuchen.");
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
|
+
/** The runs this process drives right now, with the handle that stops each. */
|
|
48
49
|
const active = new Map();
|
|
49
|
-
// ---
|
|
50
|
-
//
|
|
51
|
-
|
|
50
|
+
// --- the line ------------------------------------------------------------------
|
|
51
|
+
// A run that wants work is marked in the control database (`wakeRun`); a runner claims it there,
|
|
52
|
+
// so several processes share one line. A tenant's runs beyond its limit stay in line; nothing is
|
|
53
|
+
// refused. See docs/plans/runner-process.md.
|
|
54
|
+
/** How often a runner looks at the line, and how often it reports on the runs it holds. */
|
|
55
|
+
const POLL_MS = 2000;
|
|
56
|
+
const HEARTBEAT_MS = 10_000;
|
|
52
57
|
async function concurrencyLimit(tenant) {
|
|
53
58
|
if (!managed) {
|
|
54
59
|
return env.limits.concurrentRuns;
|
|
@@ -56,45 +61,6 @@ async function concurrencyLimit(tenant) {
|
|
|
56
61
|
const info = await tenantInfo(tenant).catch(() => null);
|
|
57
62
|
return info?.limits.concurrentRuns || env.limits.concurrentRuns;
|
|
58
63
|
}
|
|
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
64
|
async function loadRun(runId) {
|
|
99
65
|
return db.query.run.findFirst({ where: eq(schema.run.id, runId) });
|
|
100
66
|
}
|
|
@@ -198,6 +164,7 @@ export async function createRun(input) {
|
|
|
198
164
|
userId: input.userId ?? null,
|
|
199
165
|
ipHash: input.ipHash ?? null,
|
|
200
166
|
origin: input.origin ?? null,
|
|
167
|
+
unattended: input.unattended ?? false,
|
|
201
168
|
status: first.type === "page" ? "waiting_input" : "running",
|
|
202
169
|
cursor: first.id,
|
|
203
170
|
state,
|
|
@@ -212,37 +179,97 @@ export async function createRun(input) {
|
|
|
212
179
|
}
|
|
213
180
|
return id;
|
|
214
181
|
}
|
|
182
|
+
/**
|
|
183
|
+
* Puts the run to work: in line in the control database, and — when this process is a runner —
|
|
184
|
+
* taken at once if the tenant has a slot. The web alone leaves it for a runner's next look.
|
|
185
|
+
*/
|
|
215
186
|
export function kick(runId) {
|
|
187
|
+
const tenant = currentTenant();
|
|
188
|
+
void wakeRun(runId)
|
|
189
|
+
.then(() => {
|
|
190
|
+
if (env.role !== "web") {
|
|
191
|
+
return take(runId, tenant);
|
|
192
|
+
}
|
|
193
|
+
})
|
|
194
|
+
.catch((err) => console.error(`[run ${runId}]`, err));
|
|
195
|
+
}
|
|
196
|
+
/** Claims the run for this process and drives it; nothing when another holds it or the tenant is full. */
|
|
197
|
+
async function take(runId, tenant) {
|
|
216
198
|
if (active.has(runId)) {
|
|
217
199
|
return;
|
|
218
200
|
}
|
|
201
|
+
if (!(await claimRun(runId, tenant, await concurrencyLimit(tenant)))) {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
219
204
|
const abort = new AbortController();
|
|
220
205
|
active.set(runId, abort);
|
|
221
|
-
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
work()
|
|
206
|
+
// The heartbeat keeps the claim and hears of a cancel the web wrote while a step works.
|
|
207
|
+
const beat = setInterval(() => {
|
|
208
|
+
void heartbeatRuns([runId]).catch(() => undefined);
|
|
209
|
+
void withTenant(tenant, () => loadRun(runId))
|
|
210
|
+
.then((run) => {
|
|
211
|
+
if (run && run.status !== "running") {
|
|
212
|
+
abort.abort();
|
|
213
|
+
}
|
|
214
|
+
})
|
|
215
|
+
.catch(() => undefined);
|
|
216
|
+
}, HEARTBEAT_MS);
|
|
217
|
+
beat.unref();
|
|
218
|
+
await withTenant(tenant, () => drive(runId, abort.signal))
|
|
235
219
|
.catch(async (err) => {
|
|
236
220
|
console.error(`[run ${runId}]`, err);
|
|
237
|
-
await updateRun(runId, { status: "failed", error: friendly(err) }).catch(() => undefined);
|
|
221
|
+
await withTenant(tenant, () => updateRun(runId, { status: "failed", error: friendly(err) })).catch(() => undefined);
|
|
238
222
|
})
|
|
239
223
|
.finally(async () => {
|
|
224
|
+
clearInterval(beat);
|
|
240
225
|
active.delete(runId);
|
|
241
|
-
await
|
|
242
|
-
|
|
243
|
-
|
|
226
|
+
await withTenant(tenant, () => releaseResources(runId));
|
|
227
|
+
// A run the shutdown stopped goes back in line for the next runner; the rest is done for now.
|
|
228
|
+
if (!stopping) {
|
|
229
|
+
await restRun(runId).catch(() => undefined);
|
|
230
|
+
}
|
|
231
|
+
withTenant(tenant, () => signalChanged(runId));
|
|
232
|
+
// A slot came free: the next run of the line need not wait for the poll.
|
|
233
|
+
void lookAtLine();
|
|
244
234
|
});
|
|
245
235
|
}
|
|
236
|
+
let stopping = false;
|
|
237
|
+
let looking = false;
|
|
238
|
+
/** Takes what waits in line, run by run; each claim counts the tenant's limit by itself. */
|
|
239
|
+
async function lookAtLine() {
|
|
240
|
+
if (looking || stopping) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
looking = true;
|
|
244
|
+
try {
|
|
245
|
+
for (const r of await waitingRuns()) {
|
|
246
|
+
if (stopping) {
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
await take(r.runId, r.tenantId).catch((err) => console.error(`[line ${r.runId}]`, err));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
console.error("[line]", err);
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
looking = false;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/** A runner: looks at the line every POLL_MS, from now on. Runs a stopped process left behind are in it. */
|
|
260
|
+
export function startRunner() {
|
|
261
|
+
const timer = setInterval(() => void lookAtLine(), POLL_MS);
|
|
262
|
+
timer.unref();
|
|
263
|
+
void lookAtLine();
|
|
264
|
+
}
|
|
265
|
+
/** Stops the runs this process holds and hands them back to the line. */
|
|
266
|
+
export async function stopRunner() {
|
|
267
|
+
stopping = true;
|
|
268
|
+
for (const abort of active.values()) {
|
|
269
|
+
abort.abort();
|
|
270
|
+
}
|
|
271
|
+
await disownRuns().catch(() => undefined);
|
|
272
|
+
}
|
|
246
273
|
/** What conditions read in this run: answers, outputs, and how many rows each stored list has. */
|
|
247
274
|
async function flowValues(run, state) {
|
|
248
275
|
const counts = {};
|
|
@@ -322,9 +349,7 @@ async function makeContext(run, project, state, signal) {
|
|
|
322
349
|
projectFiles: (await projectFiles(project.id)).filter((f) => f.status === "ready"),
|
|
323
350
|
signal,
|
|
324
351
|
resources,
|
|
325
|
-
ask: (ask) => unattended.
|
|
326
|
-
? Promise.resolve(null)
|
|
327
|
-
: askPerson(run.id, { ...ask, stepId }, signal),
|
|
352
|
+
ask: (ask) => run.unattended ? Promise.resolve(null) : askPerson(run.id, { ...ask, stepId }, signal),
|
|
328
353
|
emit: (type, message, asset) => emitEvent(run.id, run.cursor, type, message, asset),
|
|
329
354
|
call: { runId: run.id, stepId },
|
|
330
355
|
chargeUsd: (usd) => addLocalCost(run.id, stepId, usd),
|
|
@@ -476,6 +501,7 @@ async function decidePageFields(run, page, state, signal) {
|
|
|
476
501
|
.map((f) => f.id);
|
|
477
502
|
}
|
|
478
503
|
async function drive(runId, signal) {
|
|
504
|
+
// The step starts afresh here: a question another process left in the row has no one waiting.
|
|
479
505
|
await clearStaleAsk(runId);
|
|
480
506
|
while (!signal.aborted) {
|
|
481
507
|
const run = await loadRun(runId);
|
|
@@ -575,20 +601,6 @@ async function drive(runId, signal) {
|
|
|
575
601
|
}
|
|
576
602
|
}
|
|
577
603
|
}
|
|
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
604
|
// --- commands ----------------------------------------------------------------
|
|
593
605
|
async function requireWaiting(runId, stepId) {
|
|
594
606
|
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
|
}
|
|
@@ -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,15 @@ 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
|
-
return
|
|
141
|
+
return watchRun(runId, (signal) => {
|
|
142
142
|
// The runtime asking the phone around the runner to think is not a change of the run.
|
|
143
|
-
if (signal
|
|
143
|
+
if (signal?.device) {
|
|
144
144
|
return;
|
|
145
145
|
}
|
|
146
|
-
|
|
146
|
+
// No signal: the run changed in another process (the runner), which tells no event.
|
|
147
|
+
const event = signal?.event;
|
|
147
148
|
const shaped = {
|
|
148
|
-
runId
|
|
149
|
+
runId,
|
|
149
150
|
event: event
|
|
150
151
|
? {
|
|
151
152
|
id: event.id,
|