Skip to content

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

Hand-offs: the budget refusal says what renews it; a fan-out counts once

Milind Sonic6e5b38277c2
diff --git a/docs/runtime-contract.md b/docs/runtime-contract.md
index c2ae842fef..f68491a482 100644
--- a/docs/runtime-contract.md
+++ b/docs/runtime-contract.md
@@ -86,7 +86,7 @@ What a cut turn did outward is the host's knowledge, read through the optional p
## 6. Budgets and clocks
-Three budgets per root, counted since the root's last durable progress (a settlement, a completed turn): `requests`, `executions`, `wakes`. Progress renews them; nothing else does. The owed follow-up turn of a node whose children all settled is never refused for budget.
+Three budgets per root, counted since the root's last durable progress (a settlement, a completed turn): `requests`, `executions`, `wakes`. Progress renews them; nothing else does. One call that reaches several teammates (`fanOut`) counts as one request. The owed follow-up turn of a node whose children all settled is never refused for budget.
Three clocks and no others: a queue bound (`queueMs`, expired means `failed(expired)`, "never started"); a per-root stall window on durable progress (`stallMs`, fails the tree); a per-turn activity window (`turnStallMs`, on the monotonic clock, so a laptop sleep is not a stall; a tool visibly in flight counts as activity through `progress()`). Time spent parked on the person is charged to no window. A wait on the person's words is bounded by `inputWaitMs`, which is infinite unless a host sets it: a question waits for the person however long they take. Where a host sets it, expiry is `failed(expired)`: not run, not refused, never reported as approved.
diff --git a/server/coordinator.ts b/server/coordinator.ts
index 9070b79f0f..0418b8a821 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -107,6 +107,8 @@ export interface HandoffOptions {
approvalGranted?: boolean;
rework?: boolean;
requestBatchKey?: string;
+ /** One call handing the same work to several teammates: it counts once against the request budget. */
+ fanOut?: string;
doneWhen?: string;
/** The target is a new thread of the requester's own bot (start_thread with report_back). */
ownThread?: boolean;
diff --git a/server/index.ts b/server/index.ts
index 2aee79bbd3..a228ef97c4 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -13771,7 +13771,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
{ approvals: blocked });
approvalGranted = true;
}
- const requestBatchKey = destination ? randomUUID() : undefined, handOnFor = CLOUD_TEAM ? teamConnections.handOnFor(internalCapability.threadId, internalCapability.generation) : null;
+ const requestBatchKey = destination ? randomUUID() : undefined, fanOut = targets.length > 1 ? randomUUID() : undefined, handOnFor = CLOUD_TEAM ? teamConnections.handOnFor(internalCapability.threadId, internalCapability.generation) : null;
const generation = EXTERNAL ? randomUUID() : internalCapability.generation;
if (EXTERNAL) {
const opener = handoffOpener(internalCapability, address.threadId);
@@ -13820,7 +13820,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const routed = lane ? { botId: target.botId, threadId: lane.threadId } : target;
outsideLineage.carry(address.threadId, routed.threadId);
const { node, duplicate } = coordinator.enqueue(address, generation, internalCapability.roomHandoffId, routed, call.message, {
- mode, reply, thread: lane || fresh ? "new" : "standing", approvalGranted, rework: call.rework, ...(lane ? {} : { requestBatchKey }), ...(call.ownThread ? { ownThread: true } : {}),
+ mode, reply, thread: lane || fresh ? "new" : "standing", approvalGranted, rework: call.rework, ...(lane ? {} : { requestBatchKey }), ...(fanOut ? { fanOut } : {}), ...(call.ownThread ? { ownThread: true } : {}),
...(call.doneWhen ? { doneWhen: call.doneWhen } : {}),
});
usageTrace.link(node.id, node.parentId, { threadId: internalCapability.threadId, turnId: liveTurnByThread.get(internalCapability.threadId) ?? "" }); if (!duplicate) actingPeople.handOn(internalCapability, node);
diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.ts
index ecbacaa1af..f77be3c038 100644
--- a/server/runtime-coordinator.test.ts
+++ b/server/runtime-coordinator.test.ts
@@ -91,10 +91,10 @@ const begun = (w: World, source: RoomAddress, generation: string, sourceText = "
};
const send = (w: World, source: RoomAddress, generation: string, parentId: string | undefined, target: RoomAddress, text: string,
- opts: { approved?: boolean; rework?: boolean; batchKey?: string; sourceText?: string } = {}) => {
+ opts: { approved?: boolean; rework?: boolean; batchKey?: string; fanOut?: string; sourceText?: string } = {}) => {
if (!parentId) begun(w, source, generation, opts.sourceText);
return w.coordinator.enqueue(source, generation, parentId, target, text, { approvalGranted: opts.approved ?? false, rework: opts.rework ?? false,
- requestBatchKey: opts.batchKey });
+ requestBatchKey: opts.batchKey, ...(opts.fanOut ? { fanOut: opts.fanOut } : {}) });
};
const ended = (w: World, generation: string, ok = true) =>
@@ -453,7 +453,15 @@ describe("RuntimeCoordinator: refusals in the legacy words", () => {
await deep.host.release(node.id, { ok: true, text: "done" });
const tight = world(undefined, { requests: 1 });
send(tight, chief, "gen-1", undefined, builder, "Build it");
- expect(() => send(tight, chief, "gen-1", undefined, tester, "Test it")).toThrow("Room handoff budget exhausted");
+ expect(() => send(tight, chief, "gen-1", undefined, tester, "Test it")).toThrow(/limit of 1 hand-offs.*nobody can reset it, the person included/s);
+ });
+
+ it("counts one call to several teammates as one request against the budget", () => {
+ const w = world(undefined, { requests: 1 });
+ const { node: first } = send(w, chief, "gen-1", undefined, builder, "Review it", { fanOut: "call-1" });
+ const { node: second } = send(w, chief, "gen-1", undefined, tester, "Review it", { fanOut: "call-1" });
+ expect([first.status, second.status]).toEqual(["queued", "queued"]);
+ expect(() => send(w, chief, "gen-1", undefined, { botId: "scout", threadId: "scout-work" }, "Review it", { fanOut: "call-2" })).toThrow(/limit of 1 hand-offs/);
});
it("lets one Chief turn brief a room of 25 visitors and starts every one of them", async () => {
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index 013038cc82..7bb11547d2 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -18,7 +18,7 @@ const ANCESTOR = "Cannot assign work back to an ancestor; results return automat
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 BUDGET = "Room handoff budget exhausted";
+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)";
/** A stop with no other cause is the person's own. */
const STOPPED_BY_USER = "Stopped by user";
@@ -228,7 +228,7 @@ export class RuntimeCoordinator implements Coordinator {
enqueue(source: RoomAddress, generation: string, parentId: string | undefined, target: RoomAddress, text: string,
options: HandoffOptions = {}): { node: HandoffView; duplicate: boolean } {
this.ready();
- const { approvalGranted = false, rework = false, requestBatchKey, thread } = options;
+ const { approvalGranted = false, 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);
@@ -271,9 +271,10 @@ export class RuntimeCoordinator implements Coordinator {
...(level.driverKind !== undefined ? { driverKind: level.driverKind } : {}),
approved: approvalGranted,
...(target.groupId && requestBatchKey ? { batchKey: requestBatchKey } : {}),
+ ...(fanOut ? { fanOut } : {}),
});
if (!result.ok) {
- if (result.outcome === "budget") throw new Error(BUDGET);
+ if (result.outcome === "budget") throw new Error(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 };
diff --git a/server/runtime/runtime.test.ts b/server/runtime/runtime.test.ts
index d5bce94a7f..c393973653 100644
--- a/server/runtime/runtime.test.ts
+++ b/server/runtime/runtime.test.ts
@@ -397,6 +397,17 @@ describe("Runtime: one tree, one lane", () => {
store.close();
});
+ it("charges the request budget once per fan-out, and still refuses the next call", () => {
+ const w = world(() => "hold", { requests: 1 });
+ const root = w.runtime.begin(beginReq());
+ ok(w.runtime.enqueue({ ...toBot("builder", root.id), fanOut: "call-1" }));
+ ok(w.runtime.enqueue({ ...toBot("tester", root.id), fanOut: "call-1" }));
+ expect(w.store.get(root.id)?.budgets?.requests).toBe(1);
+ expect(w.store.children(root.id).map(c => c.fanOut)).toEqual(["call-1", "call-1"]);
+ expect(w.runtime.enqueue({ ...toBot("scout", root.id), fanOut: "call-2" })).toMatchObject({ ok: false, outcome: "budget" });
+ expect(w.runtime.enqueue(toBot("scout", root.id))).toMatchObject({ ok: false, outcome: "budget" });
+ });
+
it("cancels down the tree, aborts running turns and reports each stop", async () => {
const w = world(() => "hold");
const root = w.runtime.begin(beginReq());
diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.ts
index dff670d019..36783380de 100644
--- a/server/runtime/runtime.ts
+++ b/server/runtime/runtime.ts
@@ -192,17 +192,20 @@ export class Runtime {
const lineage = parent ? path(this.store, parent) : [];
const root = lineage[0];
const target = req.assignee;
+ let sameCall = false;
const ancestors = ownThread(lineage, target, req.ownThread) ? lineage.slice(0, -1) : lineage;
if (!answersSender(parent, mode, { botId: target.botId, ...target.destination }) && ancestors.some(a => a.assignee.botId === target.botId &&
(!a.assignee.destination.groupId || !target.destination.groupId || a.assignee.destination.groupId === target.destination.groupId))) {
return refuse("Cannot assign work back to an ancestor; results return automatically");
}
if (parent) {
- const existing = this.store.children(parent.id).findLast(c => c.brief === brief && c.mode === mode && c.assignee.botId === target.botId &&
+ const siblings = this.store.children(parent.id);
+ const existing = siblings.findLast(c => c.brief === brief && c.mode === mode && c.assignee.botId === target.botId &&
c.assignee.destination.threadId === target.destination.threadId && c.assignee.destination.groupId === target.destination.groupId);
if (existing && !(req.rework && isTerminal(existing))) return { ok: true, assignment: existing, duplicate: true };
if (parent.depth + 1 > this.limits.depth) return refuse(`Assignment depth limit reached (${this.limits.depth})`);
- if (root?.budgets && root.budgets.requests + 1 > this.limits.requests) {
+ sameCall = req.fanOut !== undefined && siblings.some(c => c.fanOut === req.fanOut);
+ if (!sameCall && root?.budgets && root.budgets.requests + 1 > this.limits.requests) {
this.store.update(root, { kind: "budget", at: now, detail: `requests: ${root.budgets.requests} since last progress` });
return refuse(`Request budget exhausted: ${this.limits.requests} requests without progress`, "budget");
}
@@ -216,7 +219,7 @@ export class Runtime {
reply: req.reply ?? (mode === "notify" ? "none" : "resume"), brief, ...(req.doneWhen ? { doneWhen: req.doneWhen } : {}),
status: "queued", level, levelSource: source, executions: 0, restarts: 0, createdAt: now, lastActivityAt: now, result: "",
rework: Boolean(req.rework), ...(req.approved !== undefined ? { approved: req.approved } : {}),
- ...(req.batchKey !== undefined ? { batchKey: req.batchKey } : {}), version: 1,
+ ...(req.batchKey !== undefined ? { batchKey: req.batchKey } : {}), ...(req.fanOut !== undefined ? { fanOut: req.fanOut } : {}), version: 1,
};
if (!parent) { node.rootId = node.id; node.budgets = { since: now, requests: 0, executions: 0, wakes: 0 }; }
const problem = this.safe("validate", () => this.runner.validate(node, parent));
@@ -224,7 +227,7 @@ export class Runtime {
if (problem) return refuse(problem);
this.store.transaction(() => {
this.store.insert(node, { kind: "enqueued", at: now, detail: "queued" });
- if (root?.budgets) { root.budgets.requests += 1; this.store.update(root); }
+ if (root?.budgets && !sameCall) { root.budgets.requests += 1; this.store.update(root); }
});
this.touch(node, ...root ? [root] : []);
return { ok: true, assignment: node, duplicate: false };
diff --git a/server/runtime/store.ts b/server/runtime/store.ts
index f73676e80c..f2b132f31e 100644
--- a/server/runtime/store.ts
+++ b/server/runtime/store.ts
@@ -79,6 +79,7 @@ const assignmentSchema = z.object({
carrying: z.array(z.string()).optional(),
approved: z.boolean().optional(),
batchKey: z.string().optional(),
+ fanOut: z.string().optional(),
version: z.literal(1),
});
diff --git a/server/runtime/types.ts b/server/runtime/types.ts
index fa1e8925cd..6e7009bca6 100644
--- a/server/runtime/types.ts
+++ b/server/runtime/types.ts
@@ -152,6 +152,8 @@ export interface Assignment {
approved?: boolean;
/** A room brief shown once per call: every recipient of that call shares it. */
batchKey?: string;
+ /** The call that handed this out, when one call reached several teammates. */
+ fanOut?: string;
version: 1;
}
@@ -217,6 +219,8 @@ export interface EnqueueRequest {
driverKind?: string;
approved?: boolean;
batchKey?: string;
+ /** One call that hands the same work to several teammates: it counts once against the request budget. */
+ fanOut?: string;
/** A new thread of the requester's own bot (tree.ts ownThread): the requesting turn is not an ancestor it refuses. */
ownThread?: boolean;
}