Skip to content

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

fix(agents): say a report cut before the runtime lost its end, and read a kept result one part at a time

luishron123c9625dbd8ba3
diff --git a/server/coordinator.ts b/server/coordinator.ts
index 2921aadd47..70413d32f2 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -94,6 +94,8 @@ export interface BeginTurnRequest {
export interface HostTurnResult {
ok: boolean;
text: string;
+ /** The reply's own length when `text` is a cut of it (handoffReply): the kept result reports its end as lost. */
+ chars?: number;
question?: string | null;
evidence?: TurnEvidence;
cap?: { note: string; handoffPath?: string };
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index fc98febedb..4bdc39c40a 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -95,9 +95,15 @@ export function needsInputQuestion(text: string): string | undefined {
}
/** The turn's reply whole, up to what the store keeps beside a record: the runtime keeps the record's head and the rest
- * beside it, so a long report is never cut here. */
-export function handoffReply(text: string): Pick<HostTurnResult, "text" | "question"> {
- return { text: text.slice(0, RESULT_KEPT_MAX), question: needsInputQuestion(text) ?? null };
+ * beside it. A longer reply is cut here and carries its own length (`chars`), so the reader says its end was lost. */
+export function handoffReply(text: string): Pick<HostTurnResult, "text" | "question" | "chars"> {
+ const question = needsInputQuestion(text) ?? null;
+ return text.length > RESULT_KEPT_MAX ? { text: text.slice(0, RESULT_KEPT_MAX), chars: text.length, question } : { text, question };
+}
+
+/** A reply's own length when its text is a cut of it. */
+function cutAt(result: Pick<HostTurnResult, "text" | "chars">): { chars?: number } {
+ return result.chars !== undefined && result.chars > result.text.length ? { chars: result.chars } : {};
}
export function handoffQuestion(result: Pick<HostTurnResult, "text" | "question">): string | undefined {
@@ -725,13 +731,13 @@ export class RuntimeCoordinator implements Coordinator {
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 (signal.aborted) return { kind: "failed", outcome: "stopped", text: result.text, ...cutAt(result) };
+ if (result.cap) return { kind: "continue", text: result.text, ...cutAt(result), 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) };
+ if (!result.ok) return { kind: "failed", outcome: result.stalled ? "stalled" : "provider_error", text: result.text, ...cutAt(result), ...(result.failure ? { failure: result.failure } : {}), ...evidence(result) };
+ if (question === undefined) return { kind: "completed", text: result.text, ...cutAt(result), ...(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) };
diff --git a/server/runtime/runtime.test.ts b/server/runtime/runtime.test.ts
index 2b60cc283b..c391909f4a 100644
--- a/server/runtime/runtime.test.ts
+++ b/server/runtime/runtime.test.ts
@@ -6,6 +6,9 @@ import { PROGRESS_WRITE_MS, RERUN_BURST, RERUN_GAP_MS, RERUN_HELD, RERUN_SUPERSE
import { openRuntimeStore, type RuntimeStore } from "./store.ts";
import { CUT_TWICE, INTERRUPTED_OUTWARD, loopStop, nextGuard, outwardDetail } from "./tree.ts";
import type { Assignment, Clock, EnqueueRequest, Limits, RunInput, RunResult, TurnRunner } from "./types.ts";
+import { assignmentResultPart } from "../assignment-read.ts";
+import { resultPartLines } from "../drivers/agents-assignment-result.ts";
+import { handoffReply } from "../runtime-coordinator.ts";
const flush = () => new Promise<void>(resolve => setImmediate(resolve));
@@ -810,6 +813,23 @@ describe("access rechecked while work runs", () => {
invariants(w);
});
+ it("says a report cut before it reached the runtime lost its end: a 2,000,003-character reply reads as truncated", async () => {
+ const w = world(() => "hold");
+ const root = w.runtime.begin(beginReq());
+ const child = ok(w.runtime.enqueue(toBot("builder", root.id)));
+ w.runtime.tick();
+ const reply = handoffReply(`${"r".repeat(2_000_000)}US$`);
+ expect(reply).toMatchObject({ chars: 2_000_003 });
+ expect(reply.text).toHaveLength(2_000_000);
+ await w.runner.release(child.id, { kind: "completed", text: reply.text, chars: reply.chars });
+ const row = w.store.get(child.id)!;
+ expect(row.resultChars).toBe(2_000_003);
+ const last = assignmentResultPart(row, String(2_000_000), (...args) => w.store.resultPart(...args)).resultPart!;
+ expect(last).toMatchObject({ offset: 2_000_000, end: 2_000_000, total: 2_000_003, text: "", truncated: true });
+ expect(resultPartLines(last, child.id).join("\n")).toMatch(/\[truncated: only the first 2000000 of 2000003 characters.*Tell the person the end of the report is missing/);
+ invariants(w);
+ });
+
it("drops a kept long result once the record's own result is short again", async () => {
const w = world(() => "hold");
const root = w.runtime.begin(beginReq());
diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.ts
index 850db90d62..a27e872356 100644
--- a/server/runtime/runtime.ts
+++ b/server/runtime/runtime.ts
@@ -581,7 +581,7 @@ export class Runtime {
const root = n.parentId ? this.store.get(n.rootId) : n;
if (result.kind === "continue") {
// The count comes from events because dispatch deletes n.continuation.
- this.keepResult(n, result.text);
+ this.keepResult(n, result.text, result.chars);
n.guard = nextGuard(n.guard, result.evidence);
const stop = loopStop(n.guard, result.text);
if (stop) {
@@ -614,7 +614,7 @@ export class Runtime {
}
return;
}
- this.keepResult(n, result.text);
+ this.keepResult(n, result.text, result.chars);
if (result.kind === "completed" && result.statusOnly) n.statusOnly = true;
const kids = awaited(this.store.children(n.id));
const unseen = live !== undefined && kids.some(c => isTerminal(c) && !live.carried.has(c.id));
@@ -948,15 +948,17 @@ export class Runtime {
/** The record holds a result's head; a longer one is kept whole beside it, so its end is never lost. A failed keep
* leaves resultChars set with nothing beside it, which the reader reports as cut, never as the whole text. */
- private keepResult(n: Assignment, said: string): void {
- const long = said.length > RESULT_MAX;
- // Masked before the cut, as an answer is, so a secret is never kept half shown at the record's edge.
- const text = long ? redactSecretsInText(said) : said;
+ private keepResult(n: Assignment, said: string, saidChars?: number): void {
+ // A long result is masked before the cut, as an answer is, so a secret is never kept half shown at the record's edge.
+ const text = said.length > RESULT_MAX || (saidChars ?? 0) > said.length ? redactSecretsInText(said) : said;
+ // saidChars: the reply was already cut before it got here (handoffReply); the reader must still say its end is lost.
+ const whole = Math.max(text.length, saidChars !== undefined && saidChars > said.length ? text.length + saidChars - said.length : 0);
+ const long = whole > RESULT_MAX;
n.result = clip(text, RESULT_MAX);
if (!long && n.resultChars === undefined) return;
- if (long) n.resultChars = text.length; else delete n.resultChars;
+ if (long) n.resultChars = whole; else delete n.resultChars;
try {
- this.store.keepResult(n.id, long ? text : undefined);
+ this.store.keepResult(n.id, long ? text : undefined, whole);
} catch (error) {
this.log(`keep result threw: ${String(error)}`);
}
diff --git a/server/runtime/store.test.ts b/server/runtime/store.test.ts
index 943efdb6f5..eae1fc0c84 100644
--- a/server/runtime/store.test.ts
+++ b/server/runtime/store.test.ts
@@ -1,8 +1,8 @@
import { mkdtempSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { DatabaseSync } from "node:sqlite";
-import { afterEach, describe, expect, it } from "vitest";
+import { DatabaseSync, StatementSync } from "node:sqlite";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { openRuntimeStore, RESULT_KEPT_MAX, type RuntimeStore } from "./store.ts";
import { removeTempDir } from "../testing/cleanup.ts";
@@ -285,6 +285,33 @@ describe("runtime store: a result kept beside its record", () => {
expect(store.resultPart("root", 0, 10)).toBeUndefined();
store.keepResult("root", "z".repeat(RESULT_KEPT_MAX + 5));
expect(store.resultPart("root", RESULT_KEPT_MAX, 10)).toEqual({ text: "", total: RESULT_KEPT_MAX + 5, kept: RESULT_KEPT_MAX });
+ // A text already cut upstream (handoffReply) carries its own length: what was kept is all there is, the total says more.
+ store.keepResult("root", "c".repeat(30_000), 2_000_003);
+ expect(store.resultPart("root", 30_000, 16_000)).toEqual({ text: "", total: 2_000_003, kept: 30_000 });
+ });
+
+ it("reads a page from only the stored parts it covers, in JavaScript's own character offsets", () => {
+ const store = open();
+ store.insert(assignment("root"), { kind: "enqueued", at: 1_000 });
+ // Astral characters count two in JavaScript and one in SQLite: the offsets the record's head gives must still line up.
+ const whole = `${"🙂a".repeat(70_000)}Total: 1,240.00 US$`;
+ store.keepResult("root", whole);
+ const all = vi.spyOn(StatementSync.prototype, "all");
+ let read = "";
+ for (;;) {
+ const part = store.resultPart("root", read.length, 16_000)!;
+ if (!part.text) break;
+ read += part.text;
+ }
+ expect(read).toBe(whole);
+ expect(store.resultPart("root", 15_990, 20)).toMatchObject({ text: whole.slice(15_990, 16_010) });
+ const pages = all.mock.results.map(r => r.value as Array<{ text: string }>);
+ all.mockRestore();
+ expect(pages.length).toBeGreaterThan(5);
+ for (const rows of pages) {
+ expect(rows.length).toBeLessThanOrEqual(2);
+ expect(rows.reduce((sum, row) => sum + row.text.length, 0)).toBeLessThanOrEqual(32_000);
+ }
});
it("prunes it with its tree, and any an older build's prune left behind", () => {
diff --git a/server/runtime/store.ts b/server/runtime/store.ts
index 558db729fb..0d3cc51f64 100644
--- a/server/runtime/store.ts
+++ b/server/runtime/store.ts
@@ -105,8 +105,9 @@ export interface RuntimeStore {
addInbox(item: InboxItem): void;
inbox(owner: Owner, undeliveredOnly?: boolean): InboxItem[];
markDelivered(ids: string[], at: number): void;
- /** A result longer than the record holds, kept whole beside it (up to RESULT_KEPT_MAX); undefined drops it. */
- keepResult(assignmentId: string, text: string | undefined): void;
+ /** A result longer than the record holds, kept beside it (up to RESULT_KEPT_MAX); undefined drops it. `total` is the
+ * result's own length when `text` is already a cut of it, so the reader still says the end was not kept. */
+ keepResult(assignmentId: string, text: string | undefined, total?: number): void;
/** Part of a kept result: `total` is the result's own length, `kept` how much of it was stored. */
resultPart(assignmentId: string, offset: number, limit: number): { text: string; total: number; kept: number } | undefined;
prune(before: number): number;
@@ -164,16 +165,32 @@ const SCHEMA = `
CREATE INDEX IF NOT EXISTS inbox_thread ON inbox(owner_thread_id, delivered_at);
CREATE INDEX IF NOT EXISTS inbox_run ON inbox(owner_run_id, delivered_at);
CREATE INDEX IF NOT EXISTS inbox_assignment ON inbox(assignment_id);
- -- A result past the record's own 12 000 characters, whole. An older build never reads it and keeps the record's head.
- CREATE TABLE IF NOT EXISTS assignment_results (
- assignment_id TEXT PRIMARY KEY,
+ -- A result past the record's own 12 000 characters, whole, in parts of RESULT_CHUNK so a page reads only the parts it
+ -- covers. An older build never reads it and keeps the record's head.
+ CREATE TABLE IF NOT EXISTS assignment_result_parts (
+ assignment_id TEXT NOT NULL,
+ seq INTEGER NOT NULL,
+ start INTEGER NOT NULL,
+ size INTEGER NOT NULL,
total INTEGER NOT NULL,
- text TEXT NOT NULL
+ kept INTEGER NOT NULL,
+ text TEXT NOT NULL,
+ PRIMARY KEY (assignment_id, seq)
);
`;
+/** At most `max` units of `text`, never ending on the first half of a surrogate pair. */
+function wholeCharacters(text: string, max: number): string {
+ const cut = text.slice(0, max);
+ const last = cut.charCodeAt(cut.length - 1);
+ return cut.length === max && text.length > max && last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;
+}
+
/** The most of one result kept beside its record; past it the reader is told the rest was not kept. */
export const RESULT_KEPT_MAX = 2_000_000;
+/** The most of one stored part of a kept result. Offsets are UTF-16 units as JavaScript counts them, so they match the
+ * record's head; a part never ends inside a surrogate pair, which SQLite would store as a replacement character. */
+const RESULT_CHUNK = 16_000;
type Row = Record<string, unknown>;
@@ -269,13 +286,14 @@ export function openRuntimeStore(path: string): RuntimeStore {
AND NOT EXISTS (SELECT 1 FROM assignments c WHERE c.root_id = r.id AND c.status NOT IN (${terminalList}))`),
pruneEvents: db.prepare("DELETE FROM assignment_events WHERE assignment_id IN (SELECT id FROM assignments WHERE root_id = ?)"),
pruneInbox: db.prepare("DELETE FROM inbox WHERE assignment_id IN (SELECT id FROM assignments WHERE root_id = ?)"),
- pruneResults: db.prepare("DELETE FROM assignment_results WHERE assignment_id IN (SELECT id FROM assignments WHERE root_id = ?)"),
+ pruneResults: db.prepare("DELETE FROM assignment_result_parts WHERE assignment_id IN (SELECT id FROM assignments WHERE root_id = ?)"),
pruneRows: db.prepare("DELETE FROM assignments WHERE root_id = ?"),
// Rows an older build's prune left behind once their record was gone.
- pruneOrphanResults: db.prepare("DELETE FROM assignment_results WHERE assignment_id NOT IN (SELECT id FROM assignments)"),
- keepResult: db.prepare("INSERT OR REPLACE INTO assignment_results (assignment_id, total, text) VALUES (?, ?, ?)"),
- dropResult: db.prepare("DELETE FROM assignment_results WHERE assignment_id = ?"),
- result: db.prepare("SELECT total, text FROM assignment_results WHERE assignment_id = ?"),
+ pruneOrphanResults: db.prepare("DELETE FROM assignment_result_parts WHERE assignment_id NOT IN (SELECT id FROM assignments)"),
+ keepResultPart: db.prepare("INSERT INTO assignment_result_parts (assignment_id, seq, start, size, total, kept, text) VALUES (?, ?, ?, ?, ?, ?, ?)"),
+ dropResult: db.prepare("DELETE FROM assignment_result_parts WHERE assignment_id = ?"),
+ resultSize: db.prepare("SELECT total, kept FROM assignment_result_parts WHERE assignment_id = ? AND seq = 0"),
+ resultParts: db.prepare("SELECT start, text FROM assignment_result_parts WHERE assignment_id = ? AND start < ? AND start + size > ? ORDER BY seq"),
};
let depth = 0;
@@ -399,15 +417,29 @@ export function openRuntimeStore(path: string): RuntimeStore {
return removed;
});
},
- keepResult(assignmentId, text) {
- if (text === undefined) statements.dropResult.run(assignmentId);
- else statements.keepResult.run(assignmentId, text.length, text.slice(0, RESULT_KEPT_MAX));
+ keepResult(assignmentId, text, total) {
+ transaction(() => {
+ statements.dropResult.run(assignmentId);
+ if (text === undefined) return;
+ const kept = wholeCharacters(text, RESULT_KEPT_MAX);
+ const whole = Math.max(total ?? 0, text.length);
+ for (let seq = 0, at = 0; seq === 0 || at < kept.length; seq += 1) {
+ const part = wholeCharacters(kept.slice(at), RESULT_CHUNK);
+ statements.keepResultPart.run(assignmentId, seq, at, part.length, whole, kept.length, part);
+ at += part.length;
+ }
+ });
},
resultPart(assignmentId, offset, limit) {
- const row = statements.result.get(assignmentId) as Row | undefined;
- if (!row) return undefined;
- const text = String(row.text);
- return { text: text.slice(offset, offset + limit), total: Number(row.total), kept: text.length };
+ const size = statements.resultSize.get(assignmentId) as Row | undefined;
+ if (!size) return undefined;
+ const kept = Number(size.kept), total = Number(size.total);
+ const start = Math.min(Math.max(0, offset), kept), end = Math.min(kept, start + Math.max(0, limit));
+ if (end <= start) return { text: "", total, kept };
+ const parts = statements.resultParts.all(assignmentId, end, start) as Row[];
+ const from = parts.length ? Number(parts[0]!.start) : start;
+ const text = parts.map(row => String(row.text)).join("").slice(start - from, end - from);
+ return { text, total, kept };
},
close() {
db.close();
diff --git a/server/runtime/types.ts b/server/runtime/types.ts
index fe67070bc3..8b202f919d 100644
--- a/server/runtime/types.ts
+++ b/server/runtime/types.ts
@@ -263,15 +263,16 @@ export interface RunInput {
mode: Mode;
}
+/** `chars` on a result: the reply's own length when `text` is already a cut of it (handoffReply), so the end is reported lost.
+ * statusOnly: nothing in `text` for the requester to do (status-reply.ts). */
export type RunResult =
- /** statusOnly: nothing in `text` for the requester to do (status-reply.ts). */
- | { kind: "completed"; text: string; evidence?: TurnEvidence; statusOnly?: boolean }
+ | { kind: "completed"; text: string; chars?: number; evidence?: TurnEvidence; statusOnly?: boolean }
/** failure: the system's own words for why the turn failed and the engine's stop reason, apart from anything the bot said. */
- | { kind: "failed"; outcome: Exclude<Outcome, "done" | "needs_input">; text: string; evidence?: TurnEvidence; failure?: { text: string; stopReason?: string | null } }
+ | { kind: "failed"; outcome: Exclude<Outcome, "done" | "needs_input">; text: string; chars?: number; evidence?: TurnEvidence; failure?: { text: string; stopReason?: string | null } }
| { kind: "needs_input"; question: string; cards?: string[]; decide?: { default?: string }; evidence?: TurnEvidence }
/** The turn stopped short (a step cap, a seat it could not get) and the
* same node continues in place with its next execution. */
- | { kind: "continue"; text: string; note: string; handoffPath?: string; evidence?: TurnEvidence };
+ | { kind: "continue"; text: string; chars?: number; note: string; handoffPath?: string; evidence?: TurnEvidence };
/** How a host-run root turn ended (Runtime.end). */
export interface EndResult {