Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Files travel with hand-offs between this computer and My Cloud, both ways (early, behind the same switch) (#6097)
Milind Soniacecd9bced97
diff --git a/server/bot-link.e2e.test.ts b/server/bot-link.e2e.test.tsindex ff389ad9c8..8b0d180573 100644--- a/server/bot-link.e2e.test.ts+++ b/server/bot-link.e2e.test.ts@@ -1,6 +1,6 @@// Two real servers on this machine: one stands in for the person's computer, the other for a server that is theirs alone// (as My Cloud is). Only each provider's planning is scripted. Nothing outside this machine is asked.-import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";import { expect, it } from "vitest";import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";@@ -82,6 +82,26 @@ it("a bot on the computer and a bot on the person's own server hand each other wexpect(worked.some((message) => /Count this week's orders\./.test(message.text ?? ""))).toBe(true);expect(worked.some((message) => message.text === "Atlas counted 42 orders.")).toBe(true);+ // A file goes with the work into the receiving conversation's own inbox, and one the teammate attaches comes back.+ const desk = join(computer.dataDir, "task-workspaces", writer.id, writer.activeTaskId), bench = join(home.dataDir, "task-workspaces", atlas.id, work.threadId);+ mkdirSync(desk, { recursive: true }); mkdirSync(bench, { recursive: true });+ writeFileSync(join(desk, "orders.csv"), "id,total\n1,20\n2,22\n");+ writeFileSync(join(bench, "totals.txt"), "42 in all\n");+ const under = (root: string, name: string): string[] => existsSync(root) ? readdirSync(root, { recursive: true }).map(String).filter((entry) => entry.endsWith(name) && /(^|[\\/])inbox[\\/]/.test(entry)) : [];+ home.plan(atlas.id, { steps: [{ tool: "attach_file", arguments: { path: join(bench, "totals.txt") } }], reply: "Atlas totalled the export." });+ computer.plan(writer.id,+ { steps: [{ tool: "coordinate_bots", arguments: { bot_ids: ["Atlas"], request_key: "export", message: "Total this export.", files: [join(desk, "orders.csv")] } }], reply: "Sent Atlas the export." },+ { reply: "Atlas totalled it." });+ await computer.cli("send", "--bot", writer.id, "--task", writer.activeTaskId, "--text", "Send Atlas the export to total.");+ await expect.poll(() => under(bench, "orders.csv").length, { timeout: 30_000 }).toBe(1);+ expect(readFileSync(join(bench, under(bench, "orders.csv")[0]!), "utf8")).toBe("id,total\n1,20\n2,22\n");+ await expect.poll(() => under(desk, "totals.txt").length, { timeout: 30_000 }).toBe(1);+ expect(readFileSync(join(desk, under(desk, "totals.txt")[0]!), "utf8")).toBe("42 in all\n");+ expect((await computer.cli("wait", "--bot", writer.id, "--task", writer.activeTaskId, "--timeout", "30")).status).toBe("settled");+ const withFiles = await computer.messages(writer.activeTaskId);+ expect(withFiles.some((message) => message.attachments?.some((file: any) => file.name === "orders.csv"))).toBe(true);+ expect(withFiles.some((message) => message.roomRequest?.phase === "result" && message.attachments?.some((file: any) => file.name === "totals.txt"))).toBe(true);+// And the other way, over the same link.computer.plan(writer.id, { reply: "Writer drafted the summary." });home.plan(atlas.id,diff --git a/server/bot-link/dial.ts b/server/bot-link/dial.tsindex b85da963b7..2d2315d679 100644--- a/server/bot-link/dial.ts+++ b/server/bot-link/dial.ts@@ -6,14 +6,20 @@// the other has not acknowledged. The Cloud's answer that it sleeps stops the asking until this computer has work for it// or the app says the Cloud is awake (`start`), since any request would start a sleeping Cloud; the app looks every// minute and never asks the Cloud itself to find out.-import type { BotLink, EndedLink } from "./link.ts";-import { HOLD_MS, SYNC_PATH, syncAnswer, type Frame } from "./protocol.ts";+import { createWriteStream, openAsBlob, rmSync } from "node:fs";+import { Readable, Transform } from "node:stream";+import { pipeline } from "node:stream/promises";++import type { BotLink, EndedLink, FileTransfer } from "./link.ts";+import { FILE_PATH, HOLD_MS, SYNC_PATH, syncAnswer, type FileWay, type Frame } from "./protocol.ts";const FIRST_RETRY_MS = 1_000;const MAX_RETRY_MS = 60_000;/** What the Cloud marks a held answer with while it goes to sleep (server/cloud-power.ts). */const POWER_HEADER = "x-omb-cloud-power";const BACKGROUND_HEADER = "x-omb-background";+/** One file may take this long to cross. */+const FILE_MS = 10 * 60_000;export interface DialerOptions {link: BotLink;@@ -35,6 +41,45 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h});const carriesWork = (frames: readonly { frame: Frame }[]) => frames.some(({ frame }) => frame.t === "handoff" || frame.t === "result" || frame.t === "cancel");+ /** A file's bytes, over requests of this computer's: put before the frame that names it, got after one that does. An+ * answer in the 400s says the Cloud will not take or does not have it (`gone`); anything else is tried again. */+ const fileUrl = (origin: string, id: string, way: FileWay, index: number, name: string, more: Record<string, string> = {}) => `${origin}${FILE_PATH}?${new URLSearchParams({ id, way, index: String(index), name, ...more })}`;+ const refusedFile = async (response: Response) => {+ const told = await response.json().then((answer) => { const error = (answer as { error?: unknown } | null)?.error; return typeof error === "string" ? error : ""; }, () => "");+ return Object.assign(new Error(told || `the Cloud answered ${response.status}`), { gone: response.status >= 400 && response.status < 500 && ![401, 403, 408, 429].includes(response.status) });+ };+ const cloud = () => { const target = link.dial(); if (!target) throw new Error("not linked"); return { ...target, headers: { authorization: `Bearer ${target.token}`, origin: target.origin } }; };+ const transfer: FileTransfer = {+ async holds(id, way, index, file) {+ const target = cloud();+ const response = await fetchImpl(fileUrl(target.origin, id, way, index, file.name, { probe: "1", bytes: String(file.bytes) }), { redirect: "error", signal: AbortSignal.timeout(30_000), headers: target.headers });+ if (!response.ok) throw await refusedFile(response);+ return (await response.json() as { have?: unknown }).have === true;+ },+ async push(id, way, index, file) {+ const target = cloud();+ const response = await fetchImpl(fileUrl(target.origin, id, way, index, file.name), { method: "PUT", redirect: "error", signal: AbortSignal.timeout(FILE_MS),+ headers: { ...target.headers, "content-type": "application/octet-stream" }, body: await openAsBlob(file.path) });+ if (!response.ok) throw await refusedFile(response);+ await response.body?.cancel();+ },+ async pull(id, way, index, meta, to) {+ const target = cloud();+ const response = await fetchImpl(fileUrl(target.origin, id, way, index, meta.name), { redirect: "error", signal: AbortSignal.timeout(FILE_MS), headers: target.headers });+ if (!response.ok || !response.body) throw await refusedFile(response);+ // No more than the frame said: a file that turns out larger is not kept.+ let taken = 0, over = false;+ const capped = new Transform({ transform(chunk: Buffer, _encoding, done) { taken += chunk.length; over = taken > meta.bytes; done(over ? new Error("too large") : null, chunk); } });+ try {+ await pipeline(Readable.fromWeb(response.body as import("node:stream/web").ReadableStream), capped, createWriteStream(to, { mode: 0o600 }));+ } catch (error) {+ rmSync(to, { force: true });+ throw over ? Object.assign(new Error(`${meta.name} is larger than it was said to be`), { gone: true }) : error;+ }+ if (taken !== meta.bytes) { rmSync(to, { force: true }); throw new Error(`${meta.name} did not arrive whole`); }+ },+ };+ link.setTransfer(transfer);const stopListening = link.onOutgoing(() => { held?.abort(); });const stopWanted = link.onWanted(() => { if (stopped) return; asleep = false; retryMs = firstRetryMs; wakeUp?.(); });@@ -147,6 +192,6 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hif (told.length) link.forgetEnded(told);},state: () => ({ running: !stopped, asleep, needsPairing }),- close(): void { stopped = true; held?.abort(); wakeUp?.(); stopListening(); stopWanted(); },+ close(): void { stopped = true; held?.abort(); wakeUp?.(); stopListening(); stopWanted(); link.setTransfer(null); },};}diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsindex 210e595ddf..86f63a21df 100644--- a/server/bot-link/link.test.ts+++ b/server/bot-link/link.test.ts@@ -1,18 +1,20 @@// Two places, each with a real coordinator over its own data folder, joined by the real routes and the real dialer over// HTTP on this machine: "the computer" asks, "the Cloud" answers. Only the engines are fake.-import { existsSync, mkdtempSync, readFileSync } from "node:fs";+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, utimesSync, writeFileSync } from "node:fs";import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import { tmpdir } from "node:os";-import { join } from "node:path";+import { extname, join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { createCoordinator, type CoordinateBotsCall, type Coordinator, type CoordinatorHost, type HandoffView, type HostTurnResult } from "../coordinator.ts";import type { RequestAuth } from "../request-auth.ts";import type { SessionRecord } from "../sessions.ts";+import type { PassedFile } from "../host/handoff-files.ts";import { removeTempDir } from "../testing/cleanup.ts";import { createDialer } from "./dial.ts";-import { createBotLink, type BotLink } from "./link.ts";+import { createBotLink, SPOOL_KEEP_MS, type BotLink } from "./link.ts";import { createBotLinkRoutes as routesOf, linkSessionRefusal } from "../routes/bot-link.ts";import { EXCHANGE_BYTES, LINK_EXPIRES_MS, PAIR_PATH, STATE_PATH, SYNC_PATH, linkedId, peerKey, type Frame } from "./protocol.ts";@@ -42,6 +44,17 @@ function place(label: string, bots: Bot[]) {const results: Array<{ thread: string; name: string; status: string; result: string }> = [];const requests: string[] = [];const issued = new Map<string, string>();+ /** The attachment store and the hand-off file ledger, as handoff-files.ts keeps them. */+ const attachments = join(dir, "attachments");+ mkdirSync(attachments);+ const ledger = new Map<string, { from: { botId: string; name: string }; files: PassedFile[] }>();+ const keep = (name: string, data: Buffer): PassedFile => {+ const path = join(attachments, `${createHash("sha256").update(data).digest("hex").slice(0, 24)}${extname(name)}`);+ writeFileSync(path, data);+ return { kind: "file", path, name, mime: "text/plain", bytes: data.length };+ };+ /** Requests this place's server answers with a failure, once each. */+ const failing: Array<{ match: RegExp; status: number }> = [];let run: Run = async (node) => ({ ok: true, text: `${node.botId} did: ${node.text}` });let coordinator!: Coordinator, link!: BotLink, dialer!: ReturnType<typeof createDialer>, ticker: NodeJS.Timeout | undefined, http: Server | undefined;let opened = 0, port = 0, generation = 0, skew = 0, minted = 0;@@ -57,6 +70,11 @@ function place(label: string, bots: Bot[]) {kick: () => { queueMicrotask(() => { try { coordinator.tick(); } catch { /* closed */ } }); },revoke: (sessionId) => { for (const [token, id] of issued) if (id === sessionId) issued.delete(token); },now: () => Date.now() + skew,+ files: {+ carried: (id, way) => ledger.get(`${id}:${way}`)?.files ?? [],+ crossed: (id, way, from, files) => { if (!ledger.has(`${id}:${way}`)) ledger.set(`${id}:${way}`, { from, files: [...files] }); },+ store: async (files) => files.map((file) => { if (file.name.endsWith(".exe")) throw new Error(`${file.name} is not a supported attachment type`); return keep(file.name, readFileSync(file.path)); }),+ },});const inner: CoordinatorHost = {validate: () => undefined, busy: () => false, report: () => {}, changed: () => {}, park: () => {},@@ -91,7 +109,9 @@ function place(label: string, bots: Bot[]) {const readBody = async (req: IncomingMessage) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); return chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {}; };http = createServer((req, res) => {const url = new URL(req.url ?? "/", "http://127.0.0.1");- requests.push(`${req.method} ${url.pathname}`);+ requests.push(`${req.method} ${url.pathname}${url.searchParams.has("probe") ? "?probe" : ""}`);+ const fails = failing.findIndex((one) => one.match.test(requests.at(-1)!));+ if (fails >= 0) { const status = failing.splice(fails, 1)[0]!.status; req.resume(); json(res, status, { error: "try again" }); return; }void routes({ req, res, url, path: url.pathname, method: req.method ?? "GET", auth: auth(req), json: json as never, readBody: readBody as never }).catch((error) => { if (!res.headersSent) json(res, 500, { error: String(error) }); });});@@ -124,7 +144,14 @@ function place(label: string, bots: Bot[]) {}const api = {- dir, bots, runs, sent, results, requests, boot, listen, unplug, shutdown, handOff,+ dir, bots, runs, sent, results, requests, boot, listen, unplug, shutdown, handOff, keep, ledger,+ failOnce: (match: RegExp, status = 500) => { failing.push({ match, status }); },+ /** What an assignment here carries one way: who it is from and each file's name and words. */+ carries: (id: string, way: "sent" | "returned") => { const batch = ledger.get(`${id}:${way}`); return batch ? { from: batch.from.name, files: batch.files.map((file) => [file.name, readFileSync(file.path, "utf8")]) } : undefined; },+ /** The bot working on `id` attaches a file: it goes back with its result. */+ attach: (id: string, name: string, words: string) => { const batch = ledger.get(`${id}:returned`) ?? { from: { botId: "x", name: "x" }, files: [] }; batch.files.push(keep(name, Buffer.from(words))); ledger.set(`${id}:returned`, batch); },+ /** The files still waiting in this place's spool folder. */+ spooled: () => { const root = join(dir, "bot-link-files"); return existsSync(root) ? readdirSync(root, { recursive: true }).map(String).filter((entry) => /[\\/](?:sent|returned)[\\/]/.test(entry)) : []; },get link() { return link; }, get dialer() { return dialer; }, get coordinator() { return coordinator; }, get port() { return port; },engine(next: Run) { run = next; },/** Time passes for this place's link. */@@ -308,7 +335,8 @@ describe("the link between a computer and its Cloud", () => {expect(cloud.coordinator.pace()).toBe("parked");await cloud.restart({ limits: { queueMs: 80, stallMs: 1_500 } });- await computer.restart({ limits: { queueMs: 80, stallMs: 1_500 } });+ // Only the Cloud holds work here, so only its clocks are short: the computer starts its work with its usual ones.+ await computer.restart();await new Promise((resolve) => setTimeout(resolve, 300));expect(cloud.coordinator.node(receipts[0]!.requestId!)?.status).toBe("queued");expect(computer.runs).toEqual([]);@@ -526,6 +554,123 @@ describe("the link between a computer and its Cloud", () => {expect(cloud.runs).toHaveLength(1);});+ it("files go with a hand-off and come back with its result, from the computer to the Cloud", async () => {+ const { computer, cloud } = await two();+ cloud.engine(async (node) => { cloud.attach(node.id, "totals.csv", "orders,42"); return { ok: true, text: "Counted: see totals.csv" }; });+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders in this export", { files: [computer.keep("orders.csv", Buffer.from("id\n1\n2")), computer.keep("notes.txt", Buffer.from("skip refunds"))] }));+ await until(() => computer.results.length === 1, "the result is back");+ const worked = cloud.coordinator.all().find((node) => node.botId === "cloud-analyst")!;+ expect(cloud.carries(worked.id, "sent")).toEqual({ from: "Writer", files: [["orders.csv", "id\n1\n2"], ["notes.txt", "skip refunds"]] });+ expect(computer.carries(receipts[0]!.requestId!, "returned")).toEqual({ from: "Analyst", files: [["totals.csv", "orders,42"]] });+ expect(computer.results[0]!.result).toBe("Counted: see totals.csv");+ expect(cloud.spooled()).toEqual([]);+ expect(computer.spooled()).toEqual([]);+ });++ it("files go with a hand-off and come back with its result, from the Cloud to the computer", async () => {+ const { computer, cloud } = await two();+ computer.engine(async (node) => { computer.attach(node.id, "draft.md", "# Summary"); return { ok: true, text: "Drafted." }; });+ const { receipts } = await cloud.handOff("cloud-analyst", call(["Writer"], "Write this up", { files: [cloud.keep("figures.csv", Buffer.from("a,b\n1,2"))] }));+ await until(() => cloud.results.length === 1, "the result is back");+ const worked = computer.coordinator.all().find((node) => node.botId === "local-writer")!;+ expect(computer.carries(worked.id, "sent")).toEqual({ from: "Analyst", files: [["figures.csv", "a,b\n1,2"]] });+ expect(cloud.carries(receipts[0]!.requestId!, "returned")).toEqual({ from: "Writer", files: [["draft.md", "# Summary"]] });+ expect(cloud.spooled()).toEqual([]);+ expect(computer.spooled()).toEqual([]);+ });++ it("files wait for a computer that is off, and a file the working side will not take ends the hand-off with the reason", async () => {+ const { computer, cloud } = await two();+ await computer.dialer.stop();+ await until(() => !cloud.link.online(), "the Cloud sees the computer gone");+ const { receipts } = await cloud.handOff("cloud-analyst", call(["Writer"], "Write this up", { files: [cloud.keep("figures.csv", Buffer.from("a,b"))] }));+ await new Promise((resolve) => setTimeout(resolve, 150));+ computer.dialer.start();+ await until(() => cloud.results.length === 1, "the result is back");+ expect(computer.carries(computer.coordinator.all().find((node) => node.botId === "local-writer")!.id, "sent")?.files).toEqual([["figures.csv", "a,b"]]);+ expect(cloud.results[0]).toMatchObject({ status: "completed" });+ expect(receipts[0]!.outcome).toBe("queued");++ await computer.handOff("local-writer", call(["Analyst"], "Run this", { files: [computer.keep("tool.exe", Buffer.from("MZ"))] }));+ await until(() => computer.results.length === 1, "the refusal is back");+ expect(computer.results[0]).toMatchObject({ status: "failed" });+ expect(computer.results[0]!.result).toContain("tool.exe is not a supported attachment type");+ expect(cloud.runs.filter((run) => run.botId === "cloud-analyst" && !run.resumed)).toEqual([]);+ expect(cloud.spooled()).toEqual([]);+ expect((await cloud.fetch("GET", "/api/bot-link/file?id=nope&way=sent&index=0&name=x.txt", undefined, "owner")).status).toBe(403);+ });++ it("a new session does not send again the files the Cloud already holds, and nothing is left in its spool", async () => {+ const { computer, cloud } = await two();+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ cloud.engine(async (node) => { await gate; return { ok: true, text: `${node.botId} did: ${node.text}` }; });+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders", { files: [computer.keep("orders.csv", Buffer.from("id\n1\n2"))] }));+ await until(() => cloud.runs.length === 1, "the work starts");+ const puts = () => cloud.requests.filter((request) => request === "PUT /api/bot-link/file").length;+ expect(puts()).toBe(1);+ expect(cloud.spooled()).toEqual([]);+ const at = cloud.port;+ for (let round = 0; round < 3; round += 1) {+ await cloud.unplug();+ await until(() => !computer.link.online(), "the link drops");+ await cloud.listen(at);+ await until(() => computer.link.online(), "the link is back");+ await new Promise((resolve) => setTimeout(resolve, 150));+ }+ expect(puts()).toBe(1);+ expect(cloud.requests.filter((request) => request === "GET /api/bot-link/file?probe").length).toBeGreaterThanOrEqual(3);+ expect(cloud.spooled()).toEqual([]);+ release();+ await until(() => computer.results.length === 1, "the result is back");+ expect(cloud.runs.filter((run) => run.botId === "cloud-analyst")).toHaveLength(1);+ });++ it("a file that could not cross is tried again on a timer, on a link that never drops", async () => {+ const { computer, cloud } = await two();+ cloud.failOnce(/^GET \/api\/bot-link\/file$/);+ await cloud.handOff("cloud-analyst", call(["Writer"], "Write this up", { files: [cloud.keep("figures.csv", Buffer.from("a,b\n1,2"))] }));+ await new Promise((resolve) => setTimeout(resolve, 1_000));+ expect(computer.runs).toEqual([]);+ expect(computer.link.online()).toBe(true);+ await until(() => cloud.results.length === 1, "the result is back after the retry", 12_000);+ expect(cloud.results[0]).toMatchObject({ status: "completed" });+ expect(cloud.requests.filter((request) => request === "GET /api/bot-link/file")).toHaveLength(2);++ cloud.failOnce(/^PUT \/api\/bot-link\/file$/);+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders", { files: [computer.keep("orders.csv", Buffer.from("id\n1"))] }));+ await until(() => computer.results.length === 1, "the upload was tried again", 12_000);+ expect(computer.results[0]).toMatchObject({ status: "completed" });+ }, 40_000);++ it("a file that turns out larger than it was said to be is not kept, and the hand-off ends with the reason", async () => {+ const { computer, cloud } = await two();+ await computer.dialer.stop();+ await until(() => !cloud.link.online(), "the Cloud sees the computer gone");+ const file = cloud.keep("figures.csv", Buffer.from("a,b"));+ await cloud.handOff("cloud-analyst", call(["Writer"], "Write this up", { files: [file] }));+ writeFileSync(file.path, "a,b and a great deal more than was said");+ computer.dialer.start();+ await until(() => cloud.results.length === 1, "the refusal is back");+ expect(cloud.results[0]).toMatchObject({ status: "failed" });+ expect(cloud.results[0]!.result).toContain("larger than it was said to be");+ expect(computer.runs).toEqual([]);+ expect(computer.spooled()).toEqual([]);+ });++ it("bytes left in the spool by hand-offs that never came are swept: the old ones, and the oldest when there is too much", async () => {+ const { cloud } = await two();+ const root = join(cloud.dir, "bot-link-files");+ const leave = (name: string, ageMs: number) => { const dir = join(root, name, "sent"); mkdirSync(dir, { recursive: true }); const file = join(dir, "0-x.txt"); writeFileSync(file, "left"); const at = new Date(Date.now() - ageMs); utimesSync(file, at, at); };+ leave("stale", SPOOL_KEEP_MS + 60_000);+ leave("fresh", 60_000);+ cloud.link.tidy();+ expect(readdirSync(root)).toEqual(["fresh"]);+ cloud.later(SPOOL_KEEP_MS);+ cloud.link.tidy();+ expect(readdirSync(root)).toEqual([]);+ });+it("the link's sign-in reaches the link's own routes and nothing else", () => {const linked = { userId: "bot-link:computer-environment" };expect(linkSessionRefusal(linked, "POST", SYNC_PATH)).toBeNull();diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex 53c1e237d7..f573823c2f 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -12,16 +12,18 @@// Security: the link joins only servers the same person signs in to as owner (server/routes/bot-link.ts), and work that// crosses it counts as the person's own, as it does between two bots of one place. Open risk: whoever controls one side// can have the other side's bots act at their own approval levels; turning the link off on the computer ends that.-import { readFileSync, rmSync } from "node:fs";-import { join } from "node:path";+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";+import { basename, join } from "node:path";import { z } from "zod";import { writeFileAtomic } from "../atomic.ts";import type { CoordinateBotsCall, Coordinator, CoordinatorHost, HandoffView, HostTurnResult } from "../coordinator.ts";+import type { PassedFile } from "../host/handoff-files.ts";import type { PeerDeliveryReceipt } from "../peer-delivery.ts";import type { Level } from "../runtime/types.ts";-import { BRIEF_MAX, EXCHANGE_BYTES, LINK_EXPIRES_MS, PEERS_MAX, frameSchema, handoffOfRoot, isLinkedId, linkRoot, linkedBotSchema, linkedId, parseLinked, peerKey, placeSchema,- type Frame, type HandoffFrame, type LinkedBot, type Numbered, type Place, type ResultFrame } from "./protocol.ts";+import { BRIEF_MAX, EXCHANGE_BYTES, FILES_MAX, LINK_EXPIRES_MS, PEERS_MAX, frameSchema, handoffOfRoot, isLinkedId, linkRoot, linkedBotSchema, linkedId, parseLinked, peerKey, placeSchema,+ type FileMeta, type FileWay, type Frame, type HandoffFrame, type LinkedBot, type Numbered, type Place, type ResultFrame } from "./protocol.ts";const FILE = "bot-link.json";const ENDED_FILE = "bot-link-ended.json";@@ -38,6 +40,29 @@ const ALIVE_EVERY_MS = 60_000;/** How often a place's last contact is written down. */const SEEN_WRITE_MS = 60 * 60_000;const STOPPED = "Coordinated work was stopped";+const SPOOL = "bot-link-files";+/** Bytes that crossed and were never stored (their hand-off was dropped, a side restarted) are removed after this long,+ * and the oldest go first when all of them together pass the size. */+export const SPOOL_KEEP_MS = DAY_MS;+export const SPOOL_MAX_BYTES = 2 * 1024 * 1024 * 1024;+/** A file the other side refuses is not offered for ever. */+const FILE_TRIES = 3;+/** A file that could not cross yet is tried again after this long, doubling up to five minutes. */+const FILE_RETRY_MS = 5_000;+const FILE_RETRY_MAX_MS = 5 * 60_000;++/** How a computer moves a file's bytes: it puts the ones it sends and gets the ones it is sent. `holds`: the Cloud already+ * has this file, so it is not sent again. `gone` on an error: the Cloud said it will not take it or has no such file, so+ * asking again would not help. */+export interface FileTransfer {+ holds(id: string, way: FileWay, index: number, file: PassedFile): Promise<boolean>;+ push(id: string, way: FileWay, index: number, file: PassedFile): Promise<void>;+ pull(id: string, way: FileWay, index: number, meta: FileMeta, to: string): Promise<void>;+}+const gone = (message: string) => Object.assign(new Error(message), { gone: true });+const isGone = (error: unknown) => Boolean((error as { gone?: unknown } | null)?.gone);+const said = (error: unknown) => (error instanceof Error ? error.message : String(error));+const metaOf = (files: readonly PassedFile[]): FileMeta[] => files.slice(0, FILES_MAX).map(({ name, mime, kind, bytes }) => ({ name: name.slice(0, 255), mime: mime.slice(0, 200), kind, bytes }));const GONE = "The result is no longer kept.";const workSchema = z.object({@@ -94,6 +119,15 @@ export interface BotLinkDeps {personName(threadId: string): string | undefined;/** "Sent to …" in the requester's conversation. */sentRow(input: { sender: LocalBot; threadId: string; recipient: { id: string; name: string }; workThreadId: string; nodeId: string; reason?: string; doneWhen?: string }): void;+ /** The files that travel with hand-offs (server/host/handoff-files.ts). Absent: files do not cross. */+ files?: {+ /** What this assignment carries one way, in the attachment store. */+ carried(assignmentId: string, way: FileWay): readonly PassedFile[];+ /** Bytes that crossed, at these paths, into the attachment store under attach_file's own type and size rules. */+ store(files: ReadonlyArray<{ path: string; name: string }>): Promise<PassedFile[]>;+ /** Keeps them on the assignment, so they reach the receiving conversation's inbox as any passed file does. */+ crossed(assignmentId: string, way: FileWay, from: { botId: string; name: string }, files: readonly PassedFile[]): void;+ };/** The teammate's result in the requester's conversation. */resultRow(parent: HandoffView, child: HandoffView, name: string): void;/** The coordinator should look again: a place came back, or went. */@@ -133,12 +167,17 @@ export function createBotLink(deps: BotLinkDeps) {const outboundListeners = new Set<(peer: string) => void>();const wantedListeners = new Set<() => void>();/** Hand-offs this side sent whose result has not come back. */- type Pending = { peer: string; frame: HandoffFrame; settle(result: HostTurnResult): void; threadId: string; cancelled: boolean };+ type Pending = { peer: string; frame: HandoffFrame; files: readonly PassedFile[]; settle(result: HostTurnResult): void; threadId: string; cancelled: boolean; busy?: boolean; tries: number };const pending = new Map<string, Pending>();/** Hand-offs whose result came: the rest that end here (cut by restarts, refused, stopped) are stopped where they run. */const resulted = new Set<string>();let alive: NodeJS.Timeout | undefined;let toldBots = "";+ /** Hand-offs whose files are being taken in, and results whose files are being sent: one at a time each. */+ const accepting = new Set<string>(), resultsGoing = new Set<string>();+ /** What waits to be tried again because a file could not cross yet, by what it is for. */+ const retries = new Map<string, { timer: NodeJS.Timeout; delay: number }>();+ let transfer: FileTransfer | null = null;const save = () => { if (state) writeFileAtomic(file, JSON.stringify(state), { mode: 0o600 }); };const linkOf = (peer: string): Live => { let one = live.get(peer); if (!one) { one = { online: false, seq: 0, outbox: [] }; live.set(peer, one); } return one; };@@ -157,6 +196,75 @@ export function createBotLink(deps: BotLinkDeps) {}const hello = (peer: string) => { if (state) { const bots = directory(); toldBots = JSON.stringify(bots); send(peer, { t: "hello", place: state.self, bots }); } };+ const spoolRoot = join(deps.dataDir, SPOOL);+ const spoolOf = (peer: string, id: string) => join(spoolRoot, createHash("sha256").update(`${peer}\0${id}`).digest("hex").slice(0, 32));+ /** Where one crossing file's bytes wait before they are stored: named for its type, never by a path the other side chose. */+ const spoolFile = (peer: string, id: string, way: FileWay, index: number, name: string) =>+ join(spoolOf(peer, id), way, `${index}-${basename(name.replace(/\\/gu, "/")).replace(/[^\w.-]+/gu, "_").slice(-120) || "file"}`);+ const unspool = (peer: string, id: string) => { rmSync(spoolOf(peer, id), { recursive: true, force: true }); };++ /** Tries `again` later, after a wait that doubles; `settled` forgets it. */+ function retryLater(key: string, again: () => void): void {+ const delay = Math.min((retries.get(key)?.delay ?? FILE_RETRY_MS / 2) * 2, FILE_RETRY_MAX_MS);+ clearTimeout(retries.get(key)?.timer);+ const timer = setTimeout(() => { if (retries.get(key)?.timer === timer && state) again(); }, delay);+ timer.unref?.();+ retries.set(key, { timer, delay });+ }+ const settled = (key: string) => { clearTimeout(retries.get(key)?.timer); retries.delete(key); };++ /** A computer puts the files a frame names before it sends the frame, each only if the Cloud does not hold it already;+ * the Cloud sends the frame and the computer gets them. */+ async function carry(id: string, way: FileWay, files: readonly PassedFile[]): Promise<void> {+ if (!files.length || state?.role !== "dialer") return;+ if (!transfer) throw new Error("not connected");+ for (const [index, file] of files.slice(0, FILES_MAX).entries()) if (!await transfer.holds(id, way, index, file)) await transfer.push(id, way, index, file);+ }++ /** The files a frame names, in the attachment store: got from the Cloud, or already put here by the computer. */+ async function fetched(peer: string, id: string, way: FileWay, metas: readonly FileMeta[] | undefined): Promise<PassedFile[]> {+ if (!metas?.length || !deps.files) return [];+ const waiting = metas.map((meta, index) => ({ path: spoolFile(peer, id, way, index, meta.name), name: meta.name, meta }));+ if (state?.role === "dialer") {+ if (!transfer) throw new Error("not connected");+ mkdirSync(join(spoolOf(peer, id), way), { recursive: true, mode: 0o700 });+ for (const [index, file] of waiting.entries()) {+ let have = -1;+ try { have = statSync(file.path).size; } catch { /* not got yet */ }+ if (have !== file.meta.bytes) await transfer.pull(id, way, index, file.meta, file.path);+ }+ } else if (waiting.some((file) => !existsSync(file.path))) throw gone("its files did not arrive");+ let stored: PassedFile[];+ try {+ stored = await deps.files.store(waiting);+ } catch (error) {+ unspool(peer, id);+ throw gone(said(error));+ }+ unspool(peer, id);+ return stored;+ }++ /** Bytes left behind by hand-offs that never came to be stored: the old go, and the oldest go while there are too many. */+ function sweep(): void {+ let entries: Array<{ path: string; at: number; bytes: number }>;+ try {+ entries = readdirSync(spoolRoot).map((name) => {+ const path = join(spoolRoot, name);+ let at = 0, bytes = 0;+ const walk = (dir: string) => { for (const entry of readdirSync(dir, { withFileTypes: true })) { const full = join(dir, entry.name); if (entry.isDirectory()) walk(full); else { const stat = statSync(full); bytes += stat.size; at = Math.max(at, stat.mtimeMs); } } };+ try { walk(path); if (at === 0) at = statSync(path).mtimeMs; } catch { /* going */ }+ return { path, at, bytes };+ });+ } catch { return; }+ let total = entries.reduce((sum, entry) => sum + entry.bytes, 0);+ for (const entry of entries.sort((a, b) => a.at - b.at)) {+ if (now() - entry.at <= SPOOL_KEEP_MS && total <= SPOOL_MAX_BYTES) continue;+ rmSync(entry.path, { recursive: true, force: true });+ total -= entry.bytes;+ }+ }+function setOnline(peer: string, next: boolean): void {const peerState = state?.peers[peer];if (!peerState) return;@@ -210,8 +318,10 @@ export function createBotLink(deps: BotLinkDeps) {...(parent && deps.personName(parent.threadId) ? { person: deps.personName(parent.threadId)!.slice(0, 120) } : {}),...(record?.doneWhen ? { doneWhen: record.doneWhen.slice(0, 2_000) } : {}),};+ const files = deps.files?.carried(node.id, "sent") ?? [];+ if (files.length) frame.files = metaOf(files);return new Promise<HostTurnResult>((settle) => {- const entry: Pending = { peer: address.peer, frame, settle, threadId: node.threadId, cancelled: false };+ const entry: Pending = { peer: address.peer, frame, files, settle, threadId: node.threadId, cancelled: false, tries: 0 };const abort = () => {if (entry.cancelled) return;entry.cancelled = true;@@ -225,8 +335,24 @@ export function createBotLink(deps: BotLinkDeps) {dispatch(entry);});}+ /** Sends a hand-off, its files first where a computer sends them. Files that could not go yet are tried again on a+ * timer and with the next session; ones the Cloud refuses three times end the hand-off with the reason. */function dispatch(entry: Pending): void {- if (!entry.cancelled) send(entry.peer, entry.frame);+ const id = entry.frame.id, mine = () => !entry.cancelled && pending.get(id) === entry;+ if (!mine()) return;+ if (!entry.files.length || state?.role !== "dialer") { send(entry.peer, entry.frame); return; }+ if (entry.busy) return;+ entry.busy = true;+ carry(id, "sent", entry.files).then(() => { settled(`out:${id}`); if (mine()) send(entry.peer, entry.frame); }, (error) => {+ log(`bot link: the files of ${id} did not go (${said(error)})`);+ if (!mine()) return;+ if (!isGone(error) || (entry.tries += 1) < FILE_TRIES) { retryLater(`out:${id}`, () => dispatch(entry)); return; }+ settled(`out:${id}`);+ pending.delete(id);+ resulted.add(id);+ keepAlive();+ entry.settle({ ok: false, text: `Its files could not be sent to ${placeName(entry.peer)} (${said(error)}), so the work was not started there.` });+ }).finally(() => { entry.busy = false; });}/** A kept result as the frame its requester gets: the words come from the runtime's own row of the work. */@@ -235,9 +361,23 @@ export function createBotLink(deps: BotLinkDeps) {const text = work.done.text ?? (work.child ? deps.coordinator().status(work.child)?.assignment.result : undefined) ?? (work.done.ok ? GONE : "");return { t: "result", id, ok: work.done.ok, text: text.slice(0, 200_000), ...(work.done.outcome ? { outcome: work.done.outcome } : {}) };}+ /** The files a finished assignment here returns to its requester. */+ const returned = (work: Work): readonly PassedFile[] => (work.done?.ok && work.child && work.ackedAt === undefined ? deps.files?.carried(work.child, "returned") ?? [] : []);+ /** Sends a kept result, the files it returns first where a computer sends them. */function dispatchResult(id: string): void {const work = state?.work[id], frame = work ? resultFrame(id, work) : null;- if (work && frame) send(work.peer, frame);+ if (!work || !frame) return;+ const files = returned(work);+ if (!files.length) { send(work.peer, frame); return; }+ const withFiles: ResultFrame = { ...frame, files: metaOf(files) };+ if (state?.role !== "dialer") { send(work.peer, withFiles); return; }+ if (resultsGoing.has(id)) return;+ resultsGoing.add(id);+ carry(id, "returned", files).then(() => { settled(`back:${id}`); send(work.peer, withFiles); }, (error) => {+ log(`bot link: the files of ${id}'s result did not go (${said(error)})`);+ if (isGone(error)) { settled(`back:${id}`); send(work.peer, { ...frame, text: `${frame.text}\n\n(The files it attached could not be sent across.)` }); }+ else retryLater(`back:${id}`, () => dispatchResult(id));+ }).finally(() => { resultsGoing.delete(id); });}/** The work ended here. `text` only when no assignment of this place holds the words. */@@ -256,10 +396,20 @@ export function createBotLink(deps: BotLinkDeps) {if (!state) return;const known = state.work[frame.id];if (known) { if (known.peer === peer && known.done) dispatchResult(frame.id); return; }- start(peer, frame);+ if (!frame.files?.length || !deps.files) { start(peer, frame, []); return; }+ if (accepting.has(frame.id)) return;+ accepting.add(frame.id);+ fetched(peer, frame.id, "sent", frame.files).then((files) => { settled(`in:${frame.id}`); start(peer, frame, files); }, (error) => {+ if (!state?.peers[peer] || state.work[frame.id]) return;+ // Not got yet: tried again on a timer, and when the requester sends the hand-off again with the next session.+ if (!isGone(error)) { log(`bot link: the files of ${frame.id} are not here yet (${said(error)})`); retryLater(`in:${frame.id}`, () => accept(peer, frame)); return; }+ settled(`in:${frame.id}`);+ state.work[frame.id] = { peer, root: linkRoot(frame.id), from: frame.from.name, at: now() };+ recordResult(frame.id, { ok: false, text: `The files sent with this could not be taken in (${said(error)}), so the work was not started.`, outcome: "refused" });+ }).finally(() => { accepting.delete(frame.id); });}- function start(peer: string, frame: HandoffFrame): void {+ function start(peer: string, frame: HandoffFrame, files: readonly PassedFile[]): void {if (!state || state.work[frame.id]) return;const root = linkRoot(frame.id);const address = { botId: linkedId(peer, frame.from.botId), threadId: root };@@ -285,6 +435,7 @@ export function createBotLink(deps: BotLinkDeps) {state.threads[key] = { threadId, at: now() };const { node } = coordinator.enqueue(address, root, undefined, { botId: bot.id, threadId }, frame.text, {mode: frame.mode, reply: frame.mode === "notify" ? "none" : "poll", thread: "standing", ...(frame.doneWhen ? { doneWhen: frame.doneWhen } : {}) });+ if (files.length) deps.files?.crossed(node.id, "sent", { botId: address.botId, name: frame.from.name }, files);work.child = node.id;state.work[frame.id] = work;save();@@ -311,12 +462,27 @@ export function createBotLink(deps: BotLinkDeps) {case "result": {const entry = pending.get(frame.id);if (entry && entry.peer !== peer) return;- send(peer, { t: "done", id: frame.id });- if (!entry) return;- pending.delete(frame.id);- resulted.add(frame.id);- keepAlive();- if (!entry.cancelled) entry.settle({ ok: frame.ok, text: frame.text || (frame.ok ? "" : "The work failed there without saying why.") });+ const finish = (note = "") => {+ settled(`got:${frame.id}`);+ send(peer, { t: "done", id: frame.id });+ unspool(peer, frame.id);+ if (!entry || pending.get(frame.id) !== entry) return;+ pending.delete(frame.id);+ resulted.add(frame.id);+ keepAlive();+ if (!entry.cancelled) entry.settle({ ok: frame.ok, text: `${frame.text || (frame.ok ? "" : "The work failed there without saying why.")}${note}` });+ };+ if (!entry || entry.cancelled || !frame.files?.length || !deps.files) return finish();+ if (entry.busy) return;+ entry.busy = true;+ // The result is acknowledged only once its files are here, so the working side keeps them until then.+ fetched(peer, frame.id, "returned", frame.files).then((files) => {+ deps.files!.crossed(frame.id, "returned", { botId: linkedId(peer, entry.frame.to), name: state?.peers[peer]?.bots.find((bot) => bot.id === entry.frame.to)?.name ?? "Teammate" }, files);+ finish();+ }, (error) => {+ if (isGone(error)) finish(`\n\n(The files it attached could not be brought across: ${said(error)}.)`);+ else { log(`bot link: the files of ${frame.id}'s result are not here yet (${said(error)})`); retryLater(`got:${frame.id}`, () => take(peer, frame)); }+ }).finally(() => { entry.busy = false; });return;}case "done": {@@ -369,6 +535,7 @@ export function createBotLink(deps: BotLinkDeps) {if (peer !== null && entry.peer !== peer) continue;pending.delete(id);resulted.add(id);+ unspool(entry.peer, id);if (!entry.cancelled) entry.settle({ ok: false, text: reason });}keepAlive();@@ -407,6 +574,9 @@ export function createBotLink(deps: BotLinkDeps) {if (was.role === "acceptor") for (const known of Object.values(was.peers)) if (known.sessionId) deps.revoke?.(known.sessionId);const peers = [...live.keys()];live.clear();+ for (const retry of retries.values()) clearTimeout(retry.timer);+ retries.clear();+ rmSync(spoolRoot, { recursive: true, force: true });failPending(null, "The link between this place and the person's other place was turned off before the work came back.");for (const peer of peers) for (const listener of outboundListeners) listener(peer);deps.kick();@@ -437,7 +607,8 @@ export function createBotLink(deps: BotLinkDeps) {const { node, duplicate } = coordinator.enqueue(context.address, context.generation, context.parentId, { botId: linked, threadId }, call.message, {mode, reply: call.reply === "none" ? "none" : "resume", thread: call.thread === "new" ? "new" : "standing", rework: call.rework, ...(call.doneWhen ? { doneWhen: call.doneWhen } : {}) });const returns = mode === "notify" ? "nothing comes back from it" : "its result will resume you";- const files = call.files?.length ? " Its files were not sent: files do not cross to the other place yet, so put what it needs in the message." : "";+ if (!duplicate && call.files?.length) deps.files?.crossed(node.id, "sent", { botId: context.sender.id, name: context.sender.name }, call.files);+ const files = call.files?.length && !deps.files ? " Its files were not sent: files do not cross to the other place here, so put what it needs in the message." : "";const online = isOnline(remote.peer);receipts.push(receipt(remote, duplicate && node.status !== "queued" ? "injected" : "queued",duplicate ? `already sent to ${remote.bot.name} on ${place}: it is ${node.status === "queued" ? "queued" : "under way"} and ${returns}`@@ -593,10 +764,33 @@ export function createBotLink(deps: BotLinkDeps) {for (const [id, work] of Object.entries(state.work)) if (work.peer === peer && work.done && work.ackedAt === undefined) dispatchResult(id);},/** Housekeeping, at start and once a day: old records go, and on the Cloud a computer long gone is unlinked. */- tidy(): void { prune(); expire(); },+ tidy(): void { prune(); expire(); sweep(); },/** This place's bots changed: connected places hear the new list. */botsChanged(): void { if (state && JSON.stringify(directory()) !== toldBots) for (const [peer, one] of live) if (one.online) hello(peer); },setOnline,+ /** A computer's way to move a file's bytes, while it has one. */+ setTransfer(next: FileTransfer | null): void { transfer = next; },+ /** On the Cloud: whether a file a computer is about to put is one it need not send: the Cloud has its bytes, or the+ * hand-off or result it belongs to is already known, finished or given up. */+ holds(peer: string, id: string, way: FileWay, index: number, name: string, bytes: number): boolean {+ if (!state?.peers[peer] || !deps.files) return true;+ if (way === "sent" ? Boolean(state.work[id]) : pending.get(id)?.peer !== peer) { unspool(peer, id); return true; }+ try { return statSync(spoolFile(peer, id, way, index, name)).size === bytes; } catch { return false; }+ },+ /** On the Cloud: where the bytes of a file a computer puts go. Null when they are not wanted. */+ incoming(peer: string, id: string, way: FileWay, index: number, name: string): string | null {+ if (!state?.peers[peer] || !deps.files || index < 0 || index >= FILES_MAX) return null;+ if (way === "sent" ? Boolean(state.work[id]) : pending.get(id)?.peer !== peer) return null;+ mkdirSync(join(spoolOf(peer, id), way), { recursive: true, mode: 0o700 });+ return spoolFile(peer, id, way, index, name);+ },+ /** On the Cloud: a file a computer gets: one a hand-off out to that computer carries, or one a result for it returns. */+ outgoingFile(peer: string, id: string, way: FileWay, index: number): PassedFile | undefined {+ if (!state?.peers[peer] || !deps.files) return undefined;+ if (way === "sent") { const entry = pending.get(id); return entry?.peer === peer ? entry.files[index] : undefined; }+ const work = state.work[id];+ return work?.peer === peer ? returned(work)[index] : undefined;+ },/** Frames from a place, each checked; one that does not parse is dropped. */receive(peer: string, frames: readonly unknown[]): void {for (const raw of frames) {@@ -625,6 +819,6 @@ export function createBotLink(deps: BotLinkDeps) {onWanted(listener: () => void): () => void { wantedListeners.add(listener); return () => wantedListeners.delete(listener); },sleeps: () => state?.sleeps === true,setSleeps(sleeps: boolean): void { if (state && state.role === "dialer" && (state.sleeps === true) !== sleeps) { state.sleeps = sleeps; save(); } },- close(): void { if (alive) clearInterval(alive); alive = undefined; outboundListeners.clear(); wantedListeners.clear(); },+ close(): void { if (alive) clearInterval(alive); alive = undefined; for (const retry of retries.values()) clearTimeout(retry.timer); retries.clear(); outboundListeners.clear(); wantedListeners.clear(); },};}diff --git a/server/bot-link/protocol.ts b/server/bot-link/protocol.tsindex 7ca9fd0a7f..cff3355b88 100644--- a/server/bot-link/protocol.ts+++ b/server/bot-link/protocol.ts@@ -18,6 +18,10 @@ export const handoffOfRoot = (rootId: string): string => rootId.slice(LINK_PREFIexport const SYNC_PATH = "/api/bot-link/sync";export const PAIR_PATH = "/api/bot-link/pair";export const STATE_PATH = "/api/bot-link";+/** One file of a hand-off or of its result, as bytes: the computer puts the ones it sends and gets the ones it is sent. */+export const FILE_PATH = "/api/bot-link/file";+/** As many as one assignment may carry in all (server/host/handoff-files.ts). */+export const FILES_MAX = 20;/** How long the Cloud holds a sync open when it has nothing to send. */export const HOLD_MS = 25_000;/** A computer that has not asked for this long is offline. */@@ -42,6 +46,12 @@ export const linkedBotSchema = z.object({}).strict();export type LinkedBot = z.infer<typeof linkedBotSchema>;+export const fileMeta = z.object({ name: z.string().min(1).max(255), mime: z.string().max(200), kind: z.enum(["image", "file"]), bytes: z.number().int().nonnegative() }).strict();+export type FileMeta = z.infer<typeof fileMeta>;+const files = z.array(fileMeta).max(FILES_MAX).optional();+export const fileWay = z.enum(["sent", "returned"]);+export type FileWay = z.infer<typeof fileWay>;+const handoff = z.object({t: z.literal("handoff"), id, to: id,from: z.object({ botId: id, name, threadId: id }).strict(),@@ -52,13 +62,15 @@ const handoff = z.object({origin: z.object({ kind: z.enum(["person", "routine", "outside"]), quote: z.string().max(2_000).optional() }).strict(),person: z.string().max(120).optional(),doneWhen: z.string().max(2_000).optional(),+ /** The files that travel with it: their bytes cross apart, by FILE_PATH, before the working side starts. */+ files,}).strict();export type HandoffFrame = z.infer<typeof handoff>;export const frameSchema = z.discriminatedUnion("t", [z.object({ t: z.literal("hello"), place: placeSchema, bots: z.array(linkedBotSchema).max(500) }).strict(),handoff,- z.object({ t: z.literal("result"), id, ok: z.boolean(), text: z.string().max(RESULT_MAX), outcome: z.string().max(40).optional() }).strict(),+ z.object({ t: z.literal("result"), id, ok: z.boolean(), text: z.string().max(RESULT_MAX), outcome: z.string().max(40).optional(), files }).strict(),z.object({ t: z.literal("done"), id }).strict(),z.object({ t: z.literal("cancel"), id }).strict(),z.object({ t: z.literal("bye") }).strict(),diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.tsindex 53238c5bf5..4c27e1a15a 100644--- a/server/host/bot-link-host.ts+++ b/server/host/bot-link-host.ts@@ -1,6 +1,8 @@// index.ts's wiring of the link between a person's computer and their Cloud (server/bot-link/link.ts): the link over this// server's store and coordinator, the computer's end that asks the Cloud, and the routes. With the link off (no// bot-link.json in the data folder) `start` asks nobody and every hook here answers as if the link did not exist.+import { dirname } from "node:path";+import { createDialer } from "../bot-link/dial.ts";import { createBotLink } from "../bot-link/link.ts";import type { Coordinator, HandoffView } from "../coordinator.ts";@@ -9,6 +11,7 @@ import type { RequestAuth } from "../request-auth.ts";import { createBotLinkRoutes, linkSessionUser } from "../routes/bot-link.ts";import type { Level } from "../runtime/types.ts";import type { BotRecord, Store } from "../store.ts";+import type { HandoffFiles, PassedFile } from "./handoff-files.ts";import { sentRow, teammateResultRow } from "./handoff-sent.ts";export interface BotLinkHostDeps {@@ -25,6 +28,9 @@ export interface BotLinkHostDeps {local(auth: RequestAuth): boolean;owner(auth: RequestAuth): boolean;power(): { sleeping(): boolean; sleepSignal(): AbortSignal } | null | undefined;+ files: Pick<HandoffFiles, "carried" | "crossed" | "sentWith" | "returnedWith">;+ /** One crossed file into the attachment store, named by its bytes, under attach_file's own type and size rules. */+ storeFile(path: string, name: string, root: string): Promise<{ attachment: { kind: string; path: string; mime: string; name?: string }; bytes: number }>;log(line: string): void;}@@ -39,22 +45,39 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {openThread: (bot, title, opener) => store.createTask(bot.id, title, false, undefined, { ...opener, at: Date.now(), kind: "work" })?.threadId,hasThread: (botId, threadId) => Boolean(store.taskByThread(botId, threadId)),personName: deps.personName,- sentRow: ({ sender, threadId, recipient, workThreadId, reason, doneWhen }) => {+ files: {+ carried: deps.files.carried, crossed: deps.files.crossed,+ store: async (files) => {+ const stored: PassedFile[] = [];+ for (const file of files) {+ const { attachment, bytes } = await deps.storeFile(file.path, file.name, dirname(file.path));+ if (attachment.kind === "image" || attachment.kind === "file") stored.push({ kind: attachment.kind, path: attachment.path, name: attachment.name || file.name, mime: attachment.mime, bytes });+ }+ return stored;+ },+ },+ sentRow: ({ sender, threadId, recipient, workThreadId, nodeId, reason, doneWhen }) => {store.appendMessage(threadId, sentRow({ sender: { id: sender.id, name: sender.name, color: sender.color ?? "blue" }, recipient: { ...recipient, color: "blue" }, threadId: workThreadId, via: "direct", language: deps.language(threadId),- ...(reason ? { reason } : {}), ...(doneWhen ? { doneWhen: redactSecretsInText(doneWhen) } : {}) }));+ ...(reason ? { reason } : {}), ...(doneWhen ? { doneWhen: redactSecretsInText(doneWhen) } : {}), ...deps.files.sentWith(nodeId) }));},resultRow: (parent: HandoffView, child: HandoffView, name: string) => {if (!store.taskByThread(parent.botId, parent.threadId)) return;const done = child.status === "completed";- store.appendMessage(parent.threadId, { role: "bot", kind: "activity", roomRequest: { id: child.id, phase: "result" },+ store.appendMessage(parent.threadId, { role: "bot", kind: "activity", roomRequest: { id: child.id, phase: "result" }, ...deps.files.returnedWith(child, parent),tool: { name: teammateResultRow(deps.language(parent.threadId), child, name, undefined, undefined), ok: done,...(done && child.result.trim() ? { output: redactSecretsInText(child.result.trim()).slice(0, 2_000) } : {}) } });if (!parent.parentId && parent.reply !== "poll") store.patchTask(parent.botId, parent.threadId, { unread: true });},});const dialer = createDialer({ link, log: deps.log });- let stopWatching: (() => void) | undefined;- const watch = () => { stopWatching ??= store.onChange((change) => { if (change.type.startsWith("bot.")) link.botsChanged(); }); };+ let stopWatching: (() => void) | undefined, upkeep: NodeJS.Timeout | undefined;+ /** While the link is on: bot changes reach the other places, and old records and stray file bytes are cleared hourly. */+ const watch = () => {+ stopWatching ??= store.onChange((change) => { if (change.type.startsWith("bot.")) link.botsChanged(); });+ if (upkeep) return;+ upkeep = setInterval(() => link.tidy(), 60 * 60_000);+ upkeep.unref?.();+ };const routes = createBotLinkRoutes({ link, dialer, turnedOn: watch, environmentId: deps.environmentId, local: deps.local, owner: deps.owner, power: deps.power,// A personal Cloud issues no session without its owner's scopes, so the link's carries them; `linkSessionRefusal`// (wired where requests are admitted) keeps it to the link's own routes.@@ -63,7 +86,6 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {return { token: issued.token, sessionId: issued.session.id };},revoke: (sessionId) => { deps.sessions.revoke(sessionId); } });- let daily: NodeJS.Timeout | undefined;return {link, routes,/** Once the server is up. Off: nothing. On, on the computer: it starts asking the Cloud. */@@ -71,10 +93,8 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {if (!link.on()) return;watch();link.tidy();- daily = setInterval(() => link.tidy(), 24 * 60 * 60_000);- daily.unref?.();if (link.role() === "dialer") dialer.start({ gentle: true });},- close(): void { if (daily) clearInterval(daily); stopWatching?.(); dialer.close(); link.close(); },+ close(): void { if (upkeep) clearInterval(upkeep); stopWatching?.(); dialer.close(); link.close(); },};}diff --git a/server/host/handoff-files.ts b/server/host/handoff-files.tsindex 163c2de3fa..95b312268c 100644--- a/server/host/handoff-files.ts+++ b/server/host/handoff-files.ts@@ -245,6 +245,16 @@ export function createHandoffFiles(deps: HandoffFilesDeps) {return true;}+ /** Files that crossed from the person's other place with `assignmentId` (server/bot-link/): the ones sent with it, or the+ * ones its result returned. They are in the attachment store already, and the place they came from charged its sender. */+ function crossed(assignmentId: string, way: Way, from: { botId: string; name: string }, files: readonly PassedFile[]): void {+ if (!files.length || batchOf(assignmentId, way)) return;+ load().batches.push({ assignmentId, way, from, files: files.slice(0, HANDOFF_FILES_PER_ASSIGNMENT), at: now() });+ save();+ }+ /** What an assignment carries one way, for sending to the person's other place. */+ const carriedOne = (assignmentId: string, way: Way): readonly PassedFile[] => batchOf(assignmentId, way)?.files ?? [];+/** The chips of a hand-off line, as the row's `attachments`. */function sentWith(assignmentId: string): Attached {return attachedRow(batchOf(assignmentId, "sent")?.files);@@ -458,7 +468,7 @@ export function createHandoffFiles(deps: HandoffFilesDeps) {else if (change.type === "bot.deleted" && change.botId && id.test(change.botId)) forget({ botId: change.botId });});- return { stage, drop, reserveDay, releaseDay, sent, attached, sentWith, returnedWith, forTurn, around, coordinate, forget };+ return { stage, drop, reserveDay, releaseDay, sent, attached, sentWith, returnedWith, forTurn, around, coordinate, forget, crossed, carried: carriedOne };}export type HandoffFiles = ReturnType<typeof createHandoffFiles>;diff --git a/server/host/room-access.ts b/server/host/room-access.tsindex 9f05051f97..82e79dfc40 100644--- a/server/host/room-access.ts+++ b/server/host/room-access.ts@@ -44,6 +44,8 @@ export function createRoomAccess({ store, privateTo = () => null, lookedAfterBy,return undefined;}function roomHandoffProblem(node: Pick<HandoffView, "groupId" | "threadId" | "botId"> & Partial<Pick<HandoffView, "kind" | "id" | "origin">>, parent?: Pick<HandoffView, "groupId" | "threadId" | "botId">): string | undefined {+ // A bot of the person's other place is no record here: whether it can be reached is the link's to say.+ if (isLinkedId(node.botId)) return undefined;const group = node.groupId ? store.group(node.groupId) : undefined;const bot = store.bot(node.botId);if (!bot || bot.hidden) return "The addressed agent no longer exists";diff --git a/server/index.ts b/server/index.tsindex b6b77b9d1f..59566bf47a 100644--- a/server/index.ts+++ b/server/index.ts@@ -3908,7 +3908,7 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),worksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });-const botLink = createBotLinkHost({ dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), refusal: botMoveRefusal, language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({+const botLink = createBotLinkHost({ dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), refusal: botMoveRefusal, language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({dataDir: DATA_DIR,now: Date.now, wrote: handoffTicks.kick, handoffLimit: { refusal: (botId, open) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) },log: line => console.error("coordinator:", line),diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.tsindex 006ef0de9b..e858a477d4 100644--- a/server/routes/bot-link.ts+++ b/server/routes/bot-link.ts@@ -9,13 +9,17 @@// The sign-in it issues is good for the link's own routes and nothing else (`linkSessionRefusal`), so the file that keeps// it on the computer (bot-link.json, mode 600) is not the person's sign-in to their Cloud. Each computer has its own; one// computer's never reads or answers another's work. Turning the link off on either side ends that session.+import { createReadStream, createWriteStream, rmSync, statSync } from "node:fs";import type { ServerResponse } from "node:http";import { randomUUID } from "node:crypto";+import { Transform } from "node:stream";+import { pipeline } from "node:stream/promises";import { z } from "zod";import type { createDialer } from "../bot-link/dial.ts";import type { BotLink } from "../bot-link/link.ts";-import { PAIR_PATH, SEEN_MS, STATE_PATH, SYNC_PATH, placeSchema, syncRequest } from "../bot-link/protocol.ts";+import { FILE_PATH, PAIR_PATH, SEEN_MS, STATE_PATH, SYNC_PATH, fileWay, placeSchema, syncRequest } from "../bot-link/protocol.ts";+import { FILE_MAX_BYTES } from "../../shared/upload-limits.ts";import { answerAsleep } from "../cloud-power.ts";import type { RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -35,7 +39,7 @@ const loopbackHost = (value: string) => /^(?:localhost|127\.0\.0\.1|\[::1\])$/u.const LINK_USER = "bot-link:";export const linkSessionUser = (computerId: string): string => `${LINK_USER}${computerId}`.slice(0, 200);/** The paths a link's own sign-in may ask. */-const LINK_ROUTES: ReadonlyArray<{ method: string; path: string }> = [{ method: "POST", path: SYNC_PATH }];+const LINK_ROUTES: ReadonlyArray<{ method: string; path: string }> = [{ method: "POST", path: SYNC_PATH }, { method: "GET", path: FILE_PATH }, { method: "PUT", path: FILE_PATH }];/** Security invariant: a link's sign-in reaches the link's own routes and nothing else, whatever scopes it carries. */export function linkSessionRefusal(session: { userId?: string }, method: string, path: string): string | null {if (!session.userId?.startsWith(LINK_USER)) return null;@@ -87,7 +91,7 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {const state = () => ({ ...link.status(), ...(link.role() === "dialer" ? dialer.state() : {}) });return async ({ req, res, url, path, method, auth, json, readBody }) => {- if (path !== STATE_PATH && path !== PAIR_PATH && path !== SYNC_PATH) return PASS;+ if (path !== STATE_PATH && path !== PAIR_PATH && path !== SYNC_PATH && path !== FILE_PATH) return PASS;res.setHeader("cache-control", "no-store");if (path === STATE_PATH) {@@ -137,9 +141,38 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {return json(res, 200, { token: issued.token, place: self });}- if (method !== "POST") { req.resume(); return json(res, 405, { error: "method not allowed" }); }const peer = auth.kind === "session" ? link.peerOfSession(auth.session.id) : null;if (!peer) { req.resume(); return json(res, 403, { error: "This link is off. Turn it on again in the app." }); }+ if (path === FILE_PATH) {+ const id = url.searchParams.get("id") ?? "", way = fileWay.safeParse(url.searchParams.get("way")), index = Number(url.searchParams.get("index")), fileName = url.searchParams.get("name") ?? "";+ if (!id || id.length > 200 || !way.success || !Number.isInteger(index) || !fileName || fileName.length > 255) { req.resume(); return json(res, 400, { error: "send id, way, index and name" }); }+ if (deps.power()?.sleeping()) { req.resume(); return answerAsleep(res, json); }+ seen(peer);+ if (method === "GET" && url.searchParams.has("probe")) return json(res, 200, { have: link.holds(peer, id, way.data, index, fileName, Number(url.searchParams.get("bytes"))) });+ if (method === "GET") {+ const file = link.outgoingFile(peer, id, way.data, index);+ let bytes = -1;+ try { if (file) bytes = statSync(file.path).size; } catch { /* no longer kept */ }+ if (!file || bytes < 0) return json(res, 404, { error: "that file is no longer kept" });+ res.writeHead(200, { "content-type": "application/octet-stream", "content-length": String(bytes) });+ await pipeline(createReadStream(file.path), res).catch(() => {});+ return;+ }+ if (method !== "PUT") { req.resume(); return json(res, 405, { error: "method not allowed" }); }+ const to = link.incoming(peer, id, way.data, index, fileName);+ if (!to) { req.resume(); return json(res, 409, { error: "that file is not wanted here any more" }); }+ let taken = 0;+ const capped = new Transform({ transform(chunk: Buffer, _encoding, done) { taken += chunk.length; done(taken > FILE_MAX_BYTES ? new Error("too large") : null, chunk); } });+ try {+ await pipeline(req, capped, createWriteStream(to, { mode: 0o600 }));+ } catch {+ rmSync(to, { force: true });+ if (res.destroyed) return;+ return json(res, taken > FILE_MAX_BYTES ? 413 : 400, { error: taken > FILE_MAX_BYTES ? `a file may be at most ${Math.round(FILE_MAX_BYTES / (1024 * 1024))} MB` : "the file did not arrive whole" });+ }+ return json(res, 200, { ok: true });+ }+ if (method !== "POST") { req.resume(); return json(res, 405, { error: "method not allowed" }); }const body = syncRequest.safeParse(await readBody(req, 4 * 1024 * 1024));if (!body.success) return json(res, 400, { error: "send { ack, frames, wait }" });const power = deps.power();