Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
import { join } from "node:path";
import type { BeginTurnRequest, Coordinator, CoordinatorHost, CoordinatorOptions, HandoffLimit, HandoffOptions, HandoffView, HostTurnResult, LiveHandoffEdge, RoomAddress } from "./coordinator.ts";
import type { WorkOrigin } from "./peer-provenance.ts";
import { composeEnvelope, composeQuestion, composeReport, composeResume, composeRootTurn, continuationLine, envelopeNote } from "./runtime/envelope.ts";
import { handoffLimits } from "./runtime/handoff-limits.ts";
import { Runtime } from "./runtime/runtime.ts";
import { importLegacyDelegations, importLegacyHandoffs, type LegacyThreadResolver } from "./runtime/import-legacy.ts";
import { openRuntimeStore, type RuntimeStore } from "./runtime/store.ts";
import { personOnly, requesterDecides, withDefault } from "./runtime/questions.ts";
import { isStatusOnly, mayBeStatusOnly, statusReplyPrompt } from "./runtime/status-reply.ts";
import { answersSender, childrenSince, clip, isTerminal, ownThread, path } from "./runtime/tree.ts";
import type { Answerer, Assignee, Assignment, EndResult, Origin, Owner, Reply, Requester, RunInput, RunResult, StatusView, TurnRunner } from "./runtime/types.ts";
import { STOPPED_BY_USER, TURN_CUT } from "./runtime/types.ts";
import { sameRequest } from "./same-request.ts";
const NOT_RUNNING = "The originating room task is no longer running";
const WRONG_SPEAKER = "The handoff belongs to a different room speaker";
const ANCESTOR = "Cannot assign work back to an ancestor; results return automatically";
const ALREADY_COMPLETED = "This agent already completed your assignment. Do not send acknowledgements or approvals as new work. Finish with your decision; results return automatically. Only use rework=true for concrete additional work.";
const ROOM_ANCESTOR = "A room request cannot return to an ancestor room; results are returned automatically";
const DEPTH = "Room handoff depth limit reached";
const TOTAL_BUDGET = /^Request budget exhausted: \d+ turns in all/;
const totalRefusal = (limit: number): string => `This request has started ${limit} turns in all, the most one request may take, so this one was not sent. Nobody can reset that, the person included, so don't ask them to, and don't send it another way. Finish with what you have and say what is left undone.`;
const budgetRefusal = (limit: number): string => `This request reached its limit of ${limit} hand-offs since any work last came back, so this one was not sent. The limit belongs to the request: nobody can reset it, the person included, so don't ask them to, and don't send it another way. If work is still out, end your turn: each result that comes back renews the limit and resumes you. If nothing is out, finish with what you have and say what is left undone.`;
const NO_TURN = "The requesting turn has no root (no turn)";
/** How long a person's stop holds against the same request coming back. */
const STOP_MEMORY_MS = 24 * 60 * 60_000;
const STOPPED_AGAIN = "The person stopped this teammate's work on this request. It isn't handed out again until the person asks again: tell them what you still wanted done, and don't send it another way.";
/** The person's request a tree traces to, as one key: their own words, harness-quoted. Empty when no person's line started it. */
const requestKey = (root: Assignment): string => root.origin.kind === "person" ? (root.origin.quote ?? "").replace(/\s+/g, " ").trim().toLowerCase() : "";
const BRIEF_MAX = 12_000;
const RUNTIME_DEPTH = /^Assignment depth limit reached/;
const NEEDS_INPUT = /^needs input:/i;
/** A NEEDS INPUT line whose whole value says there is nothing to ask ("none", "无", …) asks nothing. */
const NOTHING_TO_ASK = new Set(["none", "nothing", "n/a", "nil", "-", "—", "无", "無", "没有", "沒有", "无需", "暂无", "なし", "없음", "нет",
"ninguna", "ninguno", "nada", "aucune", "aucun", "rien", "keine", "nichts", "nenhuma", "nenhum", "không", "ไม่มี"]);
/** Per-turn stalls belong to the host's watchdog: this only keeps the runtime's window out of its way. */
const TURN_STALL_MS = 24 * 60 * 60_000;
/** Handed-off work parked on the person: a reminder after a day, closed after three. */
const PARKED_REMIND_MS = 24 * 60 * 60_000;
const PARKED_LIMIT_MS = 72 * 60 * 60_000;
const REQUESTS_PER_ROOT = 64;
const EXECUTIONS_PER_ROOT = 96;
const PRUNE_AFTER_MS = 30 * 24 * 60 * 60_000;
const PRUNE_EVERY_MS = 24 * 60 * 60_000;
const address = (a: Assignment): RoomAddress => {
const { groupId, threadId } = a.assignee.destination;
return { threadId, botId: a.assignee.botId, ...(groupId !== undefined ? { groupId } : {}) };
};
const sameSpeaker = (a: Assignment, source: RoomAddress): boolean =>
a.assignee.destination.groupId === source.groupId && a.assignee.destination.threadId === source.threadId && a.assignee.botId === source.botId;
const ancestorOf = (ancestor: RoomAddress, target: RoomAddress): boolean =>
ancestor.botId === target.botId && (!ancestor.groupId || !target.groupId || ancestor.groupId === target.groupId);
const kindOf = (groupId: string | undefined, parent: Assignment | undefined): HandoffView["kind"] =>
groupId !== undefined && parent?.assignee.destination.groupId === groupId ? "assignment" : "work";
function legacyOrigin(origin: Origin): WorkOrigin | undefined {
if (origin.kind !== "person") return { kind: "outside" };
return origin.quote ? { kind: "user", request: origin.quote } : undefined;
}
const hostFirstTurn = (a: Assignment): boolean => !a.parentId && a.status === "running" && a.executions === 1;
function runtimeOrigin(origin: WorkOrigin | undefined, source: RoomAddress): Origin {
return origin?.kind === "user"
? { kind: "person", source: "chat", ref: source.threadId, quote: origin.request }
: { kind: "outside", source: "chat", ref: source.threadId };
}
/** The question a reply ends on: its last line starts with NEEDS INPUT:, or the line before a closing `Default:` line. */
export function needsInputQuestion(text: string): string | undefined {
const lines = text.split(/\r?\n/);
const filled = (from: number) => { let at = from; while (at >= 0 && lines[at]!.trim() === "") at -= 1; return at; };
const last = filled(lines.length - 1);
if (last < 0) return undefined;
const at = /^default:/i.test(lines[last]!.trim()) ? filled(last - 1) : last;
const line = at < 0 ? "" : lines[at]!.trim();
if (!NEEDS_INPUT.test(line)) return undefined;
const value = line.slice("NEEDS INPUT:".length).trim();
if (NOTHING_TO_ASK.has(value.replace(/[.!。!]+$/u, "").toLowerCase())) return undefined;
const question = [value, ...lines.slice(at + 1)].join("\n").trim();
return question || undefined;
}
export function handoffReply(text: string): Pick<HostTurnResult, "text" | "question"> {
return { text: text.slice(0, BRIEF_MAX), question: needsInputQuestion(text) ?? null };
}
export function handoffQuestion(result: Pick<HostTurnResult, "text" | "question">): string | undefined {
return result.question === undefined ? needsInputQuestion(result.text) : result.question ?? undefined;
}
export function view(a: Assignment, parent?: Assignment): HandoffView {
const groupId = a.assignee.destination.groupId;
const status: HandoffView["status"] = hostFirstTurn(a) ? "source" : a.status === "needs_input" ? "waiting" : a.status;
const node: HandoffView = {
id: a.id, rootId: a.rootId, threadId: a.assignee.destination.threadId, botId: a.assignee.botId, key: a.assignee.botId,
text: a.brief, createdAt: a.createdAt, status, result: a.result, reported: a.reportedAt !== undefined, executions: a.executions,
lastProgressAt: a.lastActivityAt, kind: kindOf(groupId, parent), restarts: a.restarts,
mode: a.mode, reply: a.reply,
};
if (a.outcome !== undefined) node.outcome = a.outcome;
if (a.outcomeDetail !== undefined) node.outcomeDetail = a.outcomeDetail;
if (a.question !== undefined) node.question = a.question;
if (a.decide !== undefined) node.decide = a.decide;
if (a.answer !== undefined) node.answer = a.answer;
if (a.answeredBy !== undefined) node.answeredBy = a.answeredBy;
if (a.carrying !== undefined) node.carrying = a.carrying;
if (a.cards !== undefined) node.cards = a.cards;
if (a.continuation !== undefined) node.continuation = { ...a.continuation };
if (a.goalRunId !== undefined) node.goalRunId = a.goalRunId;
if (a.parentId !== undefined) node.parentId = a.parentId;
if (groupId !== undefined) node.groupId = groupId;
if (a.batchKey !== undefined) node.requestBatchKey = a.batchKey;
if (a.statusOnly) node.statusOnly = true;
if (a.startedAt !== undefined) node.startedAt = a.startedAt;
const origin = legacyOrigin(a.origin);
if (origin) node.origin = origin;
if (a.restart !== undefined) node.restart = a.restart;
return node;
}
function announcingWrites(store: RuntimeStore, wrote: () => void): RuntimeStore {
const announced = <A extends unknown[], R>(write: (...args: A) => R) => (...args: A): R => {
const result = write(...args);
wrote();
return result;
};
return { ...store, insert: announced(store.insert), update: announced(store.update), addInbox: announced(store.addInbox),
markDelivered: announced(store.markDelivered), prune: announced(store.prune) };
}
/** A request back to a bot that waits on the asker's answer in the same conversation would leave each waiting on the other.
* The ancestor rule covers this within one request; this covers two requests. A request from another of the asker's
* conversations goes through: each conversation answers its own. The waiting request's words are not repeated: it may come
* from another person's private chat. */
const crossed = (asker: string, request: Assignment, here: boolean): string => here ? `@${asker} is already waiting on you: it handed you a request in this conversation (assignment ${
request.id}), and you have not finished it yet. Asking @${asker} for something now would leave each of you waiting on the other, so this was not sent. Answer that request here from what you know; once @${
asker} has your answer, you can ask it again.` : `@${asker} is already waiting on you: it handed you a request (assignment ${
request.id}), and ${request.status === "queued" ? "that has not reached you yet" : request.status === "running" ? "you are answering it in another conversation now"
: "you have not finished it yet"}. Asking @${asker} for something now would leave each of you waiting on the other, so this was not sent. Answer the person here from what you know; @${
asker}'s request reaches you in its own thread, and your answer there goes back to it. Once @${asker} has that answer, you can ask it again.`;
/** How often a request that joined another looks at it. */
const JOIN_POLL_MS = 1_000;
const JOINED_NOTE = "Another teammate asked this a moment ago, so it was answered once, for both of you:";
export class RuntimeCoordinator implements Coordinator {
private readonly host: CoordinatorHost;
private readonly handoffLimit: HandoffLimit | undefined;
private readonly store: RuntimeStore;
private readonly runtime: Runtime;
private readonly legacyFile: string | undefined;
private readonly legacyDir: string | undefined;
private readonly legacyThreads: LegacyThreadResolver | undefined;
private readonly now: () => number;
private readonly log: (line: string) => void;
/** The person's stops, remembered: which bots' work on which request they stopped, and when. */
private readonly stops: Array<{ at: number; request: string; bots: Set<string>; rootId?: string }> = [];
/** The cause of the stop running now, if any (stopFor). */
private stopCause: string | undefined;
/** A single hand-off is being stopped (stopHandoff): its thread's other work is not part of that stop. */
private stoppingHandoff = false;
private opened = false;
private prunedAt: number | undefined;
constructor(options: CoordinatorOptions) {
this.host = options.host;
this.handoffLimit = options.handoffLimit;
this.legacyDir = options.dataDir === ":memory:" ? undefined : options.dataDir;
this.legacyFile = this.legacyDir === undefined ? undefined : join(this.legacyDir, "room-handoffs.json");
this.legacyThreads = options.legacyThreads;
this.now = options.now ?? Date.now;
this.log = options.log ?? ((line) => console.error("coordinator:", line));
const store = openRuntimeStore(options.dataDir === ":memory:" ? ":memory:" : join(options.dataDir, "runtime.db"));
this.store = options.wrote ? announcingWrites(store, options.wrote) : store;
this.runtime = new Runtime(this.store, this.runner(), {
clock: { now: () => this.now(), monotonic: () => performance.now() },
limits: { depth: 4, requests: REQUESTS_PER_ROOT, executions: EXECUTIONS_PER_ROOT, turnStallMs: TURN_STALL_MS, inputWaitMs: PARKED_LIMIT_MS, inputRemindMs: PARKED_REMIND_MS, ...handoffLimits(), ...options.runtimeLimits },
...(options.log ? { log: options.log } : {}),
...(options.restartCut ? { restartCut: options.restartCut } : {}),
});
}
/** Not at construction: reconciling calls the host, which is still initialising then. */
private ready(): void {
if (this.opened) return;
this.opened = true;
if (this.legacyFile) {
try {
const imported = importLegacyHandoffs(this.store, this.legacyFile, this.now());
if (imported) this.log(`imported ${imported} room-handoff rows from ${this.legacyFile}`);
} catch (error) {
this.log(`room-handoffs.json not imported: ${String(error)}`);
}
}
if (this.legacyDir) {
try {
const imported = importLegacyDelegations(this.store, this.legacyDir, this.now(),
{ log: this.log, ...(this.legacyThreads ? { threads: this.legacyThreads } : {}) });
if (imported) this.log(`imported ${imported} delegation-ledger rows from ${this.legacyDir}`);
} catch (error) {
this.log(`delegations.json not imported: ${String(error)}`);
}
}
this.runtime.open();
}
node(id: string): HandoffView | undefined {
this.ready();
const a = this.store.get(id);
return a && this.project(a);
}
answersTo(id: string): { botId: string; threadId: string } | undefined {
this.ready();
const a = this.store.get(id);
const { botId, threadId } = a?.requester ?? {};
return a && botId && threadId && answersSender(a, "notify", { botId, threadId }) ? { botId, threadId } : undefined;
}
has(id: string): boolean {
this.ready();
return this.store.get(id) !== undefined;
}
all(): HandoffView[] {
this.ready();
const rows = this.store.all();
const byId = new Map(rows.map(row => [row.id, row]));
return rows.map(row => view(row, row.parentId ? byId.get(row.parentId) : undefined));
}
newestRoot(threadId: string, ids: Iterable<string>): HandoffView | undefined {
this.ready();
let newest: Assignment | undefined;
for (const id of ids) {
const a = this.store.get(id);
if (a && !a.parentId && a.assignee.destination.threadId === threadId && (!newest || a.createdAt >= newest.createdAt)) newest = a;
}
return newest && view(newest);
}
inThread(threadId: string, filter: { open?: boolean; since?: number } = {}): HandoffView[] {
this.ready();
return this.store.all({ assigneeThreadId: threadId, ...(filter.open ? { nonTerminal: true } : {}), ...(filter.since !== undefined ? { openSince: filter.since } : {}) })
.map(a => this.project(a));
}
active(): HandoffView[] {
this.ready();
return this.live().map(row => this.project(row));
}
threadActivity(threads: ReadonlyMap<string, ReadonlySet<string>>): {
awaitingAnswer: Set<string>; activeDirect: Set<string>; queued: Map<string, Map<string, HandoffView>>;
} {
this.ready();
const awaitingAnswer = new Set<string>();
const activeDirect = new Set<string>();
const queued = new Map<string, Map<string, HandoffView>>();
for (const row of this.live()) {
const { threadId, groupId } = row.assignee.destination;
const bots = threads.get(threadId);
if (!bots) continue;
if (row.status === "needs_input") awaitingAnswer.add(threadId);
if (groupId === undefined) activeDirect.add(threadId);
if (row.status !== "queued" || groupId || !bots.has(row.assignee.botId)) continue;
let byBot = queued.get(threadId);
if (!byBot) { byBot = new Map(); queued.set(threadId, byBot); }
if (!byBot.has(row.assignee.botId)) byBot.set(row.assignee.botId, this.project(row));
}
return { awaitingAnswer, activeDirect, queued };
}
children(id: string): HandoffView[] {
this.ready();
const parent = this.store.get(id);
return this.store.children(id).map(child => view(child, parent));
}
enqueue(source: RoomAddress, generation: string, parentId: string | undefined, target: RoomAddress, text: string,
options: HandoffOptions = {}): { node: HandoffView; duplicate: boolean } {
this.ready();
const { rework = false, requestBatchKey, fanOut, thread } = options;
const mode = options.mode ?? "work";
const parent = parentId ? this.store.get(parentId) : this.store.get(generation);
if (!parent) throw new Error(parentId ? NOT_RUNNING : NO_TURN);
if (parent.status !== "running") throw new Error(NOT_RUNNING);
if (!sameSpeaker(parent, source)) throw new Error(WRONG_SPEAKER);
const brief = clip(text, BRIEF_MAX);
const kind: HandoffView["kind"] = target.groupId !== undefined && target.groupId === source.groupId ? "assignment" : "work";
const lineage = path(this.store, parent);
const root = lineage[0]!;
const assignee: Assignee = { botId: target.botId, destination: { kind: target.groupId ? "room_thread" : thread === "standing" ? "standing_thread" : "work_thread",
threadId: target.threadId, ...(target.groupId ? { groupId: target.groupId } : {}) } };
const own = ownThread(lineage, assignee, options.ownThread);
const wanted: Reply = mode === "notify" ? "none" : options.reply ?? "resume";
const reply: Reply = wanted === "none" ? "none" : root.reply === "poll" ? "poll" : wanted;
// Same rule as the runtime's admit: only a reply that would wait on the ancestor's completion closes a wait cycle.
if (!answersSender(parent, mode, target) && reply === "resume" && (own ? lineage.slice(0, -1) : lineage).some(n => ancestorOf(address(n), target))) throw new Error(ANCESTOR);
if (this.stoppedFor(root, target.botId)) throw new Error(STOPPED_AGAIN);
const siblings = this.store.children(parent.id);
const existing = siblings.findLast(c => c.assignee.botId === target.botId && c.assignee.destination.groupId === target.groupId && c.brief === brief && c.mode === mode
&& (!own || c.assignee.destination.threadId === target.threadId));
if (existing && !(rework && isTerminal(existing))) return { node: view(existing, parent), duplicate: true };
const limited = this.handoffLimit?.refusal(target.botId, () => this.live().filter(a => a.parentId !== undefined).length, parent.origin.kind === "person" ? "user" : "outside");
if (limited) throw new Error(limited);
if (mode === "work" && !rework && !own && siblings.some(c => c.mode === "work" && kindOf(c.assignee.destination.groupId, parent) === kind &&
c.assignee.destination.groupId === target.groupId && c.assignee.botId === target.botId && c.status === "completed")) throw new Error(ALREADY_COMPLETED);
if (kind === "work" && target.groupId && lineage.some(n => n.assignee.destination.groupId === target.groupId)) throw new Error(ROOM_ANCESTOR);
// A bot's own threads wait on it by design and can never ask it back (the ancestor rule above), so no two bots can cross.
const waiting = own || mode === "notify" || target.groupId !== undefined ? undefined : this.waitingOn(source, target);
if (waiting) throw new Error(crossed(this.host.names(this.project(waiting.request), this.project(waiting.parent)).requester, waiting.request, waiting.here));
const requester: Requester = { kind: "bot_turn", botId: parent.assignee.botId, threadId: parent.assignee.destination.threadId,
chief: this.host.chiefOf(address(parent)), ...(parent.id === root.id && root.requester.runId !== undefined ? { runId: root.requester.runId } : {}) };
const level = this.host.levelOf(target, this.project(parent));
const result = this.runtime.enqueue({
parentId: parent.id,
origin: parent.origin,
requester,
assignee, mode, reply, brief: text, rework,
...(own ? { ownThread: true } : {}),
...(options.doneWhen ? { doneWhen: options.doneWhen } : {}),
levels: { own: level.level, ...(level.chief !== undefined ? { chief: level.chief } : {}) },
...(level.driverKind !== undefined ? { driverKind: level.driverKind } : {}),
...(target.groupId && requestBatchKey ? { batchKey: requestBatchKey } : {}),
...(fanOut ? { fanOut } : {}),
});
if (!result.ok) {
if (result.outcome === "budget") throw new Error(TOTAL_BUDGET.test(result.reason) ? totalRefusal(this.runtime.limits.totalExecutions) : budgetRefusal(this.runtime.limits.requests));
throw new Error(RUNTIME_DEPTH.test(result.reason) ? DEPTH : result.reason);
}
return { node: view(result.assignment, parent), duplicate: result.duplicate };
}
status(id: string): StatusView | undefined {
this.ready();
return this.runtime.status(id);
}
job(threadId: string, since: number, botId?: string): { scopes: string[]; rows: Assignment[] } {
this.ready();
const given = new Map<string, Assignment>();
for (const a of this.store.all({ ownerThreadId: threadId, roots: true, openSince: since })) {
if (a.assignee.destination.threadId === threadId) given.set(a.id, a);
}
if (botId) for (const a of this.store.all({ assignee: { botId, threadId }, openSince: since })) given.set(a.id, a);
const rows = new Map<string, Assignment>();
const scopes: string[] = [];
for (const start of [...given.values()].sort((a, b) => a.createdAt - b.createdAt)) {
if (rows.has(start.id)) continue;
scopes.push(start.id);
const subtree = start.parentId ? this.subtree(start) : this.store.all({ rootId: start.id });
for (const a of subtree) rows.set(a.id, a);
}
return { scopes, rows: [...rows.values()].sort((a, b) => a.createdAt - b.createdAt) };
}
private subtree(start: Assignment): Assignment[] {
const out = [start];
const seen = new Set([start.id]);
for (let i = 0; i < out.length; i++) {
for (const child of this.store.children(out[i]!.id)) if (!seen.has(child.id)) { seen.add(child.id); out.push(child); }
}
return out;
}
poll(owner: Owner): { items: StatusView["inbox"]; assignments: HandoffView[] } {
this.ready();
const polled = this.runtime.poll(owner);
return { items: polled.items, assignments: polled.assignments.map(a => this.project(a)) };
}
outstandingFor(threadId: string): HandoffView[] {
this.ready();
return this.store.all({ nonTerminal: true, assigneeThreadId: threadId })
.flatMap(parent => this.store.children(parent.id).filter(a => !isTerminal(a) && a.reply !== "none").map(a => ({ a, parent })))
.sort((x, y) => x.a.createdAt - y.a.createdAt)
.map(({ a, parent }) => view(a, parent));
}
runningIn(threadId: string): HandoffView[] {
this.ready();
return this.store.all({ nonTerminal: true, assigneeThreadId: threadId }).map(a => this.project(a)).filter(n => n.status === "running");
}
beginTurn(req: BeginTurnRequest): HandoffView {
this.ready();
const existing = this.store.get(req.id);
if (existing) return this.project(existing);
const { address, opener } = req;
const row = this.runtime.begin({
id: req.id,
origin: opener?.origin ?? runtimeOrigin(req.origin, address),
requester: opener
? { ...opener.requester, botId: opener.requester.botId ?? address.botId, threadId: opener.requester.threadId ?? address.threadId, chief: this.host.chiefOf(address) }
: { kind: "person", threadId: address.threadId, botId: address.botId, chief: this.host.chiefOf(address) },
assignee: { botId: address.botId, destination: { kind: address.groupId ? "room_thread" : "standing_thread", threadId: address.threadId,
...(address.groupId ? { groupId: address.groupId } : {}) } },
brief: req.brief.slice(0, BRIEF_MAX),
level: req.level,
...(opener?.requester.kind === "external_runtime" ? { reply: "poll" as const } : {}),
...(req.goalRunId ? { goalRunId: req.goalRunId } : {}),
});
return this.project(row);
}
endTurn(id: string, result: HostTurnResult): void {
this.ready();
const cards = result.cards && result.cards.ids.length > 0 ? result.cards : undefined;
const end: EndResult = { ok: result.ok, text: result.text, ...(result.evidence ? { evidence: result.evidence } : {}),
...(cards ? { needsInput: { question: cards.question, cards: cards.ids } } : {}),
...(result.cap ? { continue: { note: result.cap.note, ...(result.cap.handoffPath ? { handoffPath: result.cap.handoffPath } : {}) } } : {}),
...(result.stalled ? { stalled: true } : {}) };
this.runtime.end(id, end);
}
answerNode(id: string, text: string, by?: Answerer): boolean {
this.ready();
const a = this.store.get(id);
if (!a || a.status !== "needs_input") return false;
return this.runtime.answer(id, text, by);
}
followCard(threadId: string, from: string, to: string): void {
this.ready();
for (const n of this.live()) if (n.assignee.destination.threadId === threadId && n.cards?.includes(from)) this.runtime.followCard(n.id, from, to);
}
/** Nothing can answer what this parked turn waits on any more. */
releaseParked(id: string, reason: string): void {
this.ready();
if (this.store.get(id)?.status === "needs_input") this.stopFor(reason, () => this.runtime.cancel(id, reason, "stopped"));
}
parkedFor(botId: string): HandoffView[] {
this.ready();
return this.live().filter(n => n.status === "needs_input" && n.assignee.botId === botId).map(n => this.project(n));
}
answerRoot(id: string, text: string): boolean {
return this.answerNode(id, text);
}
parkedDirect(threadId: string): HandoffView | undefined {
this.ready();
const a = this.live().find(n => n.parentId === undefined && n.status === "needs_input" && this.direct(n, threadId));
return a && this.project(a);
}
prune(before: number): number {
this.ready();
return this.runtime.prune(before);
}
sharedRequest(node: HandoffView): { id: string; botIds: string[] } {
this.ready();
const batch = node.groupId && node.requestBatchKey && node.parentId
? this.store.children(node.parentId).filter(c => c.batchKey === node.requestBatchKey && c.assignee.destination.groupId === node.groupId &&
c.assignee.destination.threadId === node.threadId && c.brief === node.text)
: [];
if (batch.length === 0) return { id: node.id, botIds: [node.botId] };
return { id: batch[0]!.id, botIds: batch.map(c => c.assignee.botId) };
}
cancelRoom(groupId: string, threadId?: string, reason = STOPPED_BY_USER, status: "failed" | "cancelled" = "cancelled"): void {
this.ready();
this.stopFor(reason, () => {
for (const n of this.live()) {
if (n.assignee.destination.groupId !== groupId || (threadId && n.assignee.destination.threadId !== threadId)) continue;
this.runtime.cancel(n.id, reason, status === "failed" ? "failed" : "stopped");
}
});
}
cancelDirect(threadId: string, reason = STOPPED_BY_USER): void {
this.ready();
this.stopFor(reason, () => { for (const n of this.live()) if (this.direct(n, threadId)) this.runtime.cancel(n.id, reason, "stopped"); });
}
/** With no reason given, the stop is the person's, unless it is part of a stop already under way: see stopFor. TURN_CUT,
* a coordinated turn's own abort, is that stop too, and with none under way the system's cut. */
stopAwaitingDirect(threadId: string, reason?: string): void {
this.ready();
// The host stops a teammate's whole thread when one of its turns is aborted; when that turn is one hand-off the person
// stopped, the runtime already ends that hand-off and what it handed on, and other requests queued there go on.
const inner = reason === undefined || reason === TURN_CUT;
if (inner && this.stoppingHandoff) return;
const cause = (inner ? this.stopCause : undefined) ?? reason ?? STOPPED_BY_USER;
const stopping = cause === STOPPED_BY_USER ? this.live().filter(n => n.assignee.destination.threadId === threadId) : [];
const trees = stopping.map(n => ({ root: this.store.get(n.rootId), work: this.subtree(n).filter(a => !isTerminal(a)) }));
this.stopFor(cause, () => this.runtime.stopRequester({ threadId }, cause));
for (const { root, work } of trees) if (root) this.rememberStop(root, work);
}
stopHandoff(id: string): "stopped" | "ended" | undefined {
this.ready();
const n = this.store.get(id);
if (!n?.parentId) return undefined;
if (isTerminal(n)) return "ended";
const root = this.store.get(n.rootId);
const work = this.subtree(n).filter(a => !isTerminal(a));
const outer = this.stoppingHandoff;
this.stoppingHandoff = true;
try { this.stopFor(STOPPED_BY_USER, () => this.runtime.cancel(id, STOPPED_BY_USER, "stopped")); } finally { this.stoppingHandoff = outer; }
if (root) this.rememberStop(root, work, true);
return "stopped";
}
/** Runs a stop with its cause. A teammate's turn it ends stops that teammate's thread as well (the host's abort handler
* calls stopAwaitingDirect with no reason), and that is still this stop: a cut the system made (a waiting line going
* first, a restart, a deleted conversation) is never remembered as the person's stop. */
private stopFor(cause: string, stop: () => void): void {
const outer = this.stopCause;
this.stopCause = cause;
try { stop(); } finally { this.stopCause = outer; }
}
/** The person's stop, remembered (scoped to that request): the bots whose work on it the stop ended don't take the same
* request from another bot again, unless the person asked again after the stop. In memory only, for a day. A `scoped`
* stop holds for that one request's tree only, never for another request in the same words, and needs no person's words:
* a routine run's tree is held the same way. */
private rememberStop(root: Assignment, work: readonly Assignment[], scoped = false): void {
const request = requestKey(root);
const bots = new Set(work.filter(a => this.store.get(a.id)?.status === "cancelled").map(a => a.assignee.botId));
const at = this.now();
while (this.stops.length && at - this.stops[0]!.at > STOP_MEMORY_MS) this.stops.shift();
if (!bots.size) return;
if (scoped) this.stops.push({ at, request, bots, rootId: root.id });
else if (request) this.stops.push({ at, request, bots });
}
/** Work for `root`'s request was stopped for `botId`, and this request is not one the person made after that stop. */
private stoppedFor(root: Assignment, botId: string): boolean {
const request = requestKey(root);
return this.stops.some(stop => stop.bots.has(botId) && this.now() - stop.at <= STOP_MEMORY_MS
&& (stop.rootId !== undefined ? stop.rootId === root.id : request !== "" && stop.request === request && root.createdAt <= stop.at));
}
activeDirect(threadId: string): boolean {
this.ready();
return this.live().some(n => this.direct(n, threadId));
}
assignerOf(threadId: string): HandoffView | undefined {
this.ready();
for (const n of this.live()) {
if (!n.parentId || !this.direct(n, threadId)) continue;
const parent = this.store.get(n.parentId);
if (parent && !isTerminal(parent)) return this.project(parent);
}
return undefined;
}
outstandingDirect(threadId: string): HandoffView[] {
this.ready();
const out: HandoffView[] = [];
for (const n of this.live()) {
if (!n.parentId || n.reply === "none") continue;
const parent = this.store.get(n.parentId);
if (parent && !isTerminal(parent) && this.direct(parent, threadId)) out.push(view(n, parent));
}
return out;
}
awaitingTeammateThreads(): Set<string> {
this.ready();
const threads = new Set<string>();
for (const n of this.live()) {
const parent = n.parentId && n.reply !== "none" ? this.store.get(n.parentId) : undefined;
if (parent && !isTerminal(parent) && parent.assignee.destination.groupId === undefined) threads.add(parent.assignee.destination.threadId);
const root = view(n);
if (!root.parentId && !root.groupId && (root.status === "resume" || (root.status === "waiting" && root.question === undefined && !root.cards?.length))) {
threads.add(root.threadId);
}
}
return threads;
}
liveEdges(): LiveHandoffEdge[] {
this.ready();
return this.runtime.liveEdges().map(edge => ({
sourceBotId: edge.sourceBotId, targetBotId: edge.targetBotId, state: edge.state === "queued" ? "queued" : "running",
threadId: edge.threadId, ...(edge.groupId !== undefined ? { groupId: edge.groupId } : {}),
}));
}
continuesAfterRestart(threadId: string): boolean {
this.ready();
return this.live().some(n => n.assignee.destination.threadId === threadId && (
(n.status === "running" && (n.restart !== "rerun" || childrenSince(this.store, n).length > 0)) ||
((n.status === "queued" || n.status === "resume") && n.restart === "rerun")));
}
note(id: string): string | undefined {
this.ready();
const a = this.store.get(id);
if (!a) return undefined;
const parent = a.parentId ? this.store.get(a.parentId) : undefined;
return envelopeNote(composeEnvelope(a, this.host.names(this.project(a), parent && this.project(parent)), parent));
}
tick(): void {
this.ready();
this.pruneDaily();
this.runtime.tick();
}
pace(): "busy" | "parked" | "idle" {
this.ready();
return this.runtime.pace();
}
private pruneDaily(): void {
const now = this.now();
if (this.prunedAt !== undefined && now - this.prunedAt < PRUNE_EVERY_MS) return;
this.prunedAt = now;
try {
const removed = this.runtime.prune(now - PRUNE_AFTER_MS);
if (removed > 0) this.log(`pruned ${removed} assignment rows of trees that finished more than 30 days ago`);
} catch (error) {
this.log(`prune failed: ${String(error)}`);
}
}
close(): void {
this.runtime.close();
}
progress(threadId: string): void {
this.ready();
for (const n of this.live()) if (n.status === "running" && n.assignee.destination.threadId === threadId) this.runtime.progress(n.id);
}
held(threadId: string, why: string): void {
this.ready();
for (const n of this.live()) if (n.status === "running" && n.assignee.destination.threadId === threadId) this.runtime.held(n.id, why);
}
answer(threadId: string, text: string): boolean {
this.ready();
const parked = this.live().find(n => n.parentId !== undefined && n.status === "needs_input" && !(n.cards && n.cards.length > 0) &&
n.assignee.destination.threadId === threadId);
return parked ? this.runtime.answer(parked.id, text) : false;
}
awaitingAnswer(threadId: string): boolean {
this.ready();
return this.parkedIn(threadId) !== undefined;
}
private runner(): TurnRunner {
const host = this.host;
return {
validate: (a, parent) => host.validate(view(a, parent), parent && this.project(parent)),
canStart: a => {
const node = this.project(a);
return host.busy(node) ? host.holdReason?.(node) ?? false : true;
},
run: (a, input, signal) => this.run(a, input, signal),
park: (a, question, restored) => host.park(this.project(a), question, restored),
remind: (a, closesAt) => host.remind?.(this.project(a), closesAt),
report: (a, parent) => host.report(view(a, parent), parent && this.project(parent)),
changed: rows => {
const groups = new Set<string>();
const threads = new Set<string>();
for (const row of rows) {
const groupId = row.assignee.destination.groupId;
if (groupId) groups.add(groupId); else threads.add(row.assignee.destination.threadId);
}
host.changed(groups, threads);
},
names: (a, parent) => host.names(view(a, parent), parent && this.project(parent)),
outward: a => host.outward ? host.outward(this.project(a)) : [],
away: a => host.away ? host.away(this.project(a)) : false,
};
}
private async statusOnly(a: Assignment, parent: Assignment | undefined, turn: RunInput["turn"], result: HostTurnResult, signal: AbortSignal): Promise<boolean> {
if (turn !== "first" || !this.host.statusReply || !mayBeStatusOnly(a, parent, result.text, result.evidence)) return false;
try {
return a.requester.botId !== undefined && isStatusOnly(await this.host.statusReply(a.requester.botId, statusReplyPrompt(a.brief, result.text), signal));
} catch (error) {
this.log(`status reply check failed: ${String(error)}`);
return false;
}
}
private async run(a: Assignment, input: RunInput, signal: AbortSignal): Promise<RunResult> {
const first = input.turn === "first" || input.turn === "rerun" ? this.answeredElsewhere(a) : undefined;
if (first && input.turn === "first") this.host.joined?.(this.project(a), this.project(first));
const answer = first ? await this.joinAnswer(a, first.id, signal) : undefined;
if (answer) return answer;
const parent = a.parentId ? this.store.get(a.parentId) : undefined;
const node = view(a, parent);
const resumed = input.turn === "resume";
const settled = input.settled ?? [];
const asked = input.asked ?? [];
const root = a.parentId === undefined;
const body = resumed
? composeResume(a, this.host.names(node, parent && this.project(parent)),
settled.map(child => composeReport(this.readable(child, a, node), this.host.names(view(child, a), node))),
asked.map(child => composeQuestion(this.readable(child, a, node), this.host.names(view(child, a), node))),
settled.flatMap(child => child.status === "failed" && child.fault ? [{ fault: child.fault, who: this.host.names(view(child, a), node).assignee }] : []))
: root
? composeRootTurn(a, { turn: input.turn === "resume" ? "first" : input.turn, restartNote: "", ...(input.answer !== undefined ? { answer: input.answer } : {}),
...(input.continuation ? { continuation: input.continuation } : {}) })
: input.continuation ? `${continuationLine(input.continuation)}\n${input.envelope}` : input.envelope;
const note = resumed || root ? body : envelopeNote(body);
const evidence = (result: HostTurnResult) => result.evidence ? { evidence: result.evidence } : {};
const result = await this.host.run(node, resumed, signal,
{ text: `${input.restartNote}${body}`, note: `${input.restartNote}${note}`, restartNote: input.restartNote, turn: input.turn });
if (signal.aborted) return { kind: "failed", outcome: "stopped", text: result.text };
if (result.cap) return { kind: "continue", text: result.text, note: result.cap.note, ...(result.cap.handoffPath ? { handoffPath: result.cap.handoffPath } : {}), ...evidence(result) };
if (result.cards) return { kind: "needs_input", question: result.cards.question, cards: result.cards.ids, ...evidence(result) };
const question = root ? undefined : handoffQuestion(result);
if (!root && a.origin.kind === "person" && result.approvalAsk && !result.stalled && question === undefined) return { kind: "needs_input", question: result.approvalAsk, ...evidence(result) };
if (!result.ok) return { kind: "failed", outcome: result.stalled ? "stalled" : "provider_error", text: result.text, ...(result.failure ? { failure: result.failure } : {}), ...evidence(result) };
if (question === undefined) return { kind: "completed", text: result.text, ...(await this.statusOnly(a, parent, input.turn, result, signal) ? { statusOnly: true } : {}), ...evidence(result) };
const named = withDefault(question);
const decide = requesterDecides(a) && !result.privateQuestion && !personOnly(named.question) ? { decide: named.default ? { default: named.default } : {} } : {};
return { kind: "needs_input", question, ...decide, ...evidence(result) };
}
private live(): Assignment[] {
return this.store.all({ nonTerminal: true });
}
/** The same request to the same bot from another requester (same words, mode, approval level and finish line), asked
* earlier and still being answered when this one was asked, whose answer this one's requester may read
* (host.shareAnswer): two teammates asking the same thing at the same time get one answer. An answer from before this
* request was asked is never reused, as things may have changed since. Rooms keep their own turn order, and a request
* still to be answered in this one's conversation could only go on after it: neither is joined. */
private answeredElsewhere(a: Assignment): Assignment | undefined {
const share = this.host.shareAnswer;
if (!share || !a.parentId || a.mode === "notify" || a.rework || a.assignee.destination.groupId !== undefined) return undefined;
const mine = this.project(a);
// In the order they were asked, each still open when this one was asked.
const rows = this.store.all({ openSince: a.createdAt });
const at = rows.findIndex(o => o.id === a.id);
return rows.slice(0, Math.max(at, 0))
.filter(o => o.parentId !== undefined && o.parentId !== a.parentId && !o.rework && o.mode === a.mode
&& o.level === a.level && o.doneWhen === a.doneWhen
&& o.assignee.botId === a.assignee.botId && o.assignee.destination.groupId === undefined
&& (o.status === "completed" || (!isTerminal(o) && o.assignee.destination.threadId !== a.assignee.destination.threadId))
&& sameRequest(o.brief, a.brief))
.find(o => share(this.project(o), mine));
}
/** Waits for the request `firstId` to be answered, keeping this one's turn out of the stall window, and ends with that
* answer. Undefined when it ends without one: this request is then worked on as usual. */
private async joinAnswer(a: Assignment, firstId: string, signal: AbortSignal): Promise<RunResult | undefined> {
this.log(`${a.id} joins ${firstId}: the same request to ${a.assignee.botId}`);
// One listener for the whole wait, however long the first takes.
const stopped = new Promise<void>(resolve => signal.addEventListener("abort", () => resolve(), { once: true }));
for (;;) {
if (signal.aborted) return { kind: "failed", outcome: "stopped", text: "" };
const first = this.store.get(firstId);
if (first?.status === "completed") return { kind: "completed", text: `${JOINED_NOTE}\n${first.result.replace(`${JOINED_NOTE}\n`, "")}` };
if (!first || isTerminal(first)) return undefined;
this.runtime.progress(a.id);
await Promise.race([stopped, new Promise<void>(resolve => setTimeout(resolve, JOIN_POLL_MS))]);
}
}
/** Direct work `asker` handed to `bot` and still waits on: an open request whose requesting turn is still open, held in the
* conversation `bot` asks from or waiting in the one the new request goes to. A request held here wins over one waiting there. */
private waitingOn(bot: RoomAddress, asker: RoomAddress): { request: Assignment; parent: Assignment; here: boolean } | undefined {
let there: { request: Assignment; parent: Assignment; here: boolean } | undefined;
for (const request of this.live()) {
if (request.assignee.botId !== bot.botId || request.requester.botId !== asker.botId || request.reply === "none" || request.assignee.destination.groupId !== undefined) continue;
const here = request.assignee.destination.threadId === bot.threadId;
if (!here && request.requester.threadId !== asker.threadId) continue;
const parent = request.parentId ? this.store.get(request.parentId) : undefined;
if (!parent || isTerminal(parent)) continue;
if (here) return { request, parent, here };
there ??= { request, parent, here };
}
return there;
}
private parkedIn(threadId: string): Assignment | undefined {
return this.live().find(n => n.status === "needs_input" && n.assignee.destination.threadId === threadId);
}
private direct(a: Assignment, threadId: string): boolean {
return a.assignee.destination.groupId === undefined && a.assignee.destination.threadId === threadId;
}
/** A route or membership that no longer admits the child withholds its words; only the reason travels. */
private readable(child: Assignment, parent: Assignment, parentView: HandoffView): Assignment {
const problem = this.host.validate(view(child, parent), parentView);
if (!problem) return child;
const { evidence: _evidence, question: _question, ...rest } = child;
return { ...rest, result: `${child.question === undefined ? "Result" : "Question"} withheld: ${problem}` };
}
private project(a: Assignment): HandoffView {
return view(a, a.parentId ? this.store.get(a.parentId) : undefined);
}
}