Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Let work handed on for the person's own request set one wait

Rutvij97a5d431dbc78a
diff --git a/docs/superpowers/specs/2026-10-27-waits-design.md b/docs/superpowers/specs/2026-10-27-waits-design.md
index 42221cf84d..eda05f0966 100644
--- a/docs/superpowers/specs/2026-10-27-waits-design.md
+++ b/docs/superpowers/specs/2026-10-27-waits-design.md
@@ -98,6 +98,10 @@ arguments) and stores those, never the token. Waits can be made only from a
direct chat turn the person started, with the same guest and outside-driven
checks `create_trigger` runs; rooms, routine runs and peer asks are refused (my
call).
+Work a bot handed on may make one wait when the person's own request started that
+work (the root's origin is the person's); it waits in the handed-on work's chat, is
+held to one open wait per assignment, and cannot cancel waits. Its follow-up still
+runs with outside provenance, so it cannot make another.
A wait with `then` is a one-off automation the bot wrote, so it is treated like
one (my call): creating it posts the same kind of visible card a new routine
diff --git a/server/handed-waits.e2e.test.ts b/server/handed-waits.e2e.test.ts
new file mode 100644
index 0000000000..5d00ef047f
--- /dev/null
+++ b/server/handed-waits.e2e.test.ts
@@ -0,0 +1,116 @@
+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb, type VerificationServer } from "../scripts/control-omb.ts";
+import { WAIT_MESSAGES } from "./routes/waits.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+import { readHandoffs } from "./testing/handoff-rows.ts";
+
+describe("waits set by work a bot handed on", () => {
+ let fixture: VerificationServer;
+ let folder: string;
+ let source: any;
+ let peer: any;
+ const call = async (method: string, path: string, body?: unknown, token?: string) => {
+ const response = await fetch(fixture.info.url + path, {
+ method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : { origin: fixture.info.url }) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json() as any };
+ };
+ const api = async (method: string, path: string, body?: unknown, token?: string) => {
+ const { status, body: value } = await call(method, path, body, token);
+ expect(status, `${method} ${path}: ${JSON.stringify(value)}`).toBeLessThan(300);
+ return value;
+ };
+ const control = (args: string[]) => runControlOmb([...args, "--url", fixture.info.url]);
+ const file = (threadId: string, extension: string) => join(fixture.info.dataDir, `${threadId}.${extension}`);
+ const finish = (threadId: string) => writeFileSync(file(threadId, "gate"), "finish isolated turn");
+ const token = async (threadId: string) => {
+ let value = "";
+ await expect.poll(() => {
+ try { value = JSON.parse(readFileSync(file(threadId, "json"), "utf8")).mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN; } catch { return false; }
+ return Boolean(value);
+ }, { timeout: 15_000 }).toBe(true);
+ return value;
+ };
+ const rows = () => readHandoffs(fixture.info.dataDir);
+ const handedWork = async (threadId: string) => {
+ const find = () => rows().find((node) => node.botId === peer.id && node.parentId && rows().find((root) => root.id === node.parentId)?.threadId === threadId);
+ await expect.poll(() => find()?.status, { timeout: 15_000 }).toBe("running");
+ return find()!;
+ };
+ const handOn = async (threadId: string) => {
+ const { receipts } = await api("POST", "/api/internal/coordinate-bots", { botIds: [peer.id], message: "Watch for the fixture report." }, await token(threadId));
+ expect(receipts).toHaveLength(1);
+ return handedWork(threadId);
+ };
+ const storedWaits = () => {
+ try { return (JSON.parse(readFileSync(join(fixture.info.dataDir, "waits.json"), "utf8")) as { waits?: any[] }).waits ?? []; } catch { return []; }
+ };
+ const fileWait = (label: string) => ({ label, kind: "file_exists", path: join(folder, `${label}.txt`) });
+
+ beforeEach(async () => {
+ folder = mkdtempSync(join(tmpdir(), "omb-handed-waits-"));
+ fixture = await launchVerificationServer();
+ source = (await control(["new-bot", "--name", "Wait owner"]) as any).bot;
+ peer = (await control(["new-bot", "--name", "Wait peer"]) as any).bot;
+ const wrapper = join(fixture.info.dataDir, "handed-gated.mjs");
+ writeFileSync(wrapper, [
+ "#!/usr/bin/env node",
+ 'import { readFileSync } from "node:fs";',
+ 'import { join } from "node:path";',
+ 'const at = process.argv.indexOf("--mcp-config");',
+ 'const thread = at < 0 ? "probe" : JSON.parse(readFileSync(process.argv[at + 1], "utf8")).mcpServers?.agents?.env?.OMB_THREAD_ID ?? "probe";',
+ 'process.env.FAKE_CLAUDE_MODE = thread === "probe" ? "happy" : "slow";',
+ `process.env.FAKE_CLAUDE_SLOW_FINISH_GATE = join(${JSON.stringify(fixture.info.dataDir)}, thread + ".gate");`,
+ `process.env.FAKE_CLAUDE_DUMP = join(${JSON.stringify(fixture.info.dataDir)}, thread + ".json");`,
+ `await import(${JSON.stringify(pathToFileURL(join(process.cwd(), "server/testing/fake-claude-cli.ts")).href)});`,
+ ].join("\n"), { mode: 0o700 });
+ await api("PATCH", "/api/instances/claude", { cli: wrapper });
+ }, 30_000);
+ afterEach(async () => {
+ await fixture?.close();
+ await removeTempDir(folder);
+ });
+
+ it("lets work handed on for the person's own request set one wait, never stop one, and not after it ends", async () => {
+ const sourceThread = (await api("GET", "/api/bots?messages=0")).bots.find((bot: any) => bot.id === source.id).threadId;
+ await control(["send", "--bot", source.id, "--text", "Have the peer tell me when the report lands."]);
+ const work = await handOn(sourceThread);
+ const handed = await token(work.threadId);
+
+ const made = await call("POST", "/api/internal/waits", fileWait("report"), handed);
+ expect(made.status, JSON.stringify(made.body)).toBe(201);
+ expect(storedWaits()).toEqual([expect.objectContaining({ label: "report", threadId: work.threadId, assignmentId: work.id })]);
+ const second = await call("POST", "/api/internal/waits", fileWait("second"), handed);
+ expect(second.status).toBe(409);
+ expect(second.body.error).toContain("keeps one wait at a time");
+ const id = /\(wait id ([\w-]+)\)/.exec(made.body.text)![1];
+ expect(await call("POST", "/api/internal/waits/cancel", { id }, handed)).toMatchObject({ status: 403, body: { error: WAIT_MESSAGES.handedStop } });
+ expect(storedWaits()).toHaveLength(1);
+
+ finish(work.threadId);
+ await expect.poll(() => rows().find((node) => node.id === work.id)?.status, { timeout: 15_000 }).not.toBe("running");
+ const late = await call("POST", "/api/internal/waits", fileWait("late"), handed);
+ expect(late.status).toBeGreaterThanOrEqual(400);
+ expect(storedWaits().map((wait) => wait.label)).toEqual(["report"]);
+ finish(sourceThread);
+ }, 60_000);
+
+ it("refuses a wait to work a routine handed on", async () => {
+ const { routine } = await api("POST", "/api/routines", {
+ name: "Handed watch", prompt: "Ask the peer to watch for the report.", botId: source.id,
+ enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 },
+ });
+ const { run } = await api("POST", `/api/routines/${routine.id}/run`);
+ await expect.poll(async () => (await api("GET", "/api/routines")).runs.find((r: any) => r.id === run.id)?.status, { timeout: 15_000 }).toBe("running");
+ const runThread = (await api("GET", "/api/routines")).runs.find((r: any) => r.id === run.id).threadId;
+ const work = await handOn(runThread);
+ expect(await call("POST", "/api/internal/waits", fileWait("routine"), await token(work.threadId))).toMatchObject({ status: 403, body: { error: WAIT_MESSAGES.notPerson } });
+ expect(storedWaits()).toEqual([]);
+ finish(work.threadId); finish(runThread);
+ }, 60_000);
+});
diff --git a/server/index.ts b/server/index.ts
index deb4b22ca0..fde8ef1b43 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -482,7 +482,7 @@ import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"
import { addressFor } from "./webhook-address.ts";
import { assertModelVariantSupported, memberTurnSelection } from "./member-turn.ts";
import { WebhookManager } from "./webhooks.ts";
-import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitRunChat } from "./wait-host.ts"; import { createWaitRoutes, findWaitPeer, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";
+import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitRunChat } from "./wait-host.ts"; import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";
import type { WebhookTrigger } from "../shared/webhooks.ts";
import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";
import { agentsProxyLaunch, agentsToolBridgeEnv, applyAgentsBridge, bridgedToolTitle, turnEngine } from "./agents-bridge-switch.ts"; import { agentsServerEnv, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, roomSkillsRefusal, type TurnKind } from "./agents-turn.ts";
@@ -11150,8 +11150,8 @@ function connectorThread(botId: string, threadId: string) {
return null;
}
function directChatOf(botId: string, threadId: string): boolean { const source = connectorThread(botId, threadId); return source !== null && !source.group; }
-function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick<WaitRouteContext, "sourceRefusal" | "hostRefusal" | "guest" | "peer" | "elsewhere"> { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; };
- return { sourceRefusal: () => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId) }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), hosted: HOSTED_WORKSPACE, guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; }
+function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick<WaitRouteContext, "sourceRefusal" | "assignmentId" | "hostRefusal" | "guest" | "peer" | "elsewhere"> { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; }, assignmentId = () => handedAssignment(capability.roomHandoffId ?? directCoordinationSettlers.get(capability.generation)?.nodeId, (id) => coordinator.node(id));
+ return { assignmentId, sourceRefusal: (op, assignment) => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId), op, assignmentId: assignment }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), hosted: HOSTED_WORKSPACE, guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; }
/** Read fresh every time; a line stamped via the HTTP API does not count, so a bot cannot re-arm the ceiling it just spent. */
function lastHumanRoomMessageAt(group: GroupRecord): number | undefined {
diff --git a/server/routes/waits.test.ts b/server/routes/waits.test.ts
index bea3e36b87..2f75e9a550 100644
--- a/server/routes/waits.test.ts
+++ b/server/routes/waits.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import { WAIT_KINDS } from "../../shared/waits.ts";
import type { NewWait, WaitRecord } from "../waits.ts";
-import { createWaitRoutes, findWaitPeer, hostWaitRefusal, isNetworkPath, parseWaitRequest, waitSourceRefusal, WAIT_MESSAGES } from "./waits.ts";
+import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, isNetworkPath, parseWaitRequest, waitSourceRefusal, WAIT_MESSAGES } from "./waits.ts";
import { PASS } from "./table.ts";
const HOME = "/home/maus";
@@ -186,6 +186,53 @@ describe("the waits route", () => {
expect(waitSourceRefusal({ ...person, ...other }), JSON.stringify(other)).toBe(WAIT_MESSAGES.notPerson);
}
});
+ it("lets work a bot handed on make one wait, never stop one, only when the person's own request started it", () => {
+ const handed = { owned: true, room: false, depth: 1, handedOff: false, routineRun: false, outsideDriven: false, personStarted: true, guest: false, assignmentId: "a1" };
+ expect(waitSourceRefusal({ ...handed, op: "create" })).toBeNull();
+ expect(waitSourceRefusal({ ...handed, depth: 0, handedOff: true, op: "create" })).toBeNull();
+ expect(waitSourceRefusal({ ...handed, op: "cancel" })).toBe(WAIT_MESSAGES.handedStop);
+ expect(waitSourceRefusal(handed)).toBe(WAIT_MESSAGES.handedStop);
+ for (const other of [{ personStarted: false }, { guest: true }, { assignmentId: undefined }, { routineRun: true }, { outsideDriven: true }]) {
+ expect(waitSourceRefusal({ ...handed, ...other, op: "create" }), JSON.stringify(other)).toBe(WAIT_MESSAGES.notPerson);
+ }
+ expect(waitSourceRefusal({ ...handed, room: true, op: "create" })).toBe(WAIT_MESSAGES.room);
+ expect(waitSourceRefusal({ ...handed, owned: false, op: "create" })).toBe(WAIT_MESSAGES.notYours);
+ });
+ it("holds a handed-on wait to its running assignment, never a root or one that ended", () => {
+ const nodes: Record<string, { id: string; parentId?: string; status: string }> = {
+ child: { id: "child", parentId: "root", status: "running" },
+ root: { id: "root", status: "running" },
+ done: { id: "done", parentId: "root", status: "completed" },
+ };
+ const node = (id: string) => nodes[id];
+ expect(handedAssignment("child", node)).toBe("child");
+ expect([handedAssignment("root", node), handedAssignment("done", node), handedAssignment("gone", node), handedAssignment(undefined, node)])
+ .toEqual([undefined, undefined, undefined, undefined]);
+ });
+ it("asks for making or stopping, and records the handed-on assignment with the wait", async () => {
+ waits.create.mockClear();
+ const ops: string[] = [];
+ const sourceRefusal = (op: "create" | "cancel") => { ops.push(op); return op === "cancel" ? WAIT_MESSAGES.handedStop : null; };
+ expect((await call("POST", "/api/internal/waits", FILE_WAIT, { sourceRefusal, assignmentId: () => "a1" })).status).toBe(201);
+ expect(waits.create).toHaveBeenCalledWith(expect.objectContaining({ assignmentId: "a1" }));
+ expect(await call("POST", "/api/internal/waits/cancel", { id: "w1" }, { sourceRefusal, assignmentId: () => "a1" })).toMatchObject({ status: 403, payload: { error: WAIT_MESSAGES.handedStop } });
+ expect(ops).toEqual(["create", "cancel"]);
+ waits.create.mockClear();
+ await call("POST", "/api/internal/waits", FILE_WAIT);
+ expect(waits.create.mock.calls[0]![0]).not.toHaveProperty("assignmentId");
+ });
+ it("reads the handed-on assignment once, before the body, and refuses if it ends meanwhile", async () => {
+ waits.create.mockClear();
+ let reads = 0;
+ const seen: (string | undefined)[] = [];
+ const sourceRefusal = (_op: "create" | "cancel", assignment: string | undefined) => { seen.push(assignment); return null; };
+ expect((await call("POST", "/api/internal/waits", FILE_WAIT, { sourceRefusal, assignmentId: () => "a1" })).status).toBe(201);
+ expect(seen).toEqual(["a1"]);
+ expect(waits.create).toHaveBeenCalledWith(expect.objectContaining({ assignmentId: "a1" }));
+ waits.create.mockClear();
+ expect(await call("POST", "/api/internal/waits", FILE_WAIT, { sourceRefusal, assignmentId: () => (reads++ === 0 ? "a1" : undefined) })).toMatchObject({ status: 403, payload: { error: WAIT_MESSAGES.notPerson } });
+ expect(waits.create).not.toHaveBeenCalled();
+ });
it("offers files and programs only on the bot's own computer", () => {
const own = { cloudHome: false, hosted: false, guest: false, place: null };
for (const place of [null, "local", "browser"] as const) expect(hostWaitRefusal({ ...own, place })).toBeNull();
diff --git a/server/routes/waits.ts b/server/routes/waits.ts
index 11cece5c28..1bc7f7b565 100644
--- a/server/routes/waits.ts
+++ b/server/routes/waits.ts
@@ -15,7 +15,8 @@ const CANCEL = "/api/internal/waits/cancel";
export const WAIT_MESSAGES = {
notYours: "This conversation is not yours.",
room: "Waits are made in a one-to-one chat with the person, not in a room.",
- notPerson: "Only the person can set up or stop a wait, in their own chat with you; work handed to you by a bot, a routine or an outside event cannot.",
+ notPerson: "Only the person can set up or stop a wait, in their own chat with you; a routine or an outside event cannot, and work a bot handed you can set one only when the person's own request started it.",
+ handedStop: "Work handed to you by a bot can set one wait but not stop one: it ends on its own, or the person stops it.",
serverHost: "File and program waits look at the computer MausBot runs on, and here that is a server, not the computer you work on. Use url_contains, url_missing or bot_idle.",
guest: "File and program waits are only for the owner of this computer. Use url_contains, url_missing or bot_idle.",
guestFollowUp: "Guests can be told when something happens, but can't set a follow-up. Make the wait without follow_up.",
@@ -123,13 +124,24 @@ export function parseWaitRequest(body: unknown, home: string): { ok: true; reque
export function waitSourceRefusal(turn: {
owned: boolean; room: boolean; depth: number; handedOff: boolean; routineRun: boolean; outsideDriven: boolean; personStarted: boolean; guest: boolean;
+ op?: "create" | "cancel"; assignmentId?: string;
}): string | null {
if (!turn.owned) return WAIT_MESSAGES.notYours;
if (turn.room) return WAIT_MESSAGES.room;
- if (turn.depth > 0 || turn.handedOff || turn.routineRun || turn.outsideDriven || !(turn.personStarted || turn.guest)) return WAIT_MESSAGES.notPerson;
+ if (turn.routineRun || turn.outsideDriven) return WAIT_MESSAGES.notPerson;
+ if (turn.depth > 0 || turn.handedOff) {
+ if (!turn.personStarted || turn.guest || !turn.assignmentId) return WAIT_MESSAGES.notPerson;
+ return turn.op === "create" ? null : WAIT_MESSAGES.handedStop;
+ }
+ if (!(turn.personStarted || turn.guest)) return WAIT_MESSAGES.notPerson;
return null;
}
+export function handedAssignment(id: string | undefined, node: (id: string) => { id: string; parentId?: string; status: string } | undefined): string | undefined {
+ const found = id ? node(id) : undefined;
+ return found?.parentId !== undefined && found.status === "running" ? found.id : undefined;
+}
+
export function hostWaitRefusal(turn: { cloudHome: boolean; hosted: boolean; guest: boolean; place: Surface | null }): string | null {
if (turn.cloudHome || turn.hosted) return WAIT_MESSAGES.serverHost;
if (turn.guest) return WAIT_MESSAGES.guest;
@@ -156,7 +168,8 @@ export interface WaitRouteContext {
botId: string;
threadId: string;
readBody: () => Promise<unknown>;
- sourceRefusal: () => string | null;
+ sourceRefusal: (op: "create" | "cancel", assignmentId: string | undefined) => string | null;
+ assignmentId?: () => string | undefined;
hostRefusal: () => string | null;
/** A Cloud guest's turn: its follow-up would run later as the owner's, so a guest's wait only tells. */
guest: () => boolean;
@@ -172,15 +185,17 @@ export function createWaitRoutes(deps: { waits: Pick<WaitManager, "create" | "li
const { res, json } = ctx;
const here = () => deps.waits.list(ctx.botId).filter((wait) => wait.threadId === ctx.threadId);
if (ctx.method === "GET" && ctx.path === WAITS) {
- if (ctx.sourceRefusal() === WAIT_MESSAGES.notYours) return void json(res, 403, { error: WAIT_MESSAGES.notYours });
+ if (ctx.sourceRefusal("create", undefined) === WAIT_MESSAGES.notYours) return void json(res, 403, { error: WAIT_MESSAGES.notYours });
const mine = here();
return void json(res, 200, { text: mine.length ? waitList(mine) : WAIT_MESSAGES.none });
}
if (ctx.method !== "POST" || (ctx.path !== WAITS && ctx.path !== CANCEL)) return PASS;
- const refusal = ctx.sourceRefusal();
+ const assignmentId = ctx.assignmentId?.();
+ const refusal = ctx.sourceRefusal(ctx.path === CANCEL ? "cancel" : "create", assignmentId);
if (refusal) return void json(res, 403, { error: refusal });
const body = await ctx.readBody();
+ if (assignmentId !== undefined && ctx.assignmentId?.() !== assignmentId) return void json(res, 403, { error: WAIT_MESSAGES.notPerson });
if (ctx.path === CANCEL) {
if (!here().length) return void json(res, 404, { error: WAIT_MESSAGES.noneToCancel });
@@ -224,6 +239,7 @@ export function createWaitRoutes(deps: { waits: Pick<WaitManager, "create" | "li
condition,
...(request.followUp ? { followUp: request.followUp } : {}),
hours: request.hours,
+ ...(assignmentId ? { assignmentId } : {}),
});
if (result.state === "refused") return void json(res, result.status, { error: result.error });
if (result.state === "already") return void json(res, 200, { text: result.text });
diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.ts
index 11ae876164..04db04d4bd 100644
--- a/server/system-prompt.test.ts
+++ b/server/system-prompt.test.ts
@@ -463,6 +463,7 @@ describe("longCommandsPrompt", () => {
expect(text).not.toContain("nohup");
expect(text).toContain("trust only the command's own fresh exit code and output");
expect(text).toContain("cannot set a wait, so finish it in this turn");
+ expect(text).toContain("Work a bot handed you for the person's own request may set one wait_until (not a trigger), cannot cancel it");
}
});
diff --git a/server/system-prompt.ts b/server/system-prompt.ts
index d807fda02b..d530ac888a 100644
--- a/server/system-prompt.ts
+++ b/server/system-prompt.ts
@@ -252,7 +252,7 @@ export const CREDENTIAL_PROMPT =
/** Ten minutes stays inside the 20-minute turn stall watchdog, which sees nothing while a command runs. */
export const BASH_MAX_TIMEOUT_MS = 600_000;
const LONG_COMMANDS_TEXT =
- ` Long-running shell commands: a shell call is stopped after a default limit (2 minutes for a Bash call) and the output of a stopped command is lost. Before running anything that can take more than a minute, such as transcription (whisper), ffmpeg or ffprobe over long media, renders, large builds or big file transfers, pass a longer per-call timeout (Bash takes \`timeout\` in milliseconds, up to ${BASH_MAX_TIMEOUT_MS}) and keep the command in the foreground until it exits; split work that cannot finish within that into shorter pieces. A detached job may be killed when the call ends, so keep work whose result you need in the foreground, and trust only the command's own fresh exit code and output, not a launch exit 0 or an old output file. Never scan the whole disk with \`find /\` or similar: search by name with \`mdfind -name\` on macOS, or search a specific folder such as your workspace or home with a depth limit. If a command times out, do not rerun it the same way. Never wait inside a command for CI, a deploy or any other job to finish (no sleep loops or repeated polls): check it once, and if it is still running, tell the person what you made (with links). Only on a turn the person started in their own chat, set wait_until or a one-time trigger to check back and end your turn; work handed to you by a bot, a routine or an outside event cannot set a wait, so finish it in this turn. When the person writes while you work, answer them first.`;
+ ` Long-running shell commands: a shell call is stopped after a default limit (2 minutes for a Bash call) and the output of a stopped command is lost. Before running anything that can take more than a minute, such as transcription (whisper), ffmpeg or ffprobe over long media, renders, large builds or big file transfers, pass a longer per-call timeout (Bash takes \`timeout\` in milliseconds, up to ${BASH_MAX_TIMEOUT_MS}) and keep the command in the foreground until it exits; split work that cannot finish within that into shorter pieces. A detached job may be killed when the call ends, so keep work whose result you need in the foreground, and trust only the command's own fresh exit code and output, not a launch exit 0 or an old output file. Never scan the whole disk with \`find /\` or similar: search by name with \`mdfind -name\` on macOS, or search a specific folder such as your workspace or home with a depth limit. If a command times out, do not rerun it the same way. Never wait inside a command for CI, a deploy or any other job to finish (no sleep loops or repeated polls): check it once, and if it is still running, tell the person what you made (with links). Only on a turn the person started in their own chat, set wait_until or a one-time trigger to check back and end your turn. Work a bot handed you for the person's own request may set one wait_until (not a trigger), cannot cancel it, and ends its turn; the wait's message lands in that work's chat. A routine or an outside event cannot set a wait, so finish it in this turn. When the person writes while you work, answer them first.`;
const VM_LONG_COMMANDS_TEXT =
" In your Local VM, vm_exec takes `timeout_seconds` instead (default 60, at most 300). The VM keeps running between calls, so a job longer than that may start detached inside it (`nohup <command> > /tmp/<job>.log 2>&1 &`); check its log with later vm_exec calls.";
export function longCommandsPrompt(computer: ComputerPromptKind | null): string {
diff --git a/server/waits.test.ts b/server/waits.test.ts
index 3920f63cde..c9300bedc2 100644
--- a/server/waits.test.ts
+++ b/server/waits.test.ts
@@ -90,6 +90,24 @@ function harness(options: Partial<WaitManagerOptions> = {}) {
}
describe("WaitManager", () => {
+ it("keeps work a bot handed on to one open wait per assignment, across a restart, until it ends", async () => {
+ const h = harness();
+ const handed = (assignmentId: string) => h.manager.create({ botId: "bot-1", threadId: "t-1", label: "the report", condition: { kind: "file_exists", path: "/r.txt" }, assignmentId });
+ const first = await handed("a1");
+ expect(first).toMatchObject({ state: "created", wait: { assignmentId: "a1" } });
+ const id = (first as { wait: WaitRecord }).wait.id;
+ expect(h.waitOf(id).assignmentId).toBe("a1");
+ const again = await handed("a1");
+ expect(again).toMatchObject({ state: "refused", status: 409 });
+ expect((again as { error: string }).error).toMatch(/^Work handed to you keeps one wait at a time, and this work already has one:\n- /);
+ expect(await handed("a2")).toMatchObject({ state: "created" });
+ expect(await h.create({ kind: "file_exists", path: "/r.txt" })).toMatchObject({ state: "created" });
+ h.reload();
+ expect(await handed("a1")).toMatchObject({ state: "refused", status: 409 });
+ expect(h.manager.cancel(id, "bot-1")).toMatchObject({ id });
+ expect(await handed("a1")).toMatchObject({ state: "created" });
+ });
+
it("creates a wait with a 24-hour default and its first check due, and keeps it across a restart", async () => {
const h = harness();
const created = await h.manager.create({ botId: "bot-1", threadId: "t-1", label: "the report", condition: { kind: "file_exists", path: "/r.txt" } });
diff --git a/server/waits.ts b/server/waits.ts
index b090f0e24a..9d2a641a1d 100644
--- a/server/waits.ts
+++ b/server/waits.ts
@@ -21,7 +21,7 @@ import {
type ProcessEntry,
} from "./wait-probes.ts";
-export const WAIT_LIMITS = { perBot: 10, total: 50 } as const;
+export const WAIT_LIMITS = { perBot: 10, total: 50, perAssignment: 1 } as const;
export const WAIT_TICK_MS = 5_000, URL_CHECK_MS = 60_000, URL_BACKOFF_MAX_MS = 15 * 60_000;
/** A sleeping Cloud wakes this often while a wait is open, to check it; checks pause in between. */
export const WAIT_WAKE_MS = 30 * 60_000;
@@ -43,11 +43,12 @@ export type WaitCondition =
export interface WaitNotice { status: "fired" | "expired" | "stopped"; text: string }
export interface WaitRecord {
id: string; botId: string; threadId: string; label: string; condition: WaitCondition; followUp?: string;
+ assignmentId?: string;
createdAt: number; expiresAt: number; nextCheckAt: number; errors: number; cardMessageId?: string;
/** Decided and saved first; posted once its chat is free. */
ending?: WaitNotice;
}
-export interface NewWait { botId: string; threadId: string; label: string; condition: NewWaitCondition; followUp?: string; hours?: number }
+export interface NewWait { botId: string; threadId: string; label: string; condition: NewWaitCondition; followUp?: string; hours?: number; assignmentId?: string }
export type CreateWaitResult =
| { state: "created"; wait: WaitRecord; note?: string }
| { state: "already"; text: string }
@@ -81,6 +82,7 @@ const recordSchema = z.object({
label: z.string(),
condition: conditionSchema,
followUp: z.string().optional(),
+ assignmentId: z.string().optional(),
createdAt: z.number(),
expiresAt: z.number(),
nextCheckAt: z.number(),
@@ -192,6 +194,7 @@ export class WaitManager {
label: input.label,
condition,
...(input.followUp ? { followUp: input.followUp } : {}),
+ ...(input.assignmentId ? { assignmentId: input.assignmentId } : {}),
createdAt: now,
expiresAt: now + (input.hours ?? WAIT_HOURS.default) * 3_600_000,
nextCheckAt: now + interval(condition.kind, 0),
@@ -212,7 +215,11 @@ export class WaitManager {
return { state: "created", wait: cloneWait(wait), ...(note ? { note } : {}) };
}
- private limitRefusal({ botId, threadId }: Pick<NewWait, "botId" | "threadId">): CreateWaitResult | null {
+ private limitRefusal({ botId, threadId, assignmentId }: Pick<NewWait, "botId" | "threadId" | "assignmentId">): CreateWaitResult | null {
+ const handed = assignmentId ? this.waits.filter((w) => w.assignmentId === assignmentId) : [];
+ if (handed.length >= WAIT_LIMITS.perAssignment) {
+ return { state: "refused", status: 409, error: `Work handed to you keeps one wait at a time, and this work already has one:\n${waitList(handed)}\nFinish this turn; it tells you here when it happens.` };
+ }
const mine = this.waits.filter((w) => w.botId === botId && !w.ending);
if (mine.length >= WAIT_LIMITS.perBot) {
const here = mine.filter((w) => w.threadId === threadId), others = mine.length - here.length;