Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Burst mode: plan limits, a durable store, the lane and the manager
Milind Soni5932c8a94017
diff --git a/server/burst/lane.ts b/server/burst/lane.tsnew file mode 100644index 0000000000..c0f15608a6--- /dev/null+++ b/server/burst/lane.ts@@ -0,0 +1,55 @@+// The burst lane: burst threads run up to the plan's limit, apart from the plan's own turn caps, so a burst never takes a+// place from the person's chats. Queued children wait in the lane's own store, never in the runtime or the engine queue,+// so the work of one step does not grow with the size of the burst.++export interface BurstLaneDeps<Slot> {+ /** The plan's most burst threads running at once. */+ parallel(): number;+ /** Whether one more burst thread may start: nobody's own work is waiting, and the machine has a place for it. */+ hasRoom(): boolean;+ /** The next queued child, taken. */+ next(): Slot | undefined;+ /** Starts it; `release` is called when it ends. */+ begin(slot: Slot): void;+}++export class BurstLane<Slot> {+ private readonly deps: BurstLaneDeps<Slot>;+ private running = 0;+ private pumping = false;+ private again = false;++ constructor(deps: BurstLaneDeps<Slot>) {+ this.deps = deps;+ }++ /** How many burst threads the lane has running or starting. */+ runningCount(): number {+ return this.running;+ }++ /** A burst thread ended: its place is free. */+ release(): void {+ this.running = Math.max(0, this.running - 1);+ this.pump();+ }++ /** Starts children while there is a place. Never re-enters: a start that settles at once asks for one more pass. */+ pump(): void {+ if (this.pumping) { this.again = true; return; }+ this.pumping = true;+ try {+ do {+ this.again = false;+ while (this.running < this.deps.parallel() && this.deps.hasRoom()) {+ const slot = this.deps.next();+ if (slot === undefined) break;+ this.running += 1;+ this.deps.begin(slot);+ }+ } while (this.again);+ } finally {+ this.pumping = false;+ }+ }+}diff --git a/server/burst/limits.ts b/server/burst/limits.tsnew file mode 100644index 0000000000..02a8421e4d--- /dev/null+++ b/server/burst/limits.ts@@ -0,0 +1,41 @@+// How much of a burst runs, by where it runs. One row per plan: enforced here, on the server, whatever a card or a bot asks.+export interface BurstLimits {+ /** Burst threads running at once across this server. */+ parallel: number;+ /** Tasks in one burst; a longer list is cut to this. */+ maxTasks: number;+ /** A plan where a higher one runs more at once. */+ smallPlan: boolean;+}++/** Starter and Personal share one machine size (2 GB, shared CPU), so past a few turns at once it slows until nothing answers. */+const SMALL_PLAN = { parallel: 2, maxTasks: 10, smallPlan: true } as const;+const MAX_TASKS = 200;++export const BURST_PLAN_LIMITS: Readonly<Record<string, BurstLimits>> = {+ starter: SMALL_PLAN,+ personal: SMALL_PLAN,+ pro: { parallel: 10, maxTasks: MAX_TASKS, smallPlan: false },+ max: { parallel: 25, maxTasks: MAX_TASKS, smallPlan: false },+ team: { parallel: 25, maxTasks: MAX_TASKS, smallPlan: false },+ business: { parallel: 25, maxTasks: MAX_TASKS, smallPlan: false },+ enterprise: { parallel: 25, maxTasks: MAX_TASKS, smallPlan: false },+};++/** Open-source installs (desktop, self-hosted) run on their own compute, with no plan. `config.json` `burst.maxParallel` changes it. */+export const OPEN_SOURCE_PARALLEL = 10;++export interface BurstHost {+ /** Whether this server is a My Cloud home. */+ cloudHome: boolean;+ /** The Cloud's plan, as the Admin last said. */+ tier: string | undefined;+ /** config.json's `burst.maxParallel`, on an open-source install. */+ maxParallel: number | undefined;+}++export function burstLimits(host: BurstHost): BurstLimits {+ if (!host.cloudHome) return { parallel: host.maxParallel ?? OPEN_SOURCE_PARALLEL, maxTasks: MAX_TASKS, smallPlan: false };+ // A tier this build doesn't know, or none yet, gets the smallest row: the machine may be small, and a burst only queues longer.+ return (host.tier !== undefined && Object.hasOwn(BURST_PLAN_LIMITS, host.tier) ? BURST_PLAN_LIMITS[host.tier] : undefined) ?? SMALL_PLAN;+}diff --git a/server/burst/manager.test.ts b/server/burst/manager.test.tsnew file mode 100644index 0000000000..e9bc2b466f--- /dev/null+++ b/server/burst/manager.test.ts@@ -0,0 +1,369 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { BurstCardData } from "../../shared/burst.ts";+import { burstLimits, BURST_PLAN_LIMITS, type BurstLimits } from "./limits.ts";+import { childOpening, createBurstManager, mergePrompt, type BurstManagerDeps, type BurstTurnOutcome } from "./manager.ts";+import { openBurstStore, type BurstChild, type BurstRecord, type BurstStore } from "./store.ts";++type Started = { burst: BurstRecord; child: BurstChild & { threadId: string }; text: string; done: (outcome: BurstTurnOutcome) => void };++function harness(input: { limits?: BurstLimits; hasRoom?: () => boolean; store?: BurstStore } = {}) {+ const store = input.store ?? openBurstStore(":memory:");+ const started: Started[] = [];+ const stopped: string[] = [];+ const merges: Array<{ burst: BurstRecord; text: string; done: (outcome: BurstTurnOutcome) => void }> = [];+ const delivered: string[] = [];+ const posted: BurstChild[][] = [];+ const drawn: BurstCardData[] = [];+ let thread = 0, limits = input.limits ?? { parallel: 3, maxTasks: 50, smallPlan: false }, mergeBusy = false, room = input.hasRoom ?? (() => true);+ const deps: BurstManagerDeps = {+ store,+ limits: () => limits,+ hasRoom: () => room(),+ openThread: () => `thread-${++thread}`,+ startChild: async (burst, child, text, done) => { started.push({ burst, child, text, done }); },+ stopChild: (_burst, child) => { stopped.push(child.threadId!); },+ startMerge: async (burst, text, done) => { if (mergeBusy) return false; merges.push({ burst, text: text(), done }); return true; },+ draw: (burst, card) => { drawn.push(card); return burst.cardMessageId ?? "card-1"; },+ postParts: (_burst, parts) => { posted.push(parts); return "parts as they came"; },+ deliver: (_burst, text) => { delivered.push(text); },+ now: () => 1_700_000_000_000,+ log: () => {},+ };+ const manager = createBurstManager(deps);+ return {+ store, manager, started, stopped, merges, delivered, posted, drawn,+ setLimits(next: BurstLimits) { limits = next; }, setRoom(next: () => boolean) { room = next; }, setMergeBusy(next: boolean) { mergeBusy = next; },+ propose(items: readonly string[]) {+ const proposal = manager.propose({ botId: "bot", threadId: "parent", task: "Research companies", instructions: "Find founders and funding.", items, model: { instanceId: "i", model: "fast-1" }, modelName: "fast-1" });+ if ("refused" in proposal) throw new Error(proposal.refused);+ return proposal;+ },+ };+}++const ok = (text: string): BurstTurnOutcome => ({ ok: true, text });+const items = (count: number) => Array.from({ length: count }, (_, index) => `Company ${index + 1}`);++let harnessed: ReturnType<typeof harness>[] = [];+const fresh = (input?: Parameters<typeof harness>[0]) => { const one = harness(input); harnessed.push(one); return one; };++beforeEach(() => { harnessed = []; });+afterEach(() => { for (const one of harnessed) { one.manager.close(); one.store.close(); } });++describe("burst plan limits", () => {+ it("are one row per plan", () => {+ expect(BURST_PLAN_LIMITS.starter).toMatchObject({ parallel: 2, maxTasks: 10 });+ expect(BURST_PLAN_LIMITS.personal).toEqual(BURST_PLAN_LIMITS.starter);+ expect(BURST_PLAN_LIMITS.pro).toMatchObject({ parallel: 10 });+ for (const plan of ["max", "team", "business", "enterprise"]) expect(BURST_PLAN_LIMITS[plan]).toMatchObject({ parallel: 25 });+ });++ it("run on the machine's own compute with no plan on an open-source install, 10 at once unless config says otherwise", () => {+ expect(burstLimits({ cloudHome: false, tier: undefined, maxParallel: undefined })).toMatchObject({ parallel: 10, smallPlan: false });+ expect(burstLimits({ cloudHome: false, tier: "starter", maxParallel: 4 })).toMatchObject({ parallel: 4, smallPlan: false });+ });++ it("hold a Cloud to the smallest row when its plan is unknown", () => {+ expect(burstLimits({ cloudHome: true, tier: undefined, maxParallel: undefined })).toEqual(BURST_PLAN_LIMITS.starter);+ expect(burstLimits({ cloudHome: true, tier: "a-tier-from-a-newer-admin", maxParallel: 99 })).toEqual(BURST_PLAN_LIMITS.starter);+ expect(burstLimits({ cloudHome: true, tier: "max", maxParallel: 1 })).toEqual(BURST_PLAN_LIMITS.max);+ });+});++describe("a burst", () => {+ it("never starts until Run is pressed", () => {+ const { manager, started, drawn, propose } = fresh();+ const card = propose(items(4));+ manager.pump();+ expect(card.phase).toBe("preview");+ expect(drawn.at(-1)).toMatchObject({ phase: "preview", total: 4, sample: ["Company 1", "Company 2", "Company 3", "Company 4"] });+ expect(started).toHaveLength(0);+ });++ it("fans out each item as its own thread with one shared id and the same instructions", () => {+ const { manager, started, store, propose } = fresh({ limits: { parallel: 25, maxTasks: 50, smallPlan: false } });+ const { burstId } = propose(items(3));+ manager.run(burstId);+ expect(started.map((run) => run.child.item)).toEqual(items(3));+ expect(new Set(started.map((run) => run.burst.id))).toEqual(new Set([burstId]));+ expect(new Set(started.map((run) => run.child.threadId)).size).toBe(3);+ for (const run of started) {+ expect(run.text).toContain("Find founders and funding.");+ expect(run.text).toContain(`This part: ${run.child.item}`);+ expect(run.text).toContain("your own words, not the person's");+ }+ expect(store.get(burstId)).toMatchObject({ phase: "running", counts: { running: 3, queued: 0 } });+ });++ it("refuses a second Run and an empty list", () => {+ const { manager, propose } = fresh();+ expect(manager.propose({ botId: "bot", threadId: "parent", task: "x", instructions: "", items: ["only one"], model: { instanceId: "i", model: "m" }, modelName: "m" })).toHaveProperty("refused");+ const { burstId } = propose(items(2));+ manager.run(burstId);+ expect(manager.run(burstId)).toEqual({ refused: "This burst has already started." });+ });+});++describe("the lane", () => {+ it.each([["starter", 2], ["pro", 10], ["max", 25]])("runs at most the plan's limit at once on %s", (plan, parallel) => {+ const limits = BURST_PLAN_LIMITS[plan]!;+ const one = fresh({ limits });+ const { manager, started, store } = one;+ const { burstId } = one.propose(items(Math.min(30, limits.maxTasks)));+ manager.run(burstId);+ expect(started).toHaveLength(Math.min(parallel, Math.min(30, limits.maxTasks)));+ expect(manager.runningCount()).toBe(Math.min(parallel, Math.min(30, limits.maxTasks)));+ let peak = manager.runningCount();+ while (store.get(burstId)!.counts.queued + store.get(burstId)!.counts.running > 0) {+ const next = started.shift()!;+ next.done(ok(`result for ${next.child.item}`));+ peak = Math.max(peak, manager.runningCount());+ }+ expect(peak).toBe(Math.min(parallel, Math.min(30, limits.maxTasks)));+ });++ it("lets the person's own chat go first: nothing new starts while their work waits", () => {+ let personWaits = true;+ const one = fresh({ limits: { parallel: 5, maxTasks: 50, smallPlan: false }, hasRoom: () => !personWaits });+ const { manager, started } = one;+ const { burstId } = one.propose(items(6));+ manager.run(burstId);+ expect(started).toHaveLength(0);+ personWaits = false;+ manager.pump();+ expect(started).toHaveLength(5);+ personWaits = true;+ started.shift()!.done(ok("done"));+ expect(started).toHaveLength(4);+ personWaits = false;+ manager.pump();+ expect(started).toHaveLength(5);+ });++ it("holds a burst to one place when the plan's limit drops", () => {+ const one = fresh({ limits: { parallel: 5, maxTasks: 50, smallPlan: false } });+ const { manager, started, setLimits } = one;+ const { burstId } = one.propose(items(8));+ setLimits({ parallel: 1, maxTasks: 50, smallPlan: false });+ manager.run(burstId);+ expect(started).toHaveLength(1);+ });++ it("stays linear on a very large burst: one indexed take per child, no scan per step", () => {+ const store = openBurstStore(":memory:");+ const calls: Record<string, number> = {};+ const counting = new Proxy(store, {+ get(target, name: keyof BurstStore) {+ const value = target[name];+ if (typeof value !== "function") return value;+ return (...args: unknown[]) => {+ calls[name] = (calls[name] ?? 0) + 1;+ return (value as (...a: unknown[]) => unknown).apply(target, args);+ };+ },+ }) as BurstStore;+ let roomChecks = 0;+ const count = 3_000;+ const one = fresh({ store: counting, limits: { parallel: 25, maxTasks: count, smallPlan: false }, hasRoom: () => { roomChecks += 1; return true; } });+ const { manager, started } = one;+ const { burstId } = one.propose(items(count));+ for (const name of Object.keys(calls)) delete calls[name];+ roomChecks = 0;+ manager.run(burstId);+ const totalStarted = () => (calls.takeQueued ?? 0);+ while (started.length > 0) started.shift()!.done(ok("done"));+ expect(totalStarted()).toBe(count + 1);+ expect(roomChecks).toBeLessThanOrEqual(3 * count + 50);+ expect(calls.children ?? 0).toBe(0);+ expect(calls.childrenIn ?? 0).toBeLessThanOrEqual(4);+ expect(calls.active ?? 0).toBeLessThanOrEqual(2);+ expect(store.get(burstId)!.counts).toMatchObject({ done: count, queued: 0, running: 0 });+ });+});++describe("cancel all and retry failed", () => {+ it("cancels what is queued, stops what runs, and merges nothing", () => {+ const one = fresh({ limits: { parallel: 2, maxTasks: 50, smallPlan: false } });+ const { manager, started, stopped, merges, store } = one;+ const { burstId } = one.propose(items(5));+ manager.run(burstId);+ expect(manager.cancel(burstId)).toMatchObject({ phase: "cancelled" });+ expect(stopped.toSorted()).toEqual(["thread-1", "thread-2"]);+ expect(store.get(burstId)!.counts).toMatchObject({ queued: 0, cancelled: 3, running: 2 });+ for (const run of started) run.done({ ok: false, text: "stopped" });+ expect(store.get(burstId)).toMatchObject({ phase: "cancelled", counts: { cancelled: 5, running: 0 } });+ expect(merges).toHaveLength(0);+ });++ it("cancels a preview without starting anything", () => {+ const one = fresh();+ const { manager, started } = one;+ const { burstId } = one.propose(items(3));+ expect(manager.cancel(burstId)).toMatchObject({ phase: "cancelled" });+ expect(started).toHaveLength(0);+ });++ it("runs only the failed parts again and merges once more", () => {+ const one = fresh({ limits: { parallel: 3, maxTasks: 50, smallPlan: false } });+ const { manager, started, merges, store, delivered } = one;+ const { burstId } = one.propose(items(3));+ manager.run(burstId);+ started[0]!.done(ok("a"));+ started[1]!.done({ ok: false, text: "ran out of memory" });+ started[2]!.done(ok("c"));+ expect(merges).toHaveLength(1);+ merges[0]!.done(ok("merged once"));+ expect(delivered).toEqual(["merged once"]);+ started.length = 0;+ expect(manager.retryFailed(burstId)).toMatchObject({ phase: "running" });+ expect(started.map((run) => run.child.item)).toEqual(["Company 2"]);+ expect(store.get(burstId)!.counts).toMatchObject({ done: 2, running: 1, failed: 0 });+ started[0]!.done(ok("b"));+ expect(merges).toHaveLength(2);+ merges[1]!.done(ok("merged twice"));+ expect(delivered).toEqual(["merged once", "merged twice"]);+ expect(store.get(burstId)).toMatchObject({ phase: "done", counts: { done: 3 } });+ });++ it("has nothing to retry when nothing failed", () => {+ const one = fresh();+ const { manager, started, merges } = one;+ const { burstId } = one.propose(items(2));+ manager.run(burstId);+ started.forEach((run) => { run.done(ok("x")); });+ merges[0]!.done(ok("merged"));+ expect(manager.retryFailed(burstId)).toEqual({ refused: "Nothing failed." });+ });+});++describe("the merged result", () => {+ it("names the parts that failed and is written once on the parent thread", () => {+ const one = fresh({ limits: { parallel: 3, maxTasks: 50, smallPlan: false } });+ const { manager, started, merges, delivered, drawn } = one;+ const { burstId } = one.propose(["Acme", "Globex", "Initech"]);+ manager.run(burstId);+ started[0]!.done(ok("Acme was founded in 1990."));+ started[1]!.done({ ok: false, text: "The provider refused." });+ started[2]!.done(ok("Initech makes software."));+ expect(merges).toHaveLength(1);+ expect(merges[0]!.text).toContain("Acme was founded in 1990.");+ expect(merges[0]!.text).toContain("Globex: The provider refused.");+ expect(merges[0]!.text).toContain("2 parts are done and 1 failed");+ expect(drawn.at(-1)).toMatchObject({ phase: "merging", failed: [{ title: "Globex", reason: "The provider refused." }] });+ merges[0]!.done(ok("Merged: Acme and Initech. Globex failed."));+ expect(delivered).toEqual(["Merged: Acme and Initech. Globex failed."]);+ expect(drawn.at(-1)).toMatchObject({ phase: "done", counts: { done: 2, failed: 1 }, failed: [{ title: "Globex" }] });+ });++ it("waits for a busy parent chat, then merges", async () => {+ const one = fresh({ limits: { parallel: 2, maxTasks: 50, smallPlan: false } });+ const { manager, started, merges, setMergeBusy, store } = one;+ const { burstId } = one.propose(items(2));+ setMergeBusy(true);+ manager.run(burstId);+ started.forEach((run) => { run.done(ok("x")); });+ expect(store.get(burstId)!.phase).toBe("merging");+ expect(merges).toHaveLength(0);+ await Promise.resolve();+ setMergeBusy(false);+ manager.recover();+ expect(merges).toHaveLength(1);+ });++ it("posts the parts as they came when the merge turn fails", () => {+ const one = fresh({ limits: { parallel: 2, maxTasks: 50, smallPlan: false } });+ const { manager, started, merges, delivered, posted } = one;+ const { burstId } = one.propose(items(2));+ manager.run(burstId);+ started.forEach((run) => { run.done(ok("result")); });+ merges[0]!.done({ ok: false, text: "" });+ expect(posted[0]!.map((child) => child.item)).toEqual(items(2));+ expect(delivered).toEqual(["parts as they came"]);+ });++ it("keeps the merge prompt within budget for a large burst", () => {+ const done: BurstChild[] = Array.from({ length: 200 }, (_, seq) => ({ burstId: "b", seq, item: `i${seq}`, title: `i${seq}`, status: "done", attempts: 1, result: "x".repeat(20_000) }));+ expect(mergePrompt({ task: "t" }, done, [], 0).length).toBeLessThan(170_000);+ });++ it("marks a child's words as the bot's own", () => {+ expect(childOpening({ task: "t", instructions: "do it" }, { seq: 0, item: "one" }, 2)).toMatch(/^\[Part 1 of 2 .*your own words, not the person's/);+ });+});++describe("a plan's limit on the list", () => {+ it("cuts a preview to the plan's limit and says how many were asked for", () => {+ const one = fresh({ limits: BURST_PLAN_LIMITS.starter! });+ const card = one.propose(items(20));+ expect(card).toMatchObject({ total: 10, requested: 20, taskLimit: 10, smallPlan: true, parallel: 2 });+ expect(one.store.get(card.burstId)!.counts.queued).toBe(10);+ });++ it("re-reads the plan when Run is pressed", () => {+ const one = fresh({ limits: BURST_PLAN_LIMITS.pro! });+ const { burstId } = one.propose(items(30));+ one.setLimits(BURST_PLAN_LIMITS.starter!);+ expect(one.manager.run(burstId)).toMatchObject({ total: 10, requested: 30, taskLimit: 10 });+ });++ it("edits a preview and cuts the new list too", () => {+ const one = fresh({ limits: BURST_PLAN_LIMITS.starter! });+ const { manager, store, propose } = one;+ const { burstId } = propose(items(4));+ expect(manager.edit(burstId, { items: items(15), instructions: "New words." })).toMatchObject({ total: 10, requested: 15, taskLimit: 10 });+ expect(store.get(burstId)!.instructions).toBe("New words.");+ expect(manager.view(burstId)!.items).toHaveLength(10);+ manager.run(burstId);+ expect(manager.edit(burstId, { items: items(2) })).toHaveProperty("refused");+ });+});++describe("after a restart", () => {+ it("puts running parts back in line and runs them again on the same thread", () => {+ const one = fresh({ limits: { parallel: 2, maxTasks: 50, smallPlan: false } });+ const { manager, started, store } = one;+ const { burstId } = one.propose(items(3));+ manager.run(burstId);+ expect(started.map((run) => run.child.threadId)).toEqual(["thread-1", "thread-2"]);+ const restarted = createBurstManager({ store, limits: () => ({ parallel: 2, maxTasks: 50, smallPlan: false }), hasRoom: () => true,+ openThread: () => "thread-new", startChild: async (burst, child, text, done) => { started.push({ burst, child, text, done }); }, stopChild: () => {},+ startMerge: async () => true, draw: () => undefined, postParts: () => "", deliver: () => {}, log: () => {} });+ started.length = 0;+ restarted.recover();+ expect(started.map((run) => run.child.threadId)).toEqual(["thread-1", "thread-2"]);+ restarted.close();+ });+});++describe("a child's start", () => {+ it("is retried when the thread is busy for now, and fails with the reason otherwise", async () => {+ vi.useFakeTimers();+ try {+ const store = openBurstStore(":memory:");+ let tries = 0;+ const finished: Array<() => void> = [];+ const manager = createBurstManager({ store, limits: () => ({ parallel: 1, maxTasks: 50, smallPlan: false }), hasRoom: () => true, openThread: () => "t",+ startChild: (_burst, child, _text, done) => {+ if (child.item === "busy" && ++tries < 3) return Promise.reject(Object.assign(new Error("busy"), { status: 409, code: "thread_busy" }));+ if (child.item === "bad") return Promise.reject(new Error("no such engine"));+ finished.push(() => done(ok("ok")));+ return Promise.resolve();+ }, stopChild: () => {}, startMerge: async () => false, draw: () => undefined, postParts: () => "", deliver: () => {}, log: () => {} });+ const card = manager.propose({ botId: "b", threadId: "p", task: "t", instructions: "", items: ["busy", "bad"], model: { instanceId: "i", model: "m" }, modelName: "m" });+ manager.run((card as BurstCardData).burstId);+ await vi.advanceTimersByTimeAsync(20_000);+ expect(tries).toBe(3);+ expect(finished).toHaveLength(1);+ finished[0]!();+ await vi.advanceTimersByTimeAsync(20_000);+ const rows = manager.view((card as BurstCardData).burstId)!.children;+ expect(rows[0]).toMatchObject({ status: "done" });+ expect(rows[1]).toMatchObject({ status: "failed", error: "no such engine" });+ manager.close();+ store.close();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/server/burst/manager.ts b/server/burst/manager.tsnew file mode 100644index 0000000000..2a4021a244--- /dev/null+++ b/server/burst/manager.ts@@ -0,0 +1,356 @@+// A burst from proposal to one merged result. Every step costs what its own child costs, never what the burst has queued:+// counts live on the burst row, children are taken from an index, and a full read happens once, when the burst settles.+import { randomUUID } from "node:crypto";++import type { BurstCardData, BurstChildRow, BurstView } from "../../shared/burst.ts";+import type { ModelSelection } from "../../shared/wire.ts";+import { BurstLane } from "./lane.ts";+import type { BurstLimits } from "./limits.ts";+import { burstRow, type BurstChild, type BurstRecord, type BurstStore } from "./store.ts";++const MINUTES_PER_TASK = 3;+const TICK_MS = 3_000;+const START_ATTEMPTS = 5;+const REASON_MAX = 200;+const RESULT_MAX = 20_000;+const FAILURES_SHOWN = 10;+/** What one merge turn reads of all the parts together: a burst of any size fits one engine's context. */+const MERGE_BUDGET = 150_000;+export const ITEM_MAX = 2_000;+export const INSTRUCTIONS_MAX = 12_000;++/** How a child's turn or a merge turn ended. */+export interface BurstTurnOutcome {+ ok: boolean;+ text: string;+ /** It stopped to ask the person something. */+ asked?: boolean;+}++/** The server's refusal to start a turn now, for a reason that passes (the thread is busy, the account is settling). */+export const startsLater = (error: unknown): boolean => (error as { status?: number })?.status === 409+ && ["thread_busy", "settling", "thread_limit"].includes((error as { code?: string }).code ?? "");++export interface BurstManagerDeps {+ store: BurstStore;+ limits(): BurstLimits;+ /** Whether one more burst thread may start now: the person's own work goes first. */+ hasRoom(): boolean;+ /** The bot's name and the thread a child runs in. Null when the bot is gone. */+ openThread(burst: BurstRecord, child: BurstChild): string | null;+ startChild(burst: BurstRecord, child: BurstChild & { threadId: string }, text: string, done: (outcome: BurstTurnOutcome) => void): Promise<void>;+ stopChild(burst: BurstRecord, child: BurstChild): void;+ /** Starts the merge turn in the parent thread on the bot's own model; `text` is read only then, so a busy parent costs no read of the parts. False when that thread is busy. */+ startMerge(burst: BurstRecord, text: () => string, done: (outcome: BurstTurnOutcome) => void): Promise<boolean>;+ /** Draws the card, or redraws it in place; returns its message id. */+ draw(burst: BurstRecord, card: BurstCardData): string | undefined;+ /** The merge turn could not write a result: post the parts as they came. */+ postParts(burst: BurstRecord, parts: BurstChild[]): string;+ /** The merged result reached the chat: put it in the person's Inbox too. */+ deliver(burst: BurstRecord, text: string): void;+ now?: () => number;+ log?: (line: string) => void;+}++export interface BurstProposal {+ botId: string;+ threadId: string;+ task: string;+ instructions: string;+ items: readonly string[];+ model: ModelSelection;+ modelName: string;+}++export type BurstRefusal = { refused: string };++const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text);+const oneLine = (text: string) => text.replace(/\s+/g, " ").trim();+const reasonOf = (text: string, fallback: string) => clip(oneLine(text) || fallback, REASON_MAX);++export function childOpening(burst: Pick<BurstRecord, "instructions" | "task">, child: Pick<BurstChild, "seq" | "item">, total: number): string {+ return `[Part ${child.seq + 1} of ${total} of a burst you run for this request: ${oneLine(burst.task)}. It is your own words, not the person's. Work on this part only and end with a clear result, since it will be merged with the others. Do not ask questions: if something is unclear, make a sensible choice and say so. Do not open other threads.]\n\n${burst.instructions}\n\nThis part: ${child.item}`;+}++export function mergePrompt(burst: Pick<BurstRecord, "task">, done: readonly BurstChild[], failed: readonly BurstChild[], cancelled: number): string {+ const each = Math.min(RESULT_MAX, Math.floor(MERGE_BUDGET / Math.max(1, done.length)));+ const parts = done.map((child) => `## ${child.title}\n${clip(child.result ?? "", each)}`);+ const failures = failed.map((child) => `- ${child.title}: ${child.error ?? "it did not finish"}`);+ const left = cancelled > 0 ? ` ${cancelled} more were cancelled.` : "";+ return `[The burst you ran for this request has finished: ${oneLine(burst.task)}. ${done.length} parts are done and ${failed.length} failed.${left} Write one merged result for the person here, in your own words, from the parts below: do not repeat the work or open threads. Then name every part that failed, and say why. Keep it as short as the result allows.]\n\n${parts.join("\n\n")}${failures.length ? `\n\nParts that failed:\n${failures.join("\n")}` : ""}`;+}++type Slot = { burst: BurstRecord; child: BurstChild };++export function createBurstManager(deps: BurstManagerDeps) {+ const { store } = deps;+ const now = deps.now ?? Date.now;+ const log = deps.log ?? ((line: string) => console.error(`burst: ${line}`));+ /** Bursts with children still queued, in the order they started: one is dropped when it runs dry, so a step never rescans it. */+ const queued: string[] = [];+ const ownThreads = new Set<string>();+ const merging = new Set<string>();+ let timer: ReturnType<typeof setInterval> | null = null;++ const lane = new BurstLane<Slot>({+ parallel: () => deps.limits().parallel,+ hasRoom: deps.hasRoom,+ next() {+ while (queued.length > 0) {+ const burst = store.get(queued[0]!);+ if (burst?.phase === "running") {+ const child = store.takeQueued(burst.id);+ if (child) return { burst, child };+ }+ queued.shift();+ }+ return undefined;+ },+ begin: ({ burst, child }) => { begin(burst, child); },+ });++ function card(burst: BurstRecord, failures?: BurstChild[]): BurstCardData {+ const limits = deps.limits();+ const total = burst.counts.queued + burst.counts.running + burst.counts.done + burst.counts.failed + burst.counts.cancelled;+ const parallel = Math.min(limits.parallel, Math.max(total, 1));+ const shown = failures?.slice(0, FAILURES_SHOWN).map((child) => ({ title: child.title, reason: child.error ?? "" }));+ return {+ version: 1, burstId: burst.id, botId: burst.botId, task: burst.task, phase: burst.phase, total, requested: burst.requested, parallel,+ ...(burst.requested > total ? { taskLimit: limits.maxTasks } : {}), ...(limits.smallPlan ? { smallPlan: true as const } : {}),+ modelName: burst.modelName, estimateMinutes: Math.max(1, Math.ceil(total / Math.max(1, limits.parallel)) * MINUTES_PER_TASK), counts: burst.counts, sample: burst.sample,+ ...(shown?.length ? { failed: shown, ...(failures!.length > shown.length ? { failedMore: failures!.length - shown.length } : {}) } : {}),+ };+ }++ function draw(burst: BurstRecord, failures?: BurstChild[]): BurstRecord {+ const messageId = deps.draw(burst, card(burst, failures));+ return messageId && messageId !== burst.cardMessageId ? store.update(burst.id, { cardMessageId: messageId }) ?? burst : burst;+ }++ function begin(burst: BurstRecord, child: BurstChild): void {+ let threadId = child.threadId;+ if (!threadId) {+ const opened = deps.openThread(burst, child);+ if (!opened) { failStart(burst, child, "The bot is no longer here."); return; }+ threadId = opened;+ store.setThread(burst.id, child.seq, threadId);+ }+ ownThreads.add(threadId);+ const running = { ...child, threadId };+ let ended = false;+ const end = (outcome: BurstTurnOutcome) => { if (!ended) { ended = true; settle(burst.id, running, outcome); } };+ deps.startChild(burst, running, childOpening(burst, child, burst.counts.queued + burst.counts.running + burst.counts.done + burst.counts.failed + burst.counts.cancelled), end).catch((error: unknown) => {+ if (ended) return;+ ended = true;+ ownThreads.delete(threadId);+ if (startsLater(error) && child.attempts < START_ATTEMPTS) { store.requeue(burst.id, child.seq); enlist(burst.id); lane.release(); return; }+ failStart(burst, child, error instanceof Error ? error.message : String(error));+ });+ }++ function failStart(burst: BurstRecord, child: BurstChild, reason: string): void {+ store.settle(burst.id, child.seq, "failed", { error: reasonOf(reason, "It could not start.") });+ childEnded(burst.id);+ }++ function settle(burstId: string, child: BurstChild & { threadId: string }, outcome: BurstTurnOutcome): void {+ ownThreads.delete(child.threadId);+ const cancelled = store.get(burstId)?.phase === "cancelled";+ const fields = cancelled ? {} : outcome.asked+ ? { error: "It stopped to ask a question. Open its thread to answer." }+ : outcome.ok && outcome.text.trim()+ ? { result: clip(outcome.text.trim(), RESULT_MAX) }+ : { error: reasonOf(outcome.text, "It ended without a result.") };+ store.settle(burstId, child.seq, cancelled ? "cancelled" : "result" in fields ? "done" : "failed", fields);+ childEnded(burstId);+ }++ function childEnded(burstId: string): void {+ lane.release();+ const burst = store.get(burstId);+ if (!burst) return;+ if (burst.phase !== "running") { draw(burst); return; }+ if (burst.counts.queued > 0 || burst.counts.running > 0) { draw(burst); return; }+ settled(burst);+ }++ /** Every child has ended. The one full read of a burst. */+ function settled(burst: BurstRecord): void {+ if (burst.counts.done === 0 && burst.counts.failed === 0) {+ draw(store.update(burst.id, { phase: "cancelled" }) ?? burst);+ stopIfIdle();+ return;+ }+ const failures = store.childrenIn(burst.id, "failed");+ draw(store.update(burst.id, { phase: "merging" }) ?? burst, failures);+ merge(burst.id);+ }++ function merge(burstId: string): void {+ const burst = store.get(burstId);+ if (!burst || burst.phase !== "merging" || merging.has(burstId)) return;+ merging.add(burstId);+ let done: BurstChild[] = [], failed: BurstChild[] = [];+ const read = () => {+ done = store.childrenIn(burstId, "done");+ failed = store.childrenIn(burstId, "failed");+ return mergePrompt(burst, done, failed, burst.counts.cancelled);+ };+ let ended = false;+ const end = (outcome: BurstTurnOutcome) => {+ if (ended) return;+ ended = true;+ merging.delete(burstId);+ finish(burst, done, failed, outcome);+ };+ deps.startMerge(burst, read, end).then((started) => {+ if (!started && !ended) { ended = true; merging.delete(burstId); }+ }, (error: unknown) => {+ if (ended) return;+ ended = true;+ merging.delete(burstId);+ log(`${burstId} merge could not start: ${error instanceof Error ? error.message : String(error)}`);+ if (done.length === 0 && failed.length === 0) read();+ finish(burst, done, failed, { ok: false, text: "" });+ });+ }++ function finish(burst: BurstRecord, done: BurstChild[], failed: BurstChild[], outcome: BurstTurnOutcome): void {+ const text = outcome.ok && outcome.text.trim() ? outcome.text.trim() : deps.postParts(burst, [...done, ...failed]);+ const current = store.update(burst.id, { phase: "done" }) ?? burst;+ draw(current, failed);+ deps.deliver(current, text);+ stopIfIdle();+ }++ function enlist(burstId: string): void {+ if (!queued.includes(burstId)) queued.push(burstId);+ }++ function ensureTimer(): void {+ timer ??= setInterval(tick, TICK_MS);+ timer.unref?.();+ }++ function stopIfIdle(): void {+ if (timer && store.active().length === 0) { clearInterval(timer); timer = null; }+ }++ /** Children whose turn could not start get another chance here, and merges waiting for a free parent thread. */+ function tick(): void {+ lane.pump();+ for (const burst of store.active()) if (burst.phase === "merging") merge(burst.id);+ stopIfIdle();+ }++ /** The list the plan allows, cut to its limit. */+ function allowed(items: readonly string[]): string[] {+ return items.slice(0, deps.limits().maxTasks);+ }++ return {+ /** The server's rule for what a bot may propose, whatever its tool call says. */+ propose(input: BurstProposal): BurstCardData | BurstRefusal {+ const task = clip(oneLine(input.task), 500);+ const items = input.items.map((item) => clip(item.trim(), ITEM_MAX)).filter(Boolean);+ if (!task) return { refused: "A burst needs a task." };+ if (items.length < 2) return { refused: "A burst needs at least two items. One item runs fine in this chat." };+ const kept = allowed(items);+ const burst = store.create({ id: randomUUID(), botId: input.botId, threadId: input.threadId, task, instructions: input.instructions.trim().slice(0, INSTRUCTIONS_MAX),+ model: input.model, modelName: input.modelName, requested: items.length, createdAt: now(), items: kept });+ return card(draw(burst));+ },+ /** Saves a change to a preview. Only a preview changes. */+ edit(id: string, plan: { instructions?: string; items?: readonly string[] }): BurstCardData | BurstRefusal {+ const burst = store.get(id);+ if (!burst) return { refused: "That burst is gone." };+ if (burst.phase !== "preview") return { refused: "This burst already ran." };+ const items = plan.items?.map((item) => clip(item.trim(), ITEM_MAX)).filter(Boolean);+ if (items && items.length < 2) return { refused: "A burst needs at least two items." };+ const instructions = plan.instructions?.trim().slice(0, INSTRUCTIONS_MAX);+ const next = store.replacePlan(id, { ...(instructions !== undefined ? { instructions } : {}), ...(items ? { items: allowed(items), requested: items.length } : {}) }) ?? burst;+ return card(draw(next));+ },+ /** Only a person's press reaches this. The plan is read again here, not taken from the preview. */+ run(id: string): BurstCardData | BurstRefusal {+ let burst = store.get(id);+ if (!burst) return { refused: "That burst is gone." };+ if (burst.phase !== "preview") return { refused: "This burst has already started." };+ const limit = deps.limits().maxTasks;+ if (burst.counts.queued > limit) burst = store.replacePlan(id, { items: store.childrenIn(id, "queued").slice(0, limit).map((child) => child.item) }) ?? burst;+ const running = store.update(id, { phase: "running" }) ?? burst;+ enlist(id);+ ensureTimer();+ const drawn = draw(running);+ lane.pump();+ return card(store.get(id) ?? drawn);+ },+ /** Cancel on the preview, or Cancel all once running. */+ cancel(id: string): BurstCardData | BurstRefusal {+ const burst = store.get(id);+ if (!burst) return { refused: "That burst is gone." };+ if (burst.phase === "done" || burst.phase === "cancelled") return card(burst);+ store.cancelQueued(id);+ const stopping = store.childrenIn(id, "running");+ const current = store.update(id, { phase: "cancelled" }) ?? burst;+ for (const child of stopping) deps.stopChild(current, child);+ stopIfIdle();+ return card(draw(store.get(id) ?? current));+ },+ /** Failed parts run again, and the result is merged again. */+ retryFailed(id: string): BurstCardData | BurstRefusal {+ const burst = store.get(id);+ if (!burst) return { refused: "That burst is gone." };+ if (burst.phase !== "running" && burst.phase !== "done") return { refused: "Nothing to retry right now." };+ if (store.requeueFailed(id).length === 0) return { refused: "Nothing failed." };+ const running = store.update(id, { phase: "running" }) ?? burst;+ enlist(id);+ ensureTimer();+ const drawn = draw(running);+ lane.pump();+ return card(store.get(id) ?? drawn);+ },+ /** The rows a card lists when opened. */+ view(id: string): BurstView | null {+ const burst = store.get(id);+ if (!burst) return null;+ const children = store.children(id);+ return { burstId: id, phase: burst.phase, instructions: burst.instructions, items: children.map((child) => child.item), children: children.map(burstRow) };+ },+ /** Who owns this burst, for the caller's access check. */+ owner(id: string): Pick<BurstRecord, "botId" | "threadId"> | null {+ const burst = store.get(id);+ return burst ? { botId: burst.botId, threadId: burst.threadId } : null;+ },+ /** Whether this thread is a burst thread running in the lane now, outside the plan's turn caps. */+ laneOwned(threadId: string): boolean {+ return ownThreads.has(threadId);+ },+ /** After a restart: a running turn is gone, so its part goes back in line, and a merge waiting on its turn tries again. */+ recover(): void {+ for (const burst of store.active()) {+ if (burst.phase === "running") { store.requeueRunning(burst.id); enlist(burst.id); }+ ensureTimer();+ }+ tick();+ },+ pump(): void {+ lane.pump();+ },+ /** How many burst threads are running in the lane. */+ runningCount(): number {+ return lane.runningCount();+ },+ prune(before: number): number {+ return store.prune(before);+ },+ close(): void {+ if (timer) clearInterval(timer);+ timer = null;+ },+ };+}++export type BurstManager = ReturnType<typeof createBurstManager>;++export type { BurstChildRow };diff --git a/server/burst/store.ts b/server/burst/store.tsnew file mode 100644index 0000000000..64eb21a662--- /dev/null+++ b/server/burst/store.ts@@ -0,0 +1,246 @@+// Durable bursts. Counts live on the burst row and every change to a child updates them in one transaction, so reading a+// burst's progress never scans its children, however large it is.+import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";+import { dirname, join } from "node:path";+import { DatabaseSync } from "node:sqlite";++import type { BurstChildRow, BurstChildStatus, BurstCounts, BurstPhase } from "../../shared/burst.ts";+import type { ModelSelection } from "../../shared/wire.ts";++export interface BurstRecord {+ id: string;+ botId: string;+ threadId: string;+ cardMessageId?: string;+ phase: BurstPhase;+ task: string;+ instructions: string;+ model: ModelSelection;+ modelName: string;+ /** Tasks the bot proposed, before the plan's task limit. */+ requested: number;+ /** The first few tasks, for the preview. */+ sample: string[];+ counts: BurstCounts;+ createdAt: number;+}++export interface BurstChild {+ burstId: string;+ seq: number;+ item: string;+ title: string;+ status: BurstChildStatus;+ threadId?: string;+ attempts: number;+ result?: string;+ error?: string;+}++const EMPTY: BurstCounts = { queued: 0, running: 0, done: 0, failed: 0, cancelled: 0 };++const SCHEMA = `+CREATE TABLE IF NOT EXISTS bursts (+ id TEXT PRIMARY KEY,+ json TEXT NOT NULL,+ phase TEXT NOT NULL,+ created_at INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS bursts_phase ON bursts(phase);+CREATE TABLE IF NOT EXISTS burst_children (+ burst_id TEXT NOT NULL,+ seq INTEGER NOT NULL,+ json TEXT NOT NULL,+ status TEXT NOT NULL,+ PRIMARY KEY (burst_id, seq)+);+CREATE INDEX IF NOT EXISTS burst_children_status ON burst_children(burst_id, status, seq);+`;++const titleOf = (item: string): string => {+ const line = item.replace(/\s+/g, " ").trim();+ return line.length > 80 ? `${line.slice(0, 79).trimEnd()}…` : line;+};++export const sampleOf = (items: readonly string[]): string[] => items.slice(0, 5).map(titleOf);++export function openBurstStore(dataDir: string) {+ const file = dataDir === ":memory:" ? ":memory:" : join(dataDir, "bursts.db");+ if (file !== ":memory:") {+ mkdirSync(dirname(file), { recursive: true });+ closeSync(openSync(file, "a", 0o600));+ chmodSync(file, 0o600);+ }+ const db = new DatabaseSync(file);+ db.exec("PRAGMA journal_mode = WAL");+ db.exec(SCHEMA);+ const rows = {+ insertBurst: db.prepare("INSERT INTO bursts (id, json, phase, created_at) VALUES (?, ?, ?, ?)"),+ updateBurst: db.prepare("UPDATE bursts SET json = ?, phase = ? WHERE id = ?"),+ getBurst: db.prepare("SELECT json FROM bursts WHERE id = ?"),+ activeBursts: db.prepare("SELECT json FROM bursts WHERE phase IN ('running', 'merging') ORDER BY created_at"),+ deleteBurst: db.prepare("DELETE FROM bursts WHERE id = ?"),+ oldBursts: db.prepare("SELECT id FROM bursts WHERE phase IN ('done', 'cancelled') AND created_at < ?"),+ insertChild: db.prepare("INSERT INTO burst_children (burst_id, seq, json, status) VALUES (?, ?, ?, ?)"),+ updateChild: db.prepare("UPDATE burst_children SET json = ?, status = ? WHERE burst_id = ? AND seq = ?"),+ getChild: db.prepare("SELECT json FROM burst_children WHERE burst_id = ? AND seq = ?"),+ nextQueued: db.prepare("SELECT json FROM burst_children WHERE burst_id = ? AND status = 'queued' ORDER BY seq LIMIT 1"),+ childrenOf: db.prepare("SELECT json FROM burst_children WHERE burst_id = ? ORDER BY seq"),+ childrenIn: db.prepare("SELECT json FROM burst_children WHERE burst_id = ? AND status = ? ORDER BY seq"),+ deleteChildren: db.prepare("DELETE FROM burst_children WHERE burst_id = ?"),+ };+ const parseBurst = (row: unknown): BurstRecord => JSON.parse((row as { json: string }).json) as BurstRecord;+ const parseChild = (row: unknown): BurstChild => JSON.parse((row as { json: string }).json) as BurstChild;+ const transaction = <T>(run: () => T): T => {+ db.exec("BEGIN");+ try {+ const result = run();+ db.exec("COMMIT");+ return result;+ } catch (error) {+ db.exec("ROLLBACK");+ throw error;+ }+ };+ const writeBurst = (burst: BurstRecord) => { rows.updateBurst.run(JSON.stringify(burst), burst.phase, burst.id); };+ const writeChild = (child: BurstChild) => { rows.updateChild.run(JSON.stringify(child), child.status, child.burstId, child.seq); };+ const insertChild = (id: string, seq: number, item: string) => {+ const child: BurstChild = { burstId: id, seq, item, title: titleOf(item), status: "queued", attempts: 0 };+ rows.insertChild.run(id, seq, JSON.stringify(child), "queued");+ };+ const getBurst = (id: string): BurstRecord | undefined => {+ const row = rows.getBurst.get(id);+ return row ? parseBurst(row) : undefined;+ };+ /** Moves a child to `status` and the counts with it, in one transaction. */+ const move = (burstId: string, seq: number, status: BurstChildStatus, change: (child: BurstChild) => void = () => {}): BurstChild | undefined =>+ transaction(() => {+ const row = rows.getChild.get(burstId, seq);+ const burst = getBurst(burstId);+ if (!row || !burst) return undefined;+ const child = parseChild(row);+ change(child);+ burst.counts[child.status] -= 1;+ burst.counts[status] += 1;+ child.status = status;+ writeChild(child);+ writeBurst(burst);+ return child;+ });+ /** Every child in `from` moves to `to`, counted once at the end. */+ const moveAll = (burstId: string, from: BurstChildStatus, to: BurstChildStatus, change: (child: BurstChild) => void = () => {}): BurstChild[] =>+ transaction(() => {+ const burst = getBurst(burstId);+ if (!burst) return [];+ const moved = rows.childrenIn.all(burstId, from).map(parseChild);+ for (const child of moved) {+ change(child);+ child.status = to;+ writeChild(child);+ }+ burst.counts[from] -= moved.length;+ burst.counts[to] += moved.length;+ writeBurst(burst);+ return moved;+ });+ return {+ create(input: Omit<BurstRecord, "counts" | "phase" | "sample"> & { items: readonly string[] }): BurstRecord {+ const { items, ...fields } = input;+ const burst: BurstRecord = { ...fields, phase: "preview", sample: sampleOf(items), counts: { ...EMPTY, queued: items.length } };+ transaction(() => {+ rows.insertBurst.run(burst.id, JSON.stringify(burst), burst.phase, burst.createdAt);+ items.forEach((item, seq) => insertChild(burst.id, seq, item));+ });+ return burst;+ },+ get: getBurst,+ child(burstId: string, seq: number): BurstChild | undefined {+ const row = rows.getChild.get(burstId, seq);+ return row ? parseChild(row) : undefined;+ },+ children(burstId: string): BurstChild[] {+ return rows.childrenOf.all(burstId).map(parseChild);+ },+ active(): BurstRecord[] {+ return rows.activeBursts.all().map(parseBurst);+ },+ update(id: string, patch: Partial<Pick<BurstRecord, "phase" | "cardMessageId">>): BurstRecord | undefined {+ return transaction(() => {+ const burst = getBurst(id);+ if (!burst) return undefined;+ Object.assign(burst, patch);+ writeBurst(burst);+ return burst;+ });+ },+ /** A preview's new list. */+ replacePlan(id: string, plan: { instructions?: string; items?: readonly string[]; requested?: number }): BurstRecord | undefined {+ return transaction(() => {+ const burst = getBurst(id);+ if (!burst) return undefined;+ if (plan.instructions !== undefined) burst.instructions = plan.instructions;+ if (plan.items) {+ rows.deleteChildren.run(id);+ plan.items.forEach((item, seq) => insertChild(id, seq, item));+ burst.counts = { ...EMPTY, queued: plan.items.length };+ burst.sample = sampleOf(plan.items);+ if (plan.requested !== undefined) burst.requested = plan.requested;+ }+ writeBurst(burst);+ return burst;+ });+ },+ /** The next queued child of this burst, now running: one indexed read. */+ takeQueued(burstId: string): BurstChild | undefined {+ const row = rows.nextQueued.get(burstId);+ return row ? move(burstId, parseChild(row).seq, "running", (child) => { child.attempts += 1; delete child.error; }) : undefined;+ },+ setThread(burstId: string, seq: number, threadId: string): void {+ transaction(() => {+ const row = rows.getChild.get(burstId, seq);+ if (!row) return;+ const child = parseChild(row);+ child.threadId = threadId;+ writeChild(child);+ });+ },+ /** A running child ended, unless a cancel settled it first. */+ settle(burstId: string, seq: number, status: "done" | "failed" | "cancelled", fields: { result?: string; error?: string }): BurstChild | undefined {+ const row = rows.getChild.get(burstId, seq);+ if (!row || parseChild(row).status !== "running") return undefined;+ return move(burstId, seq, status, (child) => {+ if (fields.result !== undefined) child.result = fields.result;+ if (fields.error !== undefined) child.error = fields.error;+ });+ },+ requeue(burstId: string, seq: number): BurstChild | undefined {+ return move(burstId, seq, "queued");+ },+ requeueRunning(burstId: string): BurstChild[] {+ return moveAll(burstId, "running", "queued");+ },+ /** Failed children go back in line, with their reason cleared. */+ requeueFailed(burstId: string): BurstChild[] {+ return moveAll(burstId, "failed", "queued", (child) => { delete child.error; delete child.result; });+ },+ cancelQueued(burstId: string): BurstChild[] {+ return moveAll(burstId, "queued", "cancelled");+ },+ childrenIn(burstId: string, status: BurstChildStatus): BurstChild[] {+ return rows.childrenIn.all(burstId, status).map(parseChild);+ },+ prune(before: number): number {+ const old = rows.oldBursts.all(before) as Array<{ id: string }>;+ transaction(() => { for (const { id } of old) { rows.deleteChildren.run(id); rows.deleteBurst.run(id); } });+ return old.length;+ },+ close(): void {+ db.close();+ },+ };+}++export type BurstStore = ReturnType<typeof openBurstStore>;++export const burstRow = (child: BurstChild): BurstChildRow => ({ seq: child.seq, title: child.title, status: child.status,+ ...(child.threadId ? { threadId: child.threadId } : {}), ...(child.error ? { error: child.error } : {}) });diff --git a/server/engine-memory.test.ts b/server/engine-memory.test.tsindex 580aa0a73b..b7e93d3cb8 100644--- a/server/engine-memory.test.ts+++ b/server/engine-memory.test.ts@@ -891,3 +891,44 @@ describe("the day's memory pressure, for the Admin", () => {expect(ledger.read(start + 24 * 60 * 60_000 + 60_000)).toEqual({ waits: 0, waitMs: 0, stopped: 0, killed: 0, stallMinutes: 0 });});});++describe("a lane of its own", () => {+ const free = (bytes: number) => () => ({ totalBytes: 4 * GB, availableBytes: bytes, swapFreeBytes: 0, oomKills: 0, fullStall10: 0 });+ const lane = new Set(["burst-1", "burst-2"]);+ const capped = (running: string[], most = 2) => {+ const memory = new EngineMemory({ enabled: true, read: free(3 * GB), groups: () => new Map(), now: () => 0, signal: () => {}, log: () => {} });+ memory.useCap({ most: () => most, waitsOnOthers: () => false, laneOwned: (threadId) => lane.has(threadId) });+ for (const threadId of running) memory.turnStarted(threadId);+ return memory;+ };++ it("keeps a burst's threads out of the plan's turn cap, so a person's chat still starts", async () => {+ const memory = capped(["burst-1", "burst-2"]);+ await expect(memory.admit("persons-chat", new AbortController().signal, () => {}, "turn")).resolves.toBe(true);+ });++ it("lets a lane's thread past the cap the lane already counted", async () => {+ const memory = capped(["persons-chat-1", "persons-chat-2"]);+ await expect(memory.admit("burst-1", new AbortController().signal, () => {}, "turn")).resolves.toBe(true);+ });++ it("gives the lane no room under the plan's cap, its own turns counted", () => {+ expect(capped(["burst-1"]).laneHasRoom()).toBe(true);+ expect(capped(["burst-1", "persons-chat"]).laneHasRoom()).toBe(false);+ });++ it("gives the lane no room while the person's own work waits", async () => {+ const memory = capped(["busy-a", "busy-b"]);+ memory.useTurnOrder((threadId) => threadId === "persons-chat");+ const abort = new AbortController();+ const waiting = memory.admit("persons-chat", abort.signal, () => {}, "turn");+ await Promise.resolve();+ expect(memory.laneHasRoom()).toBe(false);+ abort.abort();+ await waiting;+ });++ it("is always open with the gate off", () => {+ expect(new EngineMemory({ enabled: false }).laneHasRoom()).toBe(true);+ });+});diff --git a/server/engine-memory.ts b/server/engine-memory.tsindex 31ce577938..8514fb390e 100644--- a/server/engine-memory.ts+++ b/server/engine-memory.ts@@ -147,6 +147,8 @@ export interface EngineCap {most(): number | undefined;/** Whether this thread's running turn waits on work it handed out: it holds no place, so the work it waits on can run. */waitsOnOthers(threadId: string): boolean;+ /** Whether a lane of its own runs this thread (a burst's): it neither takes a place under this limit nor waits for one. */+ laneOwned?(threadId: string): boolean;}/** An engine process and the threads whose sessions it runs: one, or several when the driver shares processes. */@@ -219,15 +221,29 @@ export class EngineMemory {/** The plan's limit when it is what this thread's turn must wait for now; undefined when there is a place. */private capped(threadId: string): number | undefined {const most = this.cap?.most();- if (most === undefined) return undefined;+ if (most === undefined || this.cap!.laneOwned?.(threadId)) return undefined;let running = 0;for (const other of new Set([...this.active, ...this.reserved.keys()])) {- if (other === threadId || this.cap!.waitsOnOthers(other)) continue;+ if (other === threadId || this.cap!.waitsOnOthers(other) || this.cap!.laneOwned?.(other)) continue;if (++running >= most) return most;}return undefined;}+ /** Whether a lane may start one more turn: nobody's own work is waiting, and under a plan's limit the whole machine, the+ * lane's own turns counted, has a place. Linear in the turns running and the ones waiting. */+ laneHasRoom(): boolean {+ if (!this.enabled) return true;+ if (this.queue.some((waiter) => this.personsOwn(waiter.threadId))) return false;+ const most = this.cap?.most();+ if (most === undefined) return true;+ let running = 0;+ for (const other of new Set([...this.active, ...this.reserved.keys()])) {+ if (!this.cap!.waitsOnOthers(other) && ++running >= most) return false;+ }+ return true;+ }+/** Whether a task is waiting for memory now. */waiting(): boolean { return this.waitingSince.size > 0; }diff --git a/shared/burst.ts b/shared/burst.tsnew file mode 100644index 0000000000..2f8d8a474e--- /dev/null+++ b/shared/burst.ts@@ -0,0 +1,55 @@+/** One burst: one person's task split into many threads of the same bot, run in parallel, merged into one result. */+export type BurstPhase = "preview" | "running" | "merging" | "done" | "cancelled";+export type BurstChildStatus = "queued" | "running" | "done" | "failed" | "cancelled";+export type BurstCounts = Record<BurstChildStatus, number>;++/** The card in the parent chat: a preview until the person presses Run, then the one progress card, patched in place. It+ * carries counts only, and the rows come from GET /api/bursts/<id>, so a card stays one small row however large the burst. */+export interface BurstCardData {+ version: 1;+ burstId: string;+ botId: string;+ task: string;+ phase: BurstPhase;+ /** Tasks that run. */+ total: number;+ /** Tasks the bot proposed: more than `total` when the plan's task limit cut the list. */+ requested: number;+ /** How many run at once here. */+ parallel: number;+ /** The plan's most tasks per burst, set when it cut this list. */+ taskLimit?: number;+ /** Set on a plan where a higher one runs more at once. */+ smallPlan?: true;+ modelName: string;+ /** A rough figure for the preview, in minutes. */+ estimateMinutes: number;+ counts: BurstCounts;+ /** The first few tasks, for the preview. */+ sample: string[];+ /** Parts that did not finish, named once the burst settles, with `failedMore` counting past the ones listed. */+ failed?: BurstFailure[];+ failedMore?: number;+}++export interface BurstFailure {+ title: string;+ reason: string;+}++/** One part of a burst, as GET /api/bursts/<id> lists it. `threadId` is absent until it starts. */+export interface BurstChildRow {+ seq: number;+ title: string;+ status: BurstChildStatus;+ threadId?: string;+ error?: string;+}++export interface BurstView {+ burstId: string;+ phase: BurstPhase;+ instructions: string;+ items: string[];+ children: BurstChildRow[];+}diff --git a/shared/wire.ts b/shared/wire.tsindex bffaf851be..1cbc90f5de 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -91,6 +91,8 @@ export interface TaskOpenedBy {* durable conversation between two bots; "work" closes itself once its* result has been reported. */kind?: "pair" | "work";+ /** The burst this thread is one part of: it is listed under that burst's card, not on its own. */+ burstId?: string;/** The opener's own conversation this "work" thread was opened from.* Everything that conversation later sends this bot continues here. */threadId?: string;