Open-source Grok Bot alternative with a virtual machine that bots can use
Waits Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: A bot can say "tell me when…": three tools (wait_until, list_waits, cancel_wait) hand a condition to a server loop that checks it with plain code, and when it is met the asking chat gets one message, an unread badge, a notification and, if the bot was given then, a follow-up run in that chat.
Architecture: server/wait-probes.ts reads files, the process list and web pages (the page read resolves the host itself, refuses non-public answers and connects to the address it checked). server/waits.ts holds WaitManager on the CalendarCallManager pattern: DATA_DIR/waits.json, a 5 s tick, per-kind intervals, an ending that is saved before it is posted so a restart never posts twice. server/wait-host.ts is the store side (the line, the card, the notification, the follow-up run through routines.enqueueWebhook). server/routes/waits.ts is the internal route behind the tools; server/index.ts gains about 20 lines of wiring and no path guard.
Tech Stack: TypeScript on Node with type stripping (type-only imports must be import type), zod 4, vitest 4, React for one renderer line.
Spec: docs/superpowers/specs/2026-10-27-waits-design.md
Worktree: /Users/omkar/Desktop/openmaus/OpenGrokBot-bot-waits, branch feat/bot-waits. Run every command from there. Never push.
Global Constraints
- No model call between set-up and firing. The tick, the probes and the posting run no AI.
- Everything is named "wait". Never "watch" (
watch.jsonand the Watcher bot exist). - Kinds, exactly:
url_contains,url_missing,file_exists,file_missing,file_changed,process_running,process_gone,bot_idle. - URL checks: http(s) only, at least 60 s apart, doubling on each failure up to 15 min, reset to 60 s on success; 15 s timeout; 2 MB read cap; no cookies; at most 3 redirects, each hop checked again. The host is resolved by the probe, every answer must be a public address, and the request connects to the checked address (pinned
lookup, no second lookup). - File, process and
bot_idlechecks every 5 s (the tick). Paths accept~. hours: integer 1–168, default 24. Limits: 10 active waits per bot, 50 in all.DATA_DIR/waits.json, mode0o600,writeFileAtomic, zod-validated on load, commit with rollback.- Fired line:
<label>: done. <detail>. Expiry line:Stopped waiting for <label> after N hours.(no notification, no follow-up). Follow-up prompt:[Wait finished: <label>] <then>. - Bot and chat come from the internal capability, never from tool arguments. Waits are made and cancelled only in a turn a person started in their own one-to-one chat with the bot (or a Cloud guest's own turn); rooms, routine runs, peer asks, handed-off work and outside events are refused.
- File and process kinds are refused when the server is not the bot's own computer: Cloud home, hosted workspace, Cloud guest, or a turn working in a Local VM, VPS or Boat.
- No new
path === "/…",path.match(,path.startsWith(inserver/index.ts(scripts/testing/index-route-ratchet.test.ts). The route lives inserver/routes/waits.ts. - Comments only for what code cannot say (
AGENTS.md). Doc comments on new wire fields inshared/. - No phone app changes in this repository. Phones get the
notifyframe and the feed as they are; drawing the wait card on phones is a separateSupaMaus/mausbot-mobilechange. - Decided here (the spec left them open): waits do not keep a sleeping Cloud home awake (
nextDueAtunchanged);waits.jsonis left out of workspace backups and Cloud sends; on a Cloud home the follow-up does not join the person's chat but runs and reports like any outside event there (its own "
Review Focus
- The condition is met while the person is mid-turn in that chat: the line must wait for the chat to be free, then appear once. Task 3 ("holds the line…") and Task 4 ("holds the line while a turn runs") pin it.
- The server stops between deciding a wait fired and posting it: after restart, one line and one follow-up, not two. Task 3 ("holds the line…", reload from file) and Task 4 (post skips a line already there) pin it.
- The chat, the bot, or the bot waited for is deleted while waiting: drop silently without recreating the chat; say so when the other bot is gone. Task 3 ("drops a wait silently…", "stops with a line…") pins it.
- A host that resolves to a public and a private address, a redirect to loopback,
localhost,[::1]: all refused. Task 2 pins it. - A relative path, a Windows
.exename, a Linux 15-character process name, a macOS full path inps: Task 1 and Task 5 pin them.
Task 1: File and process probes
Files:
- Create:
server/wait-probes.ts - Test:
server/wait-probes.test.ts
Interfaces:
Produces:
interface FileStamp { size: number; mtimeMs: number }interface ProcessEntry { pid: number; name: string }expandHome(path: string, home: string): stringfileStamp(path: string): Promise<FileStamp | null>(any stat error isnull)fileChanged(before: FileStamp | null, now: FileStamp | null): booleanparsePs(stdout: string): ProcessEntry[],parseTasklist(stdout: string): ProcessEntry[]listProcesses(platform?: NodeJS.Platform, run?: (file: string, args: string[]) => Promise<string>): Promise<ProcessEntry[]>processRunning(entries: readonly ProcessEntry[], wanted: string): booleanpageText(body: string): string,pageSays(text: string, wanted: string): boolean
Step 1: Write the failing tests
describe("file and process probes", () => {
it("expands ~ to the home folder and leaves other paths alone", () => {
expect(expandHome("~", "/h")).toBe("/h");
expect(expandHome("~/a/b.txt", "/h")).toBe(join("/h", "a/b.txt"));
expect(expandHome("/x/y", "/h")).toBe("/x/y");
expect(expandHome("~bob/x", "/h")).toBe("~bob/x");
});
it("stamps a file with its size and modification time, and a missing one as null", async () => {
// writeFileSync(join(dir, "r.txt"), "abc")
expect(await fileStamp(join(dir, "r.txt"))).toEqual({ size: 3, mtimeMs: expect.any(Number) });
expect(await fileStamp(join(dir, "none.txt"))).toBeNull();
});
it("sees a change in size or modification time and a file that appears, never a missing file", () => {
expect(fileChanged({ size: 3, mtimeMs: 1 }, { size: 4, mtimeMs: 1 })).toBe(true);
expect(fileChanged({ size: 3, mtimeMs: 1 }, { size: 3, mtimeMs: 2 })).toBe(true);
expect(fileChanged({ size: 3, mtimeMs: 1 }, { size: 3, mtimeMs: 1 })).toBe(false);
expect(fileChanged(null, { size: 0, mtimeMs: 1 })).toBe(true);
expect(fileChanged({ size: 3, mtimeMs: 1 }, null)).toBe(false);
});
it("reads ps and tasklist output", () => {
expect(parsePs(" 1 /sbin/launchd\n 812 /Applications/Google Chrome.app/Contents/MacOS/Google Chrome\n 9 node\n"))
.toEqual([{ pid: 1, name: "launchd" }, { pid: 812, name: "Google Chrome" }, { pid: 9, name: "node" }]);
expect(parseTasklist('"chrome.exe","1234","Console","1","123,456 K"\r\n"System","4","Services","0","1,000 K"\r\n'))
.toEqual([{ pid: 1234, name: "chrome.exe" }, { pid: 4, name: "System" }]);
});
it("matches a program by name in any case, with or without .exe, by Linux's 15-character name, or by pid", () => {
const entries = [{ pid: 812, name: "Google Chrome" }, { pid: 1234, name: "node.exe" }, { pid: 77, name: "gnome-shell-cal" }];
for (const wanted of ["google chrome", "NODE", "node.exe", "gnome-shell-calendar-server", "812"]) expect(processRunning(entries, wanted), wanted).toBe(true);
for (const wanted of ["google", "813", "gnome-shell"]) expect(processRunning(entries, wanted), wanted).toBe(false);
});
it("runs ps on macOS and Linux and tasklist on Windows, without a shell", async () => {
const calls: unknown[] = [];
const run = async (file: string, args: string[]) => { calls.push([file, args]); return ""; };
await listProcesses("darwin", run); await listProcesses("linux", run); await listProcesses("win32", run);
expect(calls).toEqual([["ps", ["-axo", "pid=,comm="]], ["ps", ["-axo", "pid=,comm="]], ["tasklist", ["/fo", "csv", "/nh"]]]);
});
it("lists this machine's processes, this one included", async () => {
expect((await listProcesses()).some((entry) => entry.pid === process.pid)).toBe(true);
});
it("reads a page as words: tags, scripts and styles out, entities decoded, spaces collapsed", () => {
const text = pageText("<html><head><style>p{}</style><script>var shipped=1</script></head><body><p>Status: <b>Shipped</b> & done</p></body></html>");
expect(text).toBe("Status: Shipped & done");
expect(pageSays(text, "status: SHIPPED")).toBe(true);
expect(pageSays(text, "shipped=1")).toBe(false);
});
});
- Step 2: Run them and see them fail
Run: pnpm exec vitest run server/wait-probes.test.ts
Expected: FAIL, Cannot find module './wait-probes.ts'.
Step 3: Implement
server/wait-probes.tsparsePs: pid is the first token, the name is the rest of the line trimmed, after its last/.parseTasklist: first two quoted CSV fields.processRunning: an all-digitwantedcompares pids; otherwise lower-case both sides and match when the name equalswanted, or equals it with.exeadded or removed, or when the name is exactly 15 characters and equals the first 15 ofwanted.listProcessesdefaultrun:promisify(execFile)(file, args, { timeout: 10_000, maxBuffer: 8 * 1024 * 1024, windowsHide: true })stdout. Never a shell.pageText: drop<script>…</script>,<style>…</style>and<!-- -->, replace remaining tags with a space, decode& < > " ' and numeric entities, collapse whitespace, trim.pageSayscollapses whitespace inwantedand compares lower-cased.Step 4: Run them and see them pass
Run: pnpm exec vitest run server/wait-probes.test.ts
Expected: PASS.
- Step 5: Commit
git add server/wait-probes.ts server/wait-probes.test.ts
git commit -m "feat(waits): file and process probes"
Task 2: The page probe, behind the egress check
Files:
- Modify:
server/wait-probes.ts - Test:
server/wait-probes.test.ts
Interfaces:
Consumes:
resolveTarget(host)fromserver/browser/egress/gate.ts:71;addressClass,ownAddressesfromserver/browser/egress/policy.ts:8.Produces:
type PageResult = { ok: true; text: string } | { ok: false; refused: boolean; error: string }interface PageFetchOptions { allow?: (target: { host: string; address: string }) => boolean; lookup?: (host: string) => Promise<Array<{ address: string; family: number }>>; timeoutMs?: number; maxBytes?: number }fetchPageText(url: string, options?: PageFetchOptions): Promise<PageResult>PAGE_TIMEOUT_MS = 15_000,PAGE_MAX_BYTES = 2 * 1024 * 1024,PAGE_MAX_REDIRECTS = 3
Step 1: Write the failing tests
A local http server on 127.0.0.1 answers / with <p>Build: Shipped</p> (and records the host and cookie request headers), /hop 302 → /, /away 302 → http://127.0.0.1:PORT/, /loop 302 → /loop, /big 3 MB of a then needle, /slow never, /404 404. test = { lookup: async (host) => host === "status.test" ? [{ address: "127.0.0.1", family: 4 }] : [], allow: ({ host }) => host === "status.test" }.
describe("fetchPageText", () => {
it("reads a page through the address it checked, under its own name, with no cookie", async () => {
expect(await fetchPageText(`http://status.test:${port}/`, test)).toEqual({ ok: true, text: "Build: Shipped" });
expect(seen.at(-1)).toEqual({ host: `status.test:${port}`, cookie: undefined });
});
it("follows a redirect only to an address it may reach, and at most three", async () => {
expect(await fetchPageText(`http://status.test:${port}/hop`, test)).toEqual({ ok: true, text: "Build: Shipped" });
expect(await fetchPageText(`http://status.test:${port}/away`, test)).toMatchObject({ ok: false, refused: true });
expect(await fetchPageText(`http://status.test:${port}/loop`, test)).toEqual({ ok: false, refused: false, error: "The page redirected too many times." });
});
it("refuses loopback, private and mixed answers with the real egress check", async () => {
const mixed = { lookup: async () => [{ address: "93.184.216.34", family: 4 }, { address: "10.0.0.5", family: 4 }] };
expect(await fetchPageText("http://mixed.test/", mixed)).toMatchObject({ ok: false, refused: true });
for (const url of [`http://127.0.0.1:${port}/`, `http://localhost:${port}/`, `http://[::1]:${port}/`]) {
expect(await fetchPageText(url), url).toMatchObject({ ok: false, refused: true });
}
});
it("takes only http and https, with no sign-in in the address", async () => {
for (const url of ["file:///etc/passwd", "ftp://example.com/", "https://user:[email protected]/"]) {
expect(await fetchPageText(url), url).toMatchObject({ ok: false, refused: true });
}
});
it("reads at most 2 MB, and gives up after its timeout", async () => {
const big = await fetchPageText(`http://status.test:${port}/big`, test);
expect(big.ok && big.text.includes("needle")).toBe(false);
expect(await fetchPageText(`http://status.test:${port}/slow`, { ...test, timeoutMs: 200 })).toEqual({ ok: false, refused: false, error: "The page took too long to answer." });
});
it("counts an answer that is not 2xx as a failed check", async () => {
expect(await fetchPageText(`http://status.test:${port}/404`, test)).toEqual({ ok: false, refused: false, error: "The page answered 404." });
});
});
- Step 2: Run them and see them fail
Run: pnpm exec vitest run server/wait-probes.test.ts -t fetchPageText
Expected: FAIL, fetchPageText is not exported.
- Step 3: Implement
fetchPageText
Defaults: lookup = resolveTarget, allow = ({ address }) => addressClass(address, ownAddresses()) === "public". One AbortSignal.timeout(timeoutMs) covers every hop. Each hop:
- Parse; protocol not
http:/https:or a username/password present →{ ok: false, refused: true, error: "Only an http or https address with no sign-in details can be checked." }. host = url.hostnamewithout[ ];addresses = await lookup(host); none →{ ok: false, refused: false, error: "That address could not be found." }.- Any address failing
allow→{ ok: false, refused: true, error: \${host} points at this computer or a private network, which waits never check.` }`. http(s).request(url, { agent: false, signal, lookup: <always answers addresses[0]>, headers: { "user-agent": "OpenMausBot-wait", accept: "text/html,text/plain;q=0.9,*/*;q=0.1" } }), the pinned-lookup shape ofserver/custom-domain.ts:99-102.- 3xx with
location: next hop fromnew URL(location, url); a fourth redirect → the "redirected too many times" error. Other non-2xx →The page answered <status>. - 2xx: collect chunks until
maxBytes, then destroy the response and use what was read;pageText(utf8). An abort →The page took too long to answer.; any other socket error →{ ok: false, refused: false, error: "The page could not be reached." }.
- Step 4: Run them and see them pass
Run: pnpm exec vitest run server/wait-probes.test.ts
Expected: PASS.
- Step 5: Commit
git add server/wait-probes.ts server/wait-probes.test.ts
git commit -m "feat(waits): page probe that only reaches public addresses"
Task 3: WaitManager
Files:
- Create:
server/waits.ts - Test:
server/waits.test.ts
Interfaces:
- Consumes: Task 1 and 2 exports;
writeFileAtomic(server/atomic.ts);DATA_DIR(server/config.ts). - Produces (all exported from
server/waits.ts):
export const WAIT_KINDS = ["url_contains", "url_missing", "file_exists", "file_missing", "file_changed", "process_running", "process_gone", "bot_idle"] as const;
export type WaitKind = (typeof WAIT_KINDS)[number];
export const WAIT_LIMITS = { perBot: 10, total: 50 } as const;
export const WAIT_HOURS = { default: 24, max: 168 } as const;
export const WAIT_TICK_MS = 5_000, URL_CHECK_MS = 60_000, URL_BACKOFF_MAX_MS = 15 * 60_000;
export type NewWaitCondition =
| { kind: "url_contains" | "url_missing"; url: string; text: string }
| { kind: "file_exists" | "file_missing" | "file_changed"; path: string }
| { kind: "process_running" | "process_gone"; process: string }
| { kind: "bot_idle"; botId: string; botName: string };
export type WaitCondition =
| { kind: "url_contains" | "url_missing"; url: string; text: string }
| { kind: "file_exists" | "file_missing"; path: string }
| { kind: "file_changed"; path: string; before: FileStamp | null }
| { kind: "process_running" | "process_gone"; process: string }
| { kind: "bot_idle"; botId: string; botName: string; sawBusy: boolean };
export interface WaitNotice { status: "fired" | "expired" | "stopped"; text: string }
export interface WaitRecord {
id: string; botId: string; threadId: string; label: string; condition: WaitCondition; then?: 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; then?: string; hours?: number }
export type CreateWaitResult =
| { state: "created"; wait: WaitRecord; note?: string }
| { state: "already"; text: string }
| { state: "refused"; status: 400 | 409; error: string };
export interface WaitProbes { page(url: string): Promise<PageResult>; stamp(path: string): Promise<FileStamp | null>; processes(): Promise<ProcessEntry[]> }
export interface WaitManagerOptions {
file?: string; now?: () => number; probes?: Partial<WaitProbes>;
sourceAlive(botId: string, threadId: string): boolean;
/** Undefined once that bot no longer exists. */
botBusy(botId: string): boolean | undefined;
/** False while a turn runs in the chat: try again next tick. */
post(wait: WaitRecord, notice: WaitNotice): boolean;
followUp(wait: WaitRecord & { then: string }): void;
showCard(wait: WaitRecord & { then: string }): string | undefined;
settleCard(wait: WaitRecord, how: "fired" | "expired" | "cancelled"): void;
}
export function describeCondition(condition: NewWaitCondition | WaitCondition): string;
export function waitList(waits: readonly WaitRecord[]): string;
export class WaitManager {
constructor(options: WaitManagerOptions);
create(input: NewWait): Promise<CreateWaitResult>;
/** Active waits only: none with an ending. */
list(botId: string): WaitRecord[];
cancel(id: string, botId: string): WaitRecord | null;
/** Every bot that has a stored wait, once each. */
owners(): string[];
removeForBot(botId: string): number;
noteBotBusy(botId: string): void;
start(): void; stop(): void; tick(): Promise<void>; get isTicking(): boolean;
}
Copy (exact):
describeCondition:<url> says “<text>”,<url> no longer says “<text>”,<path> exists,<path> is gone,<path> changes,<process> is running,<process> has stopped,<botName> finishes its work.Already true:
`${describeCondition(c)} already. Nothing was set up: tell the person now.`Fired detail after
<label>: done.:<url> now says “<text>”.,<url> no longer says “<text>”.,<path> is there now.,<path> is gone.,<path> changed.,<process> is running.,<process> stopped.,<botName> finished.Expired:
`Stopped waiting for ${label} after ${n} hour${n === 1 ? "" : "s"}.`withn = Math.round((expiresAt - createdAt) / 3_600_000).Stopped (the other bot is gone):
`Stopped waiting for ${label}: ${botName} no longer exists.`waitListline:`- ${id} · ${label} · until ${describeCondition(c)} · made ${iso(createdAt)} · stops ${iso(expiresAt)}${then ? ` · then: ${then}` : ""}`(iso=new Date(ms).toISOString()).Per-bot limit:
`You already keep ${WAIT_LIMITS.perBot} waits, the most one bot may:\n${waitList(mine)}\nCancel one with cancel_wait first.`; total:This computer already keeps 50 waits, the most it holds. Ask the person which ones to stop.Unreachable page at creation,
note:`The page could not be read just now (${error}); checks go on every minute and slow down while it keeps failing.`Step 1: Write the failing tests
Harness harness(options?: Partial<WaitManagerOptions>) returns h with: manager, file (in a mkdtemp), reload() (a new manager on the same file and stubs), a clock now() starting at T0 with advance(ms) / advanceTo(ms); probe stubs h.stamp (default null), h.page, h.processes (default []) with counters stampCalls, pageCalls, processCalls; h.busy (a Map behind botBusy), h.alive (default true, behind sourceAlive); post, followUp, showCard (returns "card-1"), settleCard as vi.fn; post returns h.postOk (default true) and h.posts holds the notices of the posts that returned true; h.create(condition, { label?, then?, botId?, hours? }) with defaults bot-1, t-1, "the report is ready"; h.waitOf(id) reads the stored record.
describe("WaitManager", () => {
it("creates a wait with a 24-hour default and its first check due, and keeps it across a restart", async () => {
const created = await h.manager.create({ botId: "bot-1", threadId: "t-1", label: "the report is ready", condition: { kind: "file_exists", path: "/r.txt" } });
expect(created).toMatchObject({ state: "created", wait: { expiresAt: T0 + 24 * 3_600_000, nextCheckAt: T0 + 5_000, errors: 0 } });
expect(h.reload().list("bot-1")).toHaveLength(1);
if (process.platform !== "win32") expect(statSync(h.file).mode & 0o777).toBe(0o600);
});
it("creates nothing when the condition is already true", async () => {
h.stamp = { size: 1, mtimeMs: 1 };
expect(await h.create({ kind: "file_exists", path: "/r.txt" })).toEqual({ state: "already", text: "/r.txt exists already. Nothing was set up: tell the person now." });
h.processes = [{ pid: 9, name: "make" }];
expect(await h.create({ kind: "process_running", process: "make" })).toMatchObject({ state: "already" });
h.page = { ok: true, text: "Shipped" };
expect(await h.create({ kind: "url_contains", url: "https://x.test/", text: "shipped" })).toMatchObject({ state: "already" });
expect(h.manager.list("bot-1")).toEqual([]);
});
it("keeps ten waits per bot and fifty in all, and names the bot's waits when full", async () => {
for (let i = 0; i < 10; i++) await h.create({ kind: "file_exists", path: `/f${i}` }, { label: `file ${i}` });
const full = await h.create({ kind: "file_exists", path: "/f10" });
expect(full).toMatchObject({ state: "refused", status: 409, error: expect.stringContaining("cancel_wait") });
expect((full as { error: string }).error).toContain("file 9");
for (let i = 0; i < 40; i++) await h.create({ kind: "file_exists", path: `/g${i}` }, { botId: `bot-${2 + (i % 8)}` });
expect(await h.create({ kind: "file_exists", path: "/h" }, { botId: "bot-99" })).toMatchObject({ state: "refused", status: 409 });
});
it("refuses a page at a private address, and keeps checking a page that only failed to load", async () => {
h.page = { ok: false, refused: true, error: "x.test points at this computer or a private network, which waits never check." };
expect(await h.create({ kind: "url_contains", url: "http://x.test/", text: "ok" })).toEqual({ state: "refused", status: 400, error: h.page.error });
h.page = { ok: false, refused: false, error: "The page took too long to answer." };
expect(await h.create({ kind: "url_contains", url: "http://x.test/", text: "ok" })).toMatchObject({ state: "created", note: expect.stringContaining("took too long") });
});
it("shows the card only for a wait with a follow-up, and stores its message id", async () => {
h.showCard.mockReturnValue("m-1");
const withThen = await h.create({ kind: "file_exists", path: "/r" }, { then: "Summarise it." });
expect(withThen).toMatchObject({ wait: { cardMessageId: "m-1" } });
await h.create({ kind: "file_exists", path: "/s" });
expect(h.showCard).toHaveBeenCalledTimes(1);
});
it("fires once: one line, one follow-up, the card settled, and the wait gone", async () => {
await h.create({ kind: "file_exists", path: "/r.txt" }, { label: "the report is ready", then: "Summarise it." });
h.stamp = { size: 1, mtimeMs: 1 }; h.advance(5_000); await h.manager.tick(); await h.manager.tick();
expect(h.posts).toEqual([{ status: "fired", text: "the report is ready: done. /r.txt is there now." }]);
expect(h.followUp).toHaveBeenCalledTimes(1);
expect(h.settleCard.mock.calls.map(([, how]) => how)).toEqual(["fired"]);
expect(h.manager.list("bot-1")).toEqual([]);
});
it("holds the line while a turn runs in the chat, then posts it once, even across a restart", async () => {
await h.create({ kind: "file_exists", path: "/r.txt" }, { then: "Go." });
h.stamp = { size: 1, mtimeMs: 1 }; h.postOk = false; h.advance(5_000); await h.manager.tick();
const reloaded = h.reload(); h.postOk = true; await reloaded.tick();
expect(h.post).toHaveBeenCalledTimes(2);
expect(h.followUp).toHaveBeenCalledTimes(1);
await reloaded.tick(); expect(h.post).toHaveBeenCalledTimes(2);
});
it("expires after its hours with one last check, quietly and without a follow-up", async () => {
await h.create({ kind: "file_exists", path: "/r" }, { label: "the build", then: "Deploy." });
h.advance(24 * 3_600_000); await h.manager.tick();
expect(h.posts).toEqual([{ status: "expired", text: "Stopped waiting for the build after 24 hours." }]);
expect(h.followUp).not.toHaveBeenCalled();
expect(h.settleCard.mock.calls.map(([, how]) => how)).toEqual(["expired"]);
});
it("fires instead of expiring when the last check finds it", async () => {
await h.create({ kind: "file_exists", path: "/r" }, { label: "the build" });
h.stamp = { size: 1, mtimeMs: 1 }; h.advance(30 * 3_600_000); await h.manager.tick();
expect(h.posts[0]).toMatchObject({ status: "fired" });
});
it("checks a page every minute and backs off to 15 minutes while it fails", async () => {
h.page = { ok: true, text: "building" };
const { wait } = await h.create({ kind: "url_contains", url: "https://x.test/", text: "shipped" }) as { wait: WaitRecord };
expect(wait.nextCheckAt - T0).toBe(60_000);
h.page = { ok: false, refused: false, error: "down" };
const gaps: number[] = [];
for (let i = 0; i < 6; i++) { h.advanceTo(h.waitOf(wait.id).nextCheckAt); await h.manager.tick(); gaps.push(h.waitOf(wait.id).nextCheckAt - h.now()); }
expect(gaps).toEqual([120_000, 240_000, 480_000, 900_000, 900_000, 900_000]);
h.page = { ok: true, text: "building" }; h.advanceTo(h.waitOf(wait.id).nextCheckAt); await h.manager.tick();
expect(h.waitOf(wait.id).nextCheckAt - h.now()).toBe(60_000);
h.advance(5_000); await h.manager.tick(); expect(h.pageCalls).toBe(8);
});
it("waits for another bot to start and then finish, even a turn shorter than a tick", async () => {
h.busy.set("coder", false);
await h.create({ kind: "bot_idle", botId: "coder", botName: "Coder" }, { label: "Coder's review" });
h.advance(5_000); await h.manager.tick(); expect(h.posts).toEqual([]);
h.manager.noteBotBusy("coder");
h.advance(5_000); await h.manager.tick();
expect(h.posts).toEqual([{ status: "fired", text: "Coder's review: done. Coder finished." }]);
});
it("stops with a line when the bot it waits for is deleted", async () => {
h.busy.set("coder", false);
await h.create({ kind: "bot_idle", botId: "coder", botName: "Coder" }, { label: "Coder's review" });
h.busy.delete("coder"); h.advance(5_000); await h.manager.tick();
expect(h.posts).toEqual([{ status: "stopped", text: "Stopped waiting for Coder's review: Coder no longer exists." }]);
});
it("drops a wait silently when its chat or bot is gone, without posting or touching the card", async () => {
await h.create({ kind: "file_exists", path: "/r" }, { then: "Go." });
h.alive = false; h.stamp = { size: 1, mtimeMs: 1 }; h.advance(5_000); await h.manager.tick();
expect([h.post.mock.calls.length, h.settleCard.mock.calls.length, h.manager.list("bot-1").length]).toEqual([0, 0, 0]);
});
it("reads a file's change against the stamp taken when the wait was made", async () => {
h.stamp = { size: 1, mtimeMs: 1 };
await h.create({ kind: "file_changed", path: "/log" });
h.advance(5_000); await h.manager.tick(); expect(h.posts).toEqual([]);
h.stamp = { size: 2, mtimeMs: 2 }; h.advance(5_000); await h.manager.tick();
expect(h.posts[0]).toMatchObject({ status: "fired" });
});
it("reads the process list once per tick for every process wait", async () => {
h.processes = [{ pid: 1, name: "a" }, { pid: 2, name: "b" }, { pid: 3, name: "c" }];
for (const name of ["a", "b", "c"]) await h.create({ kind: "process_gone", process: name }, { label: name });
h.processCalls = 0; h.advance(5_000); await h.manager.tick();
expect(h.processCalls).toBe(1);
expect(h.posts).toEqual([]);
});
it("lets a bot cancel only its own waits, and settles the card", async () => {
const { wait } = await h.create({ kind: "file_exists", path: "/r" }, { then: "Go." }) as { wait: WaitRecord };
expect(h.manager.cancel(wait.id, "bot-2")).toBeNull();
expect(h.manager.cancel(wait.id, "bot-1")?.id).toBe(wait.id);
expect(h.settleCard.mock.calls.map(([, how]) => how)).toEqual(["cancelled"]);
});
it("removes a deleted bot's waits and nobody else's", async () => {
await h.create({ kind: "file_exists", path: "/a" }); await h.create({ kind: "file_exists", path: "/b" });
await h.create({ kind: "file_exists", path: "/c" }, { botId: "bot-2" });
expect(h.manager.owners()).toEqual(["bot-1", "bot-2"]);
expect(h.manager.removeForBot("bot-1")).toBe(2);
expect([h.manager.list("bot-1").length, h.manager.list("bot-2").length, h.posts.length]).toEqual([0, 1, 0]);
});
it("checks every five seconds once started, and not at all once stopped", async () => {
vi.useFakeTimers();
const h = harness({ now: () => Date.now() });
await h.create({ kind: "file_exists", path: "/r" });
h.manager.start(); await vi.advanceTimersByTimeAsync(5_000); const seen = h.stampCalls;
h.manager.stop(); await vi.advanceTimersByTimeAsync(20_000);
expect(h.stampCalls).toBe(seen); expect(h.manager.isTicking).toBe(false);
});
});
- Step 2: Run them and see them fail
Run: pnpm exec vitest run server/waits.test.ts
Expected: FAIL, Cannot find module './waits.ts'.
- Step 3: Implement
server/waits.ts
Persistence exactly as server/calendar-calls.ts:183-386: file ?? join(DATA_DIR, "waits.json"), { version: 1, waits } validated by a zod schema per record (invalid records dropped), commit() with rollback for create/cancel/removeForBot/noteBotBusy, save() with writeFileAtomic(…, { mode: 0o600 }), start() runs tick() then a WAIT_TICK_MS interval with unref().
create: limits first (per bot counts waits of botId without ending; total counts all), then one probe through the same check as the tick: met → already; a refused page → refused 400; a failed page → created with note. file_changed stores before from stamp(path); bot_idle stores sawBusy: false. nextCheckAt = now + interval(kind, 0); expiresAt = now + (hours ?? 24) * 3_600_000. After the commit, a wait with then gets cardMessageId = showCard(wait) in a second commit.
noteBotBusy(botId) sets sawBusy on active bot_idle waits for that bot that do not have it yet, and saves only if one changed.
tick() (guarded by ticking; the process list is read at most once, lazily, per tick):
- For each wait:
!sourceAlive(botId, threadId)→ remove it; no post, nosettleCard. - A wait with
endingskips to step 5. - Due when
now >= nextCheckAtornow >= expiresAt(an expired wait gets one last check). Probe every due wait concurrently.bot_idle:botBusyundefined → gone; true →sawBusy = true, not met; false → met whensawBusy. - Met →
ending= fired notice; gone → stopped notice; otherwise pastexpiresAt→ expired notice; otherwise a failed page →errors += 1, elseerrors = 0;nextCheckAt = now + interval(kind, errors)whereintervalismin(URL_CHECK_MS * 2 ** errors, URL_BACKOFF_MAX_MS)forurl_*andWAIT_TICK_MSfor the rest. Save before step 5 when anyendingwas set. - With an
ending:post(wait, ending); false → keep it for the next tick. True →followUpwhen fired withthen(an exception is logged, the wait still ends),settleCard(wait, status === "fired" ? "fired" : "expired")when it has a card, remove it, save.
- Step 4: Run them and see them pass
Run: pnpm exec vitest run server/waits.test.ts
Expected: PASS.
- Step 5: Commit
git add server/waits.ts server/waits.test.ts
git commit -m "feat(waits): WaitManager with a 5 s tick, limits and expiry"
Task 4: Wire shapes, the notification, the follow-up run and the store side
Files:
- Modify:
shared/notification.ts:3-28(add| "wait"with a doc comment) - Modify:
server/notify.ts:26-64(title) - Modify:
src/components/NotificationsPanel.tsx:13-26(KIND_LOOK.wait) - Modify:
shared/wire.ts:516(message field),shared/wire.ts:640-698(card field andWaitCardData) - Modify:
shared/routine-run.ts:33,shared/routines.ts:173,server/routines.ts:113-115and:768-792 - Create:
server/wait-host.ts - Test:
server/notify.test.ts,server/routines.test.ts,server/wait-host.test.ts
Interfaces:
- Consumes:
WaitManagerOptions,WaitRecord,WaitNotice(Task 3). - Produces:
NotifyKindgains"wait";buildNotification("wait", …)title`${who}'s wait is over`.WireMessage.wait?: { id: string; status: "fired" | "expired" | "stopped" }— doc: "The line a wait (wait_until) posted when it ended."OptionCardData.waitRequest?: WaitCardData;export interface WaitCardData { waitId: string; label: string; then: string; settled?: "fired" | "expired" | "cancelled" }— doc: "A wait with a follow-up a bot set up from chat; Cancel stops it until it settles."AutomationLine.triggerandRoutineRun.eventSource(shared and server) gain"wait".RoutineManager.enqueueWebhookinput gainseventSource?: "app" | "wait"andresultsThreadId?: string(used instead ofeventResultsThreadwhen given).server/wait-host.ts:
export interface WaitHostDeps {
store: Pick<Store, "appendMessage" | "patchMessage" | "patchTask" | "messagesFor" | "bot">;
/** A one-to-one chat this bot owns; a room is not one. */
directChat(botId: string, threadId: string): boolean;
threadBusy(botId: string, threadId: string): boolean;
wrote(bot: BotRecord, threadId: string): void;
notify(notification: Notification | null): void;
enqueue(input: Parameters<RoutineManager["enqueueWebhook"]>[0]): { id: string };
cloudHome: boolean;
now?: () => number;
}
export function createWaitHost(deps: WaitHostDeps): Pick<WaitManagerOptions, "sourceAlive" | "botBusy" | "post" | "followUp" | "showCard" | "settleCard">;
/** The chat a wait's follow-up run works in: the one it was asked in, never on a Cloud home or in a room. */
export function waitRunChat(run: Pick<RoutineRun, "botId" | "resultsThreadId">, directChat: (botId: string, threadId: string) => boolean, cloudHome: boolean): string | null;
- Step 1: Write the failing tests
server/notify.test.ts:
it("titles a finished wait and keeps its line as the body", () => {
expect(buildNotification("wait", { id: "b", name: "Pepper" }, "t", "the build: done. ci passed.")).toEqual({
kind: "wait", botId: "b", botName: "Pepper", threadId: "t", title: "Pepper's wait is over", body: "the build: done. ci passed.",
});
});
server/routines.test.ts, beside "sends an outside event's run to report where the bot's chat is" (:3907):
it("runs a wait's follow-up in the chat it was asked in, reporting nowhere else", async () => {
const h = harness();
h.options.eventResultsThread = () => "main";
h.options.joinConversation = (run) => run.eventSource === "wait" ? run.resultsThreadId ?? null : null;
const queued = h.manager.enqueueWebhook({ webhookId: "wait:w1", webhookName: "the build", prompt: "[Wait finished: the build] Deploy.", botId: "maus-1",
runOn: "maus", deliveryId: "w1", receivedAt: Date.now(), eventSource: "wait", resultsThreadId: "chat-1" });
await h.manager.tick();
expect(h.manager.listRuns().find((run) => run.id === queued.id)).toMatchObject({ eventSource: "wait", resultsThreadId: "chat-1", threadId: "chat-1", status: "running" });
expect(h.taskTitles).toHaveLength(0);
});
server/wait-host.test.ts (a small in-memory store fake with appendMessage returning { id: "m-<n>", …message }):
describe("the store side of waits", () => {
it("posts a wait's line once, marks the chat unread and notifies only when it fired", () => {
expect(host.post(wait, { status: "fired", text: "the build: done. ci passed." })).toBe(true);
expect(host.post(wait, { status: "fired", text: "the build: done. ci passed." })).toBe(true);
expect(store.lines).toEqual([{ role: "bot", kind: "text", text: "the build: done. ci passed.", wait: { id: "w1", status: "fired" } }]);
expect(store.patchTask).toHaveBeenCalledWith("bot-1", "t-1", { unread: true });
expect(wrote).toHaveBeenCalledTimes(1);
host.post({ ...wait, id: "w2" }, { status: "expired", text: "Stopped waiting for the build after 24 hours." });
expect(notify.mock.calls.map(([n]) => n?.kind)).toEqual(["wait"]);
});
it("holds the line while a turn runs in the chat", () => {
busy = true;
expect(host.post(wait, { status: "fired", text: "x" })).toBe(false);
expect(store.lines).toEqual([]);
});
it("shows a card with the follow-up, and settles it", () => {
const id = host.showCard({ ...wait, then: "Deploy it." });
expect(store.message(id!)).toMatchObject({ role: "bot", kind: "options", card: {
title: "Waiting: the build", subtitle: "When the build, Pepper will: Deploy it.", options: [], answered: "allow", dismissed: true,
autoApplied: true, requestId: "w1", tool: "wait_until", waitRequest: { waitId: "w1", label: "the build", then: "Deploy it." } } });
host.settleCard({ ...wait, cardMessageId: id }, "cancelled");
expect(store.message(id!).card).toMatchObject({ undone: true, waitRequest: { settled: "cancelled" } });
});
it("queues the follow-up as an outside event that joins the chat, except on a Cloud home", () => {
host.followUp({ ...wait, then: "Deploy it." });
expect(enqueue).toHaveBeenLastCalledWith({ webhookId: "wait:w1", webhookName: "the build", prompt: "[Wait finished: the build] Deploy it.",
botId: "bot-1", runOn: "maus", deliveryId: "w1", receivedAt: NOW, eventSource: "wait", resultsThreadId: "t-1" });
cloudHost.followUp({ ...wait, then: "Deploy it." });
expect(enqueue.mock.lastCall![0]).not.toHaveProperty("resultsThreadId");
expect(waitRunChat({ botId: "bot-1", resultsThreadId: "t-1" }, () => true, false)).toBe("t-1");
expect(waitRunChat({ botId: "bot-1", resultsThreadId: "t-1" }, () => true, true)).toBeNull();
expect(waitRunChat({ botId: "bot-1", resultsThreadId: "room" }, () => false, false)).toBeNull();
});
it("knows a deleted bot from an idle one", () => {
expect([host.botBusy("bot-1"), host.botBusy("gone")]).toEqual([false, undefined]);
});
});
- Step 2: Run them and see them fail
Run: pnpm exec vitest run server/notify.test.ts server/routines.test.ts server/wait-host.test.ts
Expected: FAIL: the title falls through to "finished", resultsThreadId is the event's main, wait-host.ts is missing.
Step 3: Implement
Types as listed in Interfaces;
KIND_LOOK.wait = { Icon: CheckCircle2, className: "text-success", status: "notifications.status.done" }(no new locale key).enqueueWebhook:resultsThreadId: input.resultsThreadId ?? this.options.eventResultsThread?.(input).createWaitHost:sourceAlive= bot exists anddirectChat;botBusy=store.bot(id)?.busy === true,undefinedfor a missing bot.post: missing bot →true(drop);threadBusy→false; a line inmessagesFor(threadId)with the samewait.idandstatus→true; else append,patchTask(…, { unread: true }),wrote(bot, threadId), and forfirednotify(buildNotification("wait", bot, threadId, text, { avatarUrl: bot.avatarUrl })).settleCard: patch the card message only when it still carrieswaitRequest;cancelledalso setsundone: true.Step 4: Run them and see them pass, then typecheck
Run: pnpm exec vitest run server/notify.test.ts server/routines.test.ts server/wait-host.test.ts src/components/NotificationsPanel.test.ts && pnpm typecheck
Expected: PASS, typecheck clean.
- Step 5: Commit
git add shared/notification.ts server/notify.ts server/notify.test.ts src/components/NotificationsPanel.tsx shared/wire.ts shared/routine-run.ts shared/routines.ts server/routines.ts server/routines.test.ts server/wait-host.ts server/wait-host.test.ts
git commit -m "feat(waits): wire shapes, wait notification and follow-up run plumbing"
Task 5: The internal route
Files:
- Create:
server/routes/waits.ts - Test:
server/routes/waits.test.ts - Modify:
server/read-and-draft.test.ts:83(pin the default-deny for waits;server/read-and-draft.tsitself does not change)
Interfaces:
- Consumes:
WaitManager(create,list,cancel),WAIT_KINDS,WAIT_HOURS,waitList(Task 3);expandHome(Task 1);PASS(server/routes/table.ts);type json(server/harness/http.ts);type Surface(shared/wire.ts:57). - Produces:
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.",
serverHost: "File and program waits look at the computer OpenMausBot 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.",
otherComputer: "You work on another computer this turn (a Local VM or a cloud computer), and file and program waits look at the one OpenMausBot runs on. Use url_contains, url_missing or bot_idle.",
noPeer: "No bot you can reach goes by that name. Use a name or id from list_bots.",
self: "You cannot wait for yourself to finish.",
noWait: "None of your waits has that id. Use list_waits.",
none: "You are not waiting for anything.",
} as const;
export interface WaitRequest { label: string; kind: WaitKind; url?: string; text?: string; path?: string; process?: string; bot?: string; then?: string; hours: number }
export function parseWaitRequest(body: unknown, home: string): { ok: true; request: WaitRequest } | { ok: false; error: string };
export function waitSourceRefusal(turn: { owned: boolean; room: boolean; depth: number; handedOff: boolean; routineRun: boolean; outsideDriven: boolean; personStarted: boolean; guest: boolean }): string | null;
export function hostWaitRefusal(turn: { cloudHome: boolean; hosted: boolean; guest: boolean; place: Surface | null }): string | null;
export function findWaitPeer(peers: readonly { id: string; name: string; hidden?: boolean }[], selfId: string, nameOrId: string): { id: string; name: string } | "self" | null;
export interface WaitRouteContext {
method: string; path: string; res: ServerResponse; json: typeof sendJson;
botId: string; threadId: string; readBody: () => Promise<unknown>;
sourceRefusal: () => string | null;
hostRefusal: () => string | null;
peer: (nameOrId: string) => { id: string; name: string } | "self" | null;
}
export function createWaitRoutes(deps: { waits: Pick<WaitManager, "create" | "list" | "cancel">; home?: () => string }): (ctx: WaitRouteContext) => Promise<typeof PASS | void>;
Routes: GET /api/internal/waits → 200 { text } (waitList(list(botId)) or none); POST /api/internal/waits → create; POST /api/internal/waits/cancel { id } → 200 { text: "Stopped waiting for <label>." } or 404 { error: noWait }. Anything else → PASS.
Create order: sourceRefusal → 403; parseWaitRequest → 400; file_*/process_* with hostRefusal → 403; bot_idle: peer(bot) → self 400 / null 400; waits.create({ botId, threadId, … }): created → 201 { text }, already → 200 { text }, refused → its status { error }. Created text:
`Waiting for ${label} (wait id ${id}): plain checks, no AI, until ${iso(expiresAt)}. When it happens a message lands in this chat${then ? ", and you will then do what you wrote in then" : ""}. Tell the person in one sentence; do not keep checking yourself.` plus \n\n${note} when there is one.
Parse rules and errors (exact):
labeltrimmed 1–120 → elselabel: the person's words for what you wait for, up to 120 characters.kind→ else`kind is one of: ${WAIT_KINDS.join(", ")}.`- Fields per kind:
url+textforurl_*,pathforfile_*,processforprocess_*,botforbot_idle. Missing →`${kind} needs ${fields joined with " and "}.`A field of another kind (null counts as absent) →`${field} applies only to ${kinds joined with " and "}.` url≤ 2048,http:/https:→ elseurl must be an http or https address.; username or password →Put no sign-in details in the address.text1–500;process1–256;bot1–128;thentrimmed 1–2000 when present.path≤ 1024,expandHome(path, home)must be absolute (path.isAbsolute) → elsepath must be a full path or start with ~.hoursinteger 1–168, default 24 → elsehours is a whole number from 1 to 168.
Refusal rules: !owned → notYours; room → room; depth > 0 || handedOff || routineRun || outsideDriven || !(personStarted || guest) → notPerson; else null. Host: cloudHome || hosted → serverHost; guest → guest; place === "vm" || place === "cloud" → otherComputer; else null. Peer: skip hidden; match id exactly or name case-insensitively; the match being selfId → "self".
- Step 1: Write the failing tests
Harness: waits = { create: vi.fn(async (input) => ({ state: "created", wait: { id: "w1", label: input.label, expiresAt: 0 } })), list: vi.fn(() => []), cancel: vi.fn() }; call(method, path, body?, overrides?) runs the route with botId: "bot-1", threadId: "thread-1", home HOME, sourceRefusal/hostRefusal returning null and peer returning null unless overridden, and returns { outcome, status, payload } from the json spy. FILE_WAIT = { label: "the report is ready", kind: "file_exists", path: "/r.txt" }.
describe("the waits route", () => {
it("passes requests that are not its own", async () => {
expect((await call("GET", "/api/internal/triggers")).outcome).toBe(PASS);
});
it("makes a wait for the capability's bot and chat, never ids from the body", async () => {
const { status, payload } = await call("POST", "/api/internal/waits", { label: "the report is ready", kind: "file_exists", path: "~/r.txt" });
expect(waits.create).toHaveBeenCalledWith({ botId: "bot-1", threadId: "thread-1", label: "the report is ready", condition: { kind: "file_exists", path: join(HOME, "r.txt") }, hours: 24 });
expect([status, payload.text]).toEqual([201, expect.stringContaining("(wait id w1)")]);
});
it("refuses a turn the person did not start in their own chat, for making and for stopping", async () => {
for (const [path, body] of [["/api/internal/waits", FILE_WAIT], ["/api/internal/waits/cancel", { id: "w1" }]] as const) {
expect(await call("POST", path, body, { sourceRefusal: () => WAIT_MESSAGES.notPerson })).toMatchObject({ status: 403, payload: { error: WAIT_MESSAGES.notPerson } });
}
expect(waits.create).not.toHaveBeenCalled(); expect(waits.cancel).not.toHaveBeenCalled();
});
it("refuses file and program waits away from the bot's own computer, and allows pages and bots there", async () => {
const away = { hostRefusal: () => WAIT_MESSAGES.otherComputer };
expect(await call("POST", "/api/internal/waits", FILE_WAIT, away)).toMatchObject({ status: 403 });
expect(await call("POST", "/api/internal/waits", { label: "l", kind: "process_gone", process: "make" }, away)).toMatchObject({ status: 403 });
expect(await call("POST", "/api/internal/waits", { label: "l", kind: "url_contains", url: "https://x.test/", text: "ok" }, away)).toMatchObject({ status: 201 });
});
it.each([
[{ label: "", kind: "file_exists", path: "/r" }, "label: the person's words for what you wait for, up to 120 characters."],
[{ label: "l", kind: "file_seen", path: "/r" }, `kind is one of: ${WAIT_KINDS.join(", ")}.`],
[{ label: "l", kind: "url_contains", url: "https://x.test/" }, "url_contains needs url and text."],
[{ label: "l", kind: "file_exists", path: "/r", text: "x" }, "text applies only to url_contains and url_missing."],
[{ label: "l", kind: "url_missing", url: "ftp://x.test/", text: "x" }, "url must be an http or https address."],
[{ label: "l", kind: "url_missing", url: "https://u:[email protected]/", text: "x" }, "Put no sign-in details in the address."],
[{ label: "l", kind: "file_exists", path: "build/out.txt" }, "path must be a full path or start with ~."],
[{ label: "l", kind: "file_exists", path: "/r", hours: 169 }, "hours is a whole number from 1 to 168."],
[{ label: "l", kind: "file_exists", path: "/r", hours: 0 }, "hours is a whole number from 1 to 168."],
])("refuses %j", async (body, error) => {
expect(await call("POST", "/api/internal/waits", body)).toMatchObject({ status: 400, payload: { error } });
});
it("finds the other bot by name or id among the bots it may reach, never itself", async () => {
const peers = [{ id: "b2", name: "Coder" }, { id: "b3", name: "Hidden", hidden: true }, { id: "bot-1", name: "Pepper" }];
expect(findWaitPeer(peers, "bot-1", "coder")).toEqual({ id: "b2", name: "Coder" });
expect(findWaitPeer(peers, "bot-1", "b2")).toEqual({ id: "b2", name: "Coder" });
expect([findWaitPeer(peers, "bot-1", "Hidden"), findWaitPeer(peers, "bot-1", "pepper")]).toEqual([null, "self"]);
expect(await call("POST", "/api/internal/waits", { label: "l", kind: "bot_idle", bot: "nobody" }, { peer: () => null })).toMatchObject({ status: 400, payload: { error: WAIT_MESSAGES.noPeer } });
});
it("lets a bot cancel only its own waits and lists only its own", async () => {
waits.cancel.mockReturnValueOnce(null);
expect(await call("POST", "/api/internal/waits/cancel", { id: "w9" })).toMatchObject({ status: 404, payload: { error: WAIT_MESSAGES.noWait } });
waits.cancel.mockReturnValueOnce({ id: "w1", label: "the build" } as WaitRecord);
expect(await call("POST", "/api/internal/waits/cancel", { id: "w1" })).toMatchObject({ status: 200, payload: { text: "Stopped waiting for the build." } });
expect(waits.cancel.mock.calls).toEqual([["w9", "bot-1"], ["w1", "bot-1"]]);
await call("GET", "/api/internal/waits"); expect(waits.list).toHaveBeenCalledWith("bot-1");
});
it("lets only a person's own one-to-one turn make a wait", () => {
const person = { owned: true, room: false, depth: 0, handedOff: false, routineRun: false, outsideDriven: false, personStarted: true, guest: false };
expect(waitSourceRefusal(person)).toBeNull();
expect(waitSourceRefusal({ ...person, personStarted: false, guest: true })).toBeNull();
expect(waitSourceRefusal({ ...person, owned: false })).toBe(WAIT_MESSAGES.notYours);
expect(waitSourceRefusal({ ...person, room: true })).toBe(WAIT_MESSAGES.room);
for (const other of [{ depth: 1 }, { handedOff: true }, { routineRun: true }, { outsideDriven: true }, { personStarted: false }]) {
expect(waitSourceRefusal({ ...person, ...other }), JSON.stringify(other)).toBe(WAIT_MESSAGES.notPerson);
}
});
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();
for (const place of ["vm", "cloud"] as const) expect(hostWaitRefusal({ ...own, place })).toBe(WAIT_MESSAGES.otherComputer);
expect([hostWaitRefusal({ ...own, cloudHome: true }), hostWaitRefusal({ ...own, hosted: true }), hostWaitRefusal({ ...own, guest: true })])
.toEqual([WAIT_MESSAGES.serverHost, WAIT_MESSAGES.serverHost, WAIT_MESSAGES.guest]);
});
});
server/read-and-draft.test.ts:83, add ["POST", "/api/internal/waits"], ["GET", "/api/internal/waits"], ["POST", "/api/internal/waits/cancel"] to the refused list.
- Step 2: Run them and see them fail
Run: pnpm exec vitest run server/routes/waits.test.ts server/read-and-draft.test.ts
Expected: waits.test.ts FAILS (module missing); read-and-draft.test.ts PASSES already (default deny), which is the point of pinning it.
Step 3: Implement
server/routes/waits.tson theserver/routes/helper-tools.tsshape, with the rules above.homedefaults toos.homedir.Step 4: Run them and see them pass
Run: pnpm exec vitest run server/routes/waits.test.ts server/read-and-draft.test.ts
Expected: PASS.
- Step 5: Commit
git add server/routes/waits.ts server/routes/waits.test.ts server/read-and-draft.test.ts
git commit -m "feat(waits): internal route with source, host and ownership checks"
Task 6: The three tools and the prompt sentence
Files:
- Create:
server/drivers/agents-wait-tools.ts,server/drivers/agents-wait-tools.test.ts - Modify:
server/drivers/agents-catalog.ts(import;...WAIT_TOOL_DEFINITIONS,right after themanage_triggerentry,:728) - Modify:
server/drivers/agents-call.ts:187(dispatch after the trigger tools) - Modify:
server/agent-tool-policy.ts:3-16andserver/agent-tool-policy.test.ts("list_waits"after"list_trigger_events";"wait_until","cancel_wait"in the never-read-only list) - Modify:
server/drivers/agents-proxy.test.ts:661("wait_until", "list_waits", "cancel_wait"after"manage_trigger") - Modify:
server/drivers/agents-catalog-wire.test.ts(new test;BUDGET_BASELINE,:70-93) - Regenerate:
server/drivers/agents-catalog-goldens/{full.tools-list,profiles,bridged.tools-list,bridged.profiles}.json - Modify:
server/system-prompt.ts:211(TRIGGER_PROMPT),server/system-prompt.test.ts:296
Interfaces:
- Consumes: the route paths and
{ text } | { error }answers of Task 5. - Produces:
WAIT_TOOL_NAMES: ReadonlySet<string>,callWaitTool(name: string, args: Json, context: ToolCallContext): Promise<ToolCallResult>,WAIT_TOOL_DEFINITIONS(in this order:wait_until,list_waits,cancel_wait).
Definitions (flat, no composition):
wait_until, description:Tell the person when something happens, with no AI running while you wait: plain code checks a web page for some words (every minute), a file or folder (there, gone or changed), a program (running or stopped), or another bot finishing its work. When it happens a message lands in this chat with a notification; with then, you also carry out then here. Use it instead of staying busy or a short-interval routine. If it is already true nothing is set up and the result says so: tell the person at once. Files and programs are those of the computer OpenMausBot runs on, only when you work on it. A wait stops after hours (default 24, at most 168).Properties:label(string, maxLength 120,The person's words for it, e.g. "the build finishes".),kind(enumWAIT_KINDS,url_* = a page says or no longer says text; file_* = path exists, is gone or changes; process_* = a program runs or stops; bot_idle = another bot finishes its work.),url(url_*: the http(s) page.),text(url_*: the words to look for, any case.),path(file_*: a full path; ~ is the home folder.),process(process_*: the program's name, any case, or its process id.),bot(bot_idle: the other bot's name or id from list_bots.),then(string, maxLength 2000,Only when the person asked for something to happen then: that request, written for a run that will not see this conversation.),hours(integer, minimum 1, maximum 168).required: ["label", "kind"].list_waits:Your waits that have not ended (wait_until): id, label, what it checks, when it was made and when it stops.No properties.cancel_wait:Stop one of your waits; its id comes from list_waits or wait_until's answer.idstring minLength 1, required.
Prompt sentence appended to TRIGGER_PROMPT: To tell the person when something a plain check can see happens (a page says something, a file appears or changes, a program starts or stops, another bot finishes), use wait_until instead of staying busy or making a short-interval routine, and give then only when they asked for something to be done at that moment.
- Step 1: Write the failing tests
server/drivers/agents-wait-tools.test.ts (a fake client.apiResponse that records calls):
it("sends wait_until's arguments unchanged to the waits route and returns its words", async () => {
reply = { ok: true, status: 201, body: { text: "Waiting for the build (wait id w1)…" } };
expect(await callWaitTool("wait_until", { label: "the build", kind: "file_exists", path: "/r" }, context)).toEqual({ text: "Waiting for the build (wait id w1)…" });
expect(calls).toEqual([["/api/internal/waits", { method: "POST", body: JSON.stringify({ label: "the build", kind: "file_exists", path: "/r" }) }]]);
});
it("marks a refusal as an error in the route's words", async () => {
reply = { ok: false, status: 403, body: { error: "Only the person can set up or stop a wait…" } };
expect(await callWaitTool("wait_until", {}, context)).toEqual({ text: "Only the person can set up or stop a wait…", isError: true });
});
it("lists with a GET and cancels by id", async () => {
await callWaitTool("list_waits", {}, context); await callWaitTool("cancel_wait", { id: "w1" }, context);
expect(calls).toEqual([["/api/internal/waits", undefined], ["/api/internal/waits/cancel", { method: "POST", body: '{"id":"w1"}' }]]);
});
server/drivers/agents-catalog-wire.test.ts, in the describe:
it("offers the wait tools right after the trigger tools on every profile", () => {
for (const [name, wire] of Object.entries(wires)) {
const names = toolsOf(wire).map((tool) => tool.name);
const at = names.indexOf("manage_trigger");
expect(names.slice(at + 1, at + 4), name).toEqual(["wait_until", "list_waits", "cancel_wait"]);
}
});
server/system-prompt.test.ts:296: expect(TRIGGER_PROMPT).toContain("use wait_until instead of staying busy or making a short-interval routine");
Policy and proxy lists as in Files.
- Step 2: Run them and see them fail
Run: pnpm exec vitest run server/drivers/agents-wait-tools.test.ts server/drivers/agents-catalog-wire.test.ts server/drivers/agents-proxy.test.ts server/agent-tool-policy.test.ts server/system-prompt.test.ts
Expected: FAIL in each file on the new names.
Step 3: Implement the driver on the
agents-helper-tools.tsshape (route map,apiResponse,body.text/body.error), the definitions, the dispatch line, the policy entry and the sentence.Step 4: Regenerate the goldens and move the budgets
Run: UPDATE_AGENTS_CATALOG_GOLDENS=1 pnpm exec vitest run server/drivers/agents-catalog-wire.test.ts server/drivers/agents-bridge-wire.test.ts
Review the golden diff: only the three tools and the three names in find_tool's description. Three tools do not fit the ±2% budget (the default profile is already at 62,220 bytes against 61,361), so set every BUDGET_BASELINE entry in agents-catalog-wire.test.ts to the new bytes this prints:
node -e 'for (const [k, v] of Object.entries(require("./server/drivers/agents-catalog-goldens/profiles.json"))) console.log(` "${k}": ${v.bytes},`)'
The bridged lists grow only by three names (about 40 bytes, under 2%), so agents-bridge-wire.test.ts keeps its baselines; if one fails, set it the same way from bridged.profiles.json.
- Step 5: Run the driver suites and see them pass
Run: pnpm exec vitest run server/drivers server/agent-tool-policy.test.ts server/system-prompt.test.ts
Expected: PASS.
- Step 6: Commit
git add server/drivers server/agent-tool-policy.ts server/agent-tool-policy.test.ts server/system-prompt.ts server/system-prompt.test.ts
git commit -m "feat(waits): wait_until, list_waits and cancel_wait in the agents catalog"
Task 7: Wire waits into the server
Files:
- Modify:
server/index.ts(imports;:9028joinConversation; after:9153construction;:9676undo branch;:9733tie to bots;:11390two helpers;:12491,:12498,:12499maintenance;:12850route instance;:13425mount;:16055start;:16117stop) - Modify:
server/bot-automations.ts,server/bot-automations.test.ts - Modify:
server/workspace-backup.ts:29-45,server/workspace-backup.test.ts - Create:
server/waits.e2e.test.ts
Interfaces:
- Consumes:
WaitManager(Task 3),createWaitHost,waitRunChat(Task 4),createWaitRoutes,waitSourceRefusal,hostWaitRefusal,findWaitPeer,WaitRouteContext(Task 5). - Produces:
bot-automations.tsAutomations.waits?: Pick<WaitManager, "removeForBot" | "owners">: itsowners()count at start like the other automations' bots, andremoveForalso callswaits.removeForBot(inside the same try/catch loop).
server/index.ts, line by line:
- Two module-level helpers beside
connectorThread(:11390):function directChatOf(botId: string, threadId: string): boolean—connectorThreadexists and has nogroup.function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick<WaitRouteContext, "sourceRefusal" | "hostRefusal" | "peer">—sourceRefusalfeedswaitSourceRefusalwithowned/roomfromconnectorThread(sender.id, threadId),depth: capability.depth,handedOff: Boolean(capability.roomHandoffId),routineRun: Boolean(activeRoutineRunForThread(threadId)),outsideDriven: outsideDrivenThread(threadId),personStarted: turnOrigin(capability).kind === "user",guest: cloudGuestDriven(threadId);hostRefusalfeedshostWaitRefusalwithcloudHome: Boolean(CLOUD_HOME),hosted: HOSTED_WORKSPACE,guest, andplace=turnPlaces.get(threadId)when itsbotIdis the sender's, else null;peer=findWaitPeer(reachablePeers(store.bots, sender), sender.id, name).
- After
calendarCalls = new CalendarCallManager(…):const botWaits = new WaitManager(createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input), cloudHome: Boolean(CLOUD_HOME) }));andstore.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); }); joinConversationfirst line:if (run.eventSource === "wait") return waitRunChat(run, directChatOf, Boolean(CLOUD_HOME));undoAppliedChange, beforecard.profileRequest:else if (card.waitRequest) result = card.undone ? { claimed: true, state: "already_undone" } : botWaits.cancel(card.waitRequest.waitId, botId) ? { claimed: true, state: "undone" } : { claimed: true, state: "invalid", error: "This wait has already ended.", status: 409 };tieAutomationsToBots(store, { …, waits: botWaits }).- Maintenance:
!botWaits.isTickinginidle;botWaits.stop()inpause;botWaits.start()inside the!moveFreeze.frozen()branch ofresume. - Beside
helperToolRoutes(:12850):const waitRoutes = createWaitRoutes({ waits: botWaits });. In the:13425chain, after thehelperToolRoutes(…) !== PASSterm:|| await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS. :16055: start and stopbotWaitsin the samemoveFreeze.holdasroutines.:16117:botWaits.stop();.
server/workspace-backup.ts: add "waits.json" to EXCLUDED with the line comment // Waits watch this machine's files and programs and end within a week.
- Step 1: Write the failing tests
server/bot-automations.test.ts: extend fixture with waits: { removeForBot: vi.fn(), owners: () => owners.waits ?? [] } and add
it("removes a deleted bot's waits, at start and when it is deleted", () => {
const { automations, emit } = fixture(["scout"], { waits: ["gone", "scout"] });
emit({ type: "bot.deleted", botId: "scout" });
expect(automations.waits.removeForBot.mock.calls).toEqual([["gone"], ["scout"]]);
});
server/workspace-backup.test.ts: it("leaves waits out of backups and Cloud sends", () => expect(omittedFromWorkspaceBackup("waits.json")).toBe(true));
server/waits.e2e.test.ts, on the server/chat-widgets.e2e.test.ts pattern (launchVerificationServer({ FAKE_CLAUDE_MODE: "slow", FAKE_CLAUDE_SLOW_FINISH_GATE: gate }), the turn's OMB_COMMS_TOKEN from the fake dump, the internal route called with it as Bearer):
it("waits for a file with no AI, posts once in the asked chat, notifies, and continues there; Cancel on its card stops another", async () => {
// Scout; control send "Tell me when the report is ready"; token from the dump while the slow turn is open.
const made = await api("POST", "/api/internal/waits", { label: "the report is ready", kind: "file_exists", path: report, then: "Say the report is ready." }, 201, token);
expect(made.text).toMatch(/\(wait id [\w-]+\)/);
writeFileSync(present, "x");
expect((await api("POST", "/api/internal/waits", { label: "present", kind: "file_exists", path: present }, 200, token)).text).toContain("already. Nothing was set up");
await api("POST", "/api/internal/waits", { label: "the other file", kind: "file_exists", path: other, then: "Never." }, 201, token);
const cards = (await transcript()).filter((m) => m.card?.waitRequest);
expect(cards.map((m) => m.card.title)).toEqual(["Waiting: the report is ready", "Waiting: the other file"]);
await api("POST", `/api/threads/${bot.threadId}/undo`, { requestId: cards[1].card.requestId }, 200);
expect((await transcript()).find((m) => m.id === cards[1].id).card).toMatchObject({ undone: true, waitRequest: { settled: "cancelled" } });
writeFileSync(gate, "finish"); await settledTurn();
writeFileSync(report, "done"); writeFileSync(other, "x");
await expect.poll(async () => (await transcript()).filter((m) => m.wait?.status === "fired").map((m) => m.text), { timeout: 30_000 })
.toEqual([`the report is ready: done. ${report} is there now.`]);
await expect.poll(async () => (await transcript()).some((m) => m.role === "user" && m.text?.includes("[Wait finished: the report is ready] Say the report is ready.")), { timeout: 40_000 }).toBe(true);
expect((await api("GET", "/api/notifications")).notifications.filter((n) => n.kind === "wait")).toMatchObject([{ title: "Scout's wait is over" }]);
await new Promise((resolve) => setTimeout(resolve, 7_000));
expect((await transcript()).filter((m) => m.wait).length).toBe(1);
}, 120_000);
report, present and other are paths in a mkdtemp folder; present is written before its call.
- Step 2: Run them and see them fail
Run: pnpm exec vitest run server/bot-automations.test.ts server/workspace-backup.test.ts server/waits.e2e.test.ts
Expected: FAIL: waits is not removed, waits.json is backed up, the internal route answers 404.
Step 3: Implement the changes listed above.
Step 4: Run them and the guards, and see them pass
Run: pnpm exec vitest run server/bot-automations.test.ts server/workspace-backup.test.ts server/waits.e2e.test.ts scripts/testing/index-route-ratchet.test.ts && pnpm typecheck && pnpm lint
Expected: PASS; the ratchet unchanged; typecheck and lint clean.
- Step 5: Commit
git add server/index.ts server/bot-automations.ts server/bot-automations.test.ts server/workspace-backup.ts server/workspace-backup.test.ts server/waits.e2e.test.ts
git commit -m "feat(waits): run waits in the server, tie them to bots, keep them out of backups"
Task 8: The card's line with Cancel
Files:
- Modify:
src/components/ApprovalCard.tsx:128-187(appliedChange) and:190-260(AppliedChangeLinebutton label) - Modify:
src/locales/en.json("approval.applied.wait": "{name} is waiting for {title}", besideapproval.applied.teamMemory; English only, other packs fall back) - Test:
src/components/ApprovalCard.test.ts
Interfaces:
Consumes:
OptionCardData.waitRequest(Task 4); the undo route (Task 7 step 4).Produces:
appliedChangereturns{ line: string; canUndo: boolean; undoLabel?: LocaleKey }; a wait card gives{ line: t("approval.applied.wait", { name, title: label }), canUndo: !settled, undoLabel: "common.cancel" };AppliedChangeLineshowst(summary.undoLabel ?? "approval.applied.undo").Step 1: Write the failing test
it("shows a wait with a follow-up as one line with Cancel, and no Cancel once it ended", () => {
const message = (settled?: "fired") => ({ id: "m1", at: 1, role: "bot", kind: "options", card: { title: "Waiting: the build finishes", subtitle: "When the build finishes, Pepper will: Deploy it.",
options: [], answered: "allow", dismissed: true, autoApplied: true, requestId: "w1", tool: "wait_until",
waitRequest: { waitId: "w1", label: "the build finishes", then: "Deploy it.", ...(settled ? { settled } : {}) } } }) as Message;
const open = renderToStaticMarkup(createElement(ApprovalCard, { bot: { name: "Pepper" }, message: message(), threadId: "t1" }));
expect(open).toContain("Pepper is waiting for the build finishes");
expect(open).toContain(">Cancel<");
expect(renderToStaticMarkup(createElement(ApprovalCard, { bot: { name: "Pepper" }, message: message("fired"), threadId: "t1" }))).not.toContain(">Cancel<");
});
- Step 2: Run it and see it fail
Run: pnpm exec vitest run src/components/ApprovalCard.test.ts
Expected: FAIL: the card renders as an approval box, not one line.
Step 3: Implement the branch and the label.
Step 4: Run it and the locale check, and see them pass
Run: pnpm exec vitest run src/components/ApprovalCard.test.ts && pnpm i18n:check && pnpm typecheck
Expected: PASS.
- Step 5: Commit
git add src/components/ApprovalCard.tsx src/components/ApprovalCard.test.ts src/locales/en.json
git commit -m "feat(waits): a wait's card reads as one line with Cancel"
Task 9: Verification recipe, run against a fixture
Files:
- Create:
docs/verification/waits.md - Modify:
docs/verification/README.md(one line in "Drive", after "Proactive routines and the brief":- [Waits: tell me when, with no AI while waiting](waits.md)) - Modify:
scripts/mcp-server.ts:714(projectMessagealso returns...(message.wait ? { wait: message.wait } : {}), somessagesshows it)
Interfaces:
Consumes: everything above; the fake engine's
FAKE_CLAUDE_TOOL_CALLS_FILEwith"server": "agents"(server/testing/fake-claude-cli.ts:31-32,:1000).Step 1: Write
docs/verification/waits.md
Sections: what a wait is (two sentences, link to the spec); Automated checks (pnpm exec vitest run server/wait-probes.test.ts server/waits.test.ts server/wait-host.test.ts server/routes/waits.test.ts server/drivers/agents-wait-tools.test.ts server/waits.e2e.test.ts src/components/ApprovalCard.test.ts); In a fixture, these commands:
W=$(mktemp -d)
printf '[{"server":"agents","name":"wait_until","input":{"label":"the report is ready","kind":"file_exists","path":"%s/report.txt","then":"Say the report is ready."}}]' "$W" > "$W/calls.json"
FAKE_CLAUDE_TOOL_CALLS_FILE="$W/calls.json" node --experimental-strip-types scripts/control-omb.ts launch
Second terminal (same W):
pnpm control:omb new-bot --name Pepper --url http://127.0.0.1:PORT
pnpm control:omb send --bot BOT_ID --text "Tell me when report.txt is there, then say so" --url http://127.0.0.1:PORT
pnpm control:omb wait --bot BOT_ID --timeout 30 --url http://127.0.0.1:PORT
pnpm control:omb messages --bot BOT_ID --limit 10 --url http://127.0.0.1:PORT
echo '[]' > "$W/calls.json"; touch "$W/report.txt"; sleep 25
pnpm control:omb wait --bot BOT_ID --timeout 60 --url http://127.0.0.1:PORT
pnpm control:omb messages --bot BOT_ID --limit 10 --url http://127.0.0.1:PORT
curl -s http://127.0.0.1:PORT/api/notifications
sleep 10; pnpm control:omb messages --bot BOT_ID --limit 10 --url http://127.0.0.1:PORT
Expected, written into the doc: after the first messages, a wait_until tool row that succeeded and a card titled Waiting: the report is ready; after the touch, exactly one bot line the report is ready: done. <W>/report.txt is there now. carrying "wait": { "status": "fired" }, then a user line [Wait finished: the report is ready] Say the report is ready. and the fake engine's reply; one notification with "kind": "wait" and "title": "Pepper's wait is over"; the last messages still shows one fired line. What it does not prove: the desktop card's Cancel button (Task 8's test and the e2e undo call cover it), phones, a real page on the internet. Cleanup: Ctrl-C the launcher; rm -r "$W". Last exercised: filled in Step 2.
- Step 2: Run the recipe and record it
Run every command in the doc against a fresh fixture. Under Last exercised, write the date, the fixture's printed log path, and the JSON of the fired line, the follow-up user line and the wait notification.
Expected: every expectation in the doc holds.
- Step 3: Full check
Run: pnpm typecheck && pnpm lint && pnpm exec vitest run server/wait-probes.test.ts server/waits.test.ts server/wait-host.test.ts server/routes/waits.test.ts server/drivers server/agent-tool-policy.test.ts server/system-prompt.test.ts server/notify.test.ts server/routines.test.ts server/bot-automations.test.ts server/workspace-backup.test.ts server/read-and-draft.test.ts src/components/ApprovalCard.test.ts src/components/NotificationsPanel.test.ts scripts/testing/index-route-ratchet.test.ts server/waits.e2e.test.ts
Expected: all PASS.
- Step 4: Commit
git add docs/verification/waits.md docs/verification/README.md scripts/mcp-server.ts
git commit -m "docs(verification): waits recipe, exercised against a fixture"