Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bots on this computer and on My Cloud hand each other work over one standing link (early, behind the same switch) (#6095)
Milind Soni3ecde709167e
diff --git a/docs/runtime-contract.md b/docs/runtime-contract.mdindex a049678588..9cad57721d 100644--- a/docs/runtime-contract.md+++ b/docs/runtime-contract.md@@ -90,7 +90,7 @@ Three budgets per root, counted since the root's last durable progress (a settleThree 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. Handed-off work parked on the person, on words or on cards, is bounded by `inputWaitMs` on the wall clock, restarts included, since a window each boot reopened would never close on a host that restarts. It is infinite unless a host sets it; OpenMausBot sets three days. `inputRemindMs` (one day here) reminds the person once, and the rest of the window always follows that reminder. Expiry is `failed(expired)`: not run, not refused, never reported as approved.-Waiting never expires where nothing of the runtime's is held: a root parked on the person's **cards** has no clock at all (the answer, however late, resumes it, and no requester waits on it; a non-finite `inputWaitMs` makes every wait on the person like that), and a node **queued to continue** in place (a seat the host holds it for) is bounded by neither `queueMs` nor the tree's stall window; the only bound on a computer wait is the host's own person-hold rule.+Waiting never expires where nothing of the runtime's is held: a root parked on the person's **cards** has no clock at all (the answer, however late, resumes it, and no requester waits on it; a non-finite `inputWaitMs` makes every wait on the person like that), and a node **queued to continue** in place (a seat the host holds it for) is bounded by neither `queueMs` nor the tree's stall window; the only bound on a computer wait is the host's own person-hold rule. Work **for a bot in another of the person's places while that place cannot be reached** (the optional port `away(a)`, §8: a computer that is off or asleep, across the link of `server/bot-link/`), queued for it or already running there, is held the same way: neither `queueMs`, the turn's activity window nor the tree's stall window counts the time up to the last tick it was away, so it runs, or its result arrives, when the place is back, however long that took. Such work is parked, not busy, for `pace()`, so a Cloud that sleeps when idle is not kept awake by a computer that is off.Two loop guards bound a node that continues in place, read from the evidence of its continuing executions (`TurnEvidence.okToolCalls`, `errors`) and kept on the row (`guard`): after two consecutive continuations with no successful tool call, or when the last three error texts across continuing executions are identical, the node ends `failed(stalled)` instead of continuing (event `stalled` "no progress: …", then the settlement). A continuation whose evidence names no ok count is progress-unknown and counts neither way; a turn that ends any other way (parks, waits, settles) clears the guard. The executions budget stays as the backstop.@@ -111,7 +111,7 @@ The suite asserts these after every scenario (`server/runtime/invariants.ts`):## 8. Ports-The host (today `server/index.ts`) implements `TurnRunner`: `validate`, `canStart`, `run`, `park`, `report`, `changed`, `names`, and optionally `outward(a)`: the short labels of the outward actions (sends, posts, publishes, commits, pushes, payments) the node's cut turn completed since it began, read from the thread's activity rows (a room thread's rows attributed to the member); the restart policy (§5) reads it once at open and never reruns a turn that acted outward. The runtime owns the record and the decisions; the host owns engines, threads, chips, cards, names and notifications. A turn the host runs itself (a person's, a routine's, a room member's) begins its root with `begin()` and ends it through `end()` with the turn's evidence, cards and seat; a turn the runtime dispatched ends through its `run` result. There is no other settle, and a hand-off from a turn whose root was never begun is refused ("no turn"). The level the host records at enqueue (`levelOf`) is the level the target's turn will run with: a room hand-off's is resolved from its source, since a Chief's level flows into a room with the hand-off and never onto the shared thread (invariant I6). When that level came down a Chief's chain, `levelOf` also returns the Chief conversation's level, which the coordinator passes as `levels.chief`; the host resolves the chain from the requester's node up its parents (`server/host/delegated-level.ts`). A host method that throws is logged and read as "not now"; the next tick retries. The host calls `tick()` on its own schedule and `progress(id)` when it sees activity on a turn; `progress` writes no event (per-tool-call rows would be noise), every status change does.+The host (today `server/index.ts`) implements `TurnRunner`: `validate`, `canStart`, `run`, `park`, `report`, `changed`, `names`, and optionally `away(a)` (the assignee's place cannot be reached now; §6) and `outward(a)`: the short labels of the outward actions (sends, posts, publishes, commits, pushes, payments) the node's cut turn completed since it began, read from the thread's activity rows (a room thread's rows attributed to the member); the restart policy (§5) reads it once at open and never reruns a turn that acted outward. The runtime owns the record and the decisions; the host owns engines, threads, chips, cards, names and notifications. A turn the host runs itself (a person's, a routine's, a room member's) begins its root with `begin()` and ends it through `end()` with the turn's evidence, cards and seat; a turn the runtime dispatched ends through its `run` result. There is no other settle, and a hand-off from a turn whose root was never begun is refused ("no turn"). The level the host records at enqueue (`levelOf`) is the level the target's turn will run with: a room hand-off's is resolved from its source, since a Chief's level flows into a room with the hand-off and never onto the shared thread (invariant I6). When that level came down a Chief's chain, `levelOf` also returns the Chief conversation's level, which the coordinator passes as `levels.chief`; the host resolves the chain from the requester's node up its parents (`server/host/delegated-level.ts`). A host method that throws is logged and read as "not now"; the next tick retries. The host calls `tick()` on its own schedule and `progress(id)` when it sees activity on a turn; `progress` writes no event (per-tool-call rows would be noise), every status change does.Engine drivers declare capabilities (`server/runtime/capabilities.ts`): `resume` (keeps a native session), `nativeReviewer`, `full`, `edits`, `stepCap`, `subagents`. The level rule and the continuation rule read these flags, never driver names.diff --git a/electron/bot-link-main.mjs b/electron/bot-link-main.mjsnew file mode 100644index 0000000000..792b724777--- /dev/null+++ b/electron/bot-link-main.mjs@@ -0,0 +1,134 @@+// Main's side of the link between this computer's bots and My Cloud's (server/bot-link/link.ts). There is no switch of+// its own: it follows "This computer and My Cloud together" (places-together.mjs). When that is on and both places+// exist, main pairs without a code or a prompt: the app is already signed in to My Cloud, so it asks My Cloud, over that+// sign-in, for a sign-in of the link's own and hands it to this computer's server, which keeps the link from then on,+// window open or closed. The link belongs to one Cloud and one account: when the switch is turned off, the person signs+// out, or either changes, main ends it on this computer at once, and this computer's server tells that Cloud (now, or+// when main next says it is awake).+//+// A Cloud that sleeps is never started for the link's sake: pairing is a background request made only while the Admin+// says the Cloud is awake (or the person has just turned the switch on), a refusal is not asked again for hours, and+// main passes the Admin's word on to this computer's server every minute so its end sleeps and wakes with the Cloud.+//+// Security: only My Cloud is ever paired (the address the person's account names), never a server saved by hand or a+// team's Cloud. The link's sign-in goes from My Cloud to this computer's server and nowhere else; no page sees it.+import { BACKGROUND_HEADERS } from "./cloud-power.mjs";+import { parseTogether } from "./places-together.mjs";++const STATE = "/api/bot-link";+const PAIR = "/api/bot-link/pair";+/** How often main brings the link in line with the switch, the account and the Cloud's sleep. */+const WATCH_MS = 60_000;+/** After My Cloud refused, or this computer's server did not take the link, main waits this long before it asks again. */+export const RETRY_MS = 6 * 60 * 60_000;+/** A Cloud on a version without the link is asked again once a day (or when the app starts, or the switch is turned on again). */+export const OUTDATED_RETRY_MS = 24 * 60 * 60_000;++async function body(response) {+ try { return await response.json(); } catch { return null; }+}++/**+ * @param {{+ * wanted(): boolean,+ * pref: { read(): unknown },+ * localRequest(route: string, init?: RequestInit): Promise<Response>,+ * fetch: typeof fetch,+ * cloud(): { origin: string | null, account: string | null, asleep: boolean, signedOut?: boolean },+ * cloudName(): string,+ * log?(line: string): void,+ * watchMs?: number,+ * now?(): number,+ * }} deps `wanted()`: the switch is on and both places exist. `pref`: the switch's own file: turning it off ends a+ * link (My Cloud not being seen for a moment leaves it alone, and so does a file that cannot be read). `cloud()`: My+ * Cloud's address and the signed-in account while the person has them, whether the Admin says it sleeps now, and+ * whether the person signed out. `cloudName()`: what the app calls My Cloud, in the person's language.+ */+export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl, cloud, cloudName, log = () => {}, watchMs = WATCH_MS, now = Date.now }) {+ const local = async (method, payload) => {+ const response = await localRequest(STATE, { method, signal: AbortSignal.timeout(15_000),+ ...(payload === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(payload) }) });+ const answer = await body(response);+ if (!response?.ok) throw Object.assign(new Error(answer?.error ?? `This computer's server answered ${response?.status}`), { status: response?.status });+ return answer ?? { on: false };+ };+ let computer = null;+ const thisComputer = async () => {+ if (computer) return computer;+ const described = await body(await localRequest("/.well-known/openmausbot/environment", { signal: AbortSignal.timeout(10_000) }));+ if (!described?.environmentId) return null;+ return (computer = { id: described.environmentId, name: String(described.label ?? "").trim().slice(0, 120) || "This computer" });+ };+ /** My Cloud forgets this computer's link and ends its sign-in. Background: it is not the person using their Cloud. */+ const forget = (origin, id) => fetchImpl(`${origin}${PAIR}?${new URLSearchParams({ computer: id })}`, { method: "DELETE", credentials: "include", cache: "no-store", redirect: "error", signal: AbortSignal.timeout(10_000),+ headers: { accept: "application/json", origin, ...BACKGROUND_HEADERS } }).then((response) => response.body?.cancel(), () => {});++ async function pair() {+ const mine = cloud();+ if (!mine.origin) return { on: false, error: "no-cloud" };+ const me = await thisComputer();+ if (!me) return { on: false, error: "no-server" };+ const response = await fetchImpl(`${mine.origin}${PAIR}`, { method: "POST", credentials: "include", cache: "no-store", redirect: "error", signal: AbortSignal.timeout(30_000),+ headers: { accept: "application/json", "content-type": "application/json", origin: mine.origin, ...BACKGROUND_HEADERS }, body: JSON.stringify({ computer: me, name: cloudName().slice(0, 120) }) });+ const paired = await body(response);+ // A Cloud on a version without the link answers 404; one that is not the person's own refuses.+ if (!response.ok || typeof paired?.token !== "string") return { on: false, error: response.status === 404 ? "cloud-outdated" : "cloud-refused" };+ try {+ return await local("PUT", { on: true, origin: mine.origin, token: paired.token, name: me.name, cloud: paired.place, ...(mine.account ? { account: mine.account } : {}) });+ } catch (error) {+ // The sign-in My Cloud just made has no keeper: it is ended, not left behind.+ await forget(mine.origin, me.id);+ log(`bot link: this computer's server did not take the link (${error?.message ?? error})`);+ return { on: false, error: "no-server" };+ }+ }++ const switchedOff = () => { try { return !parseTogether(pref.read()); } catch (error) { return error?.code === "ENOENT"; } };+ let retryAt = -Infinity, switchWasOn = null, looking = null;+ async function tryPair(force) {+ if (!force && now() < retryAt) return;+ let paired;+ try { paired = await pair(); } catch (error) { paired = { on: false, error: error?.message ?? String(error) }; }+ if (paired.on) { retryAt = -Infinity; return; }+ retryAt = now() + (paired.error === "cloud-outdated" ? OUTDATED_RETRY_MS : RETRY_MS);+ log(`bot link: not linked to My Cloud (${paired.error})`);+ }+ async function reconcile() {+ const state = await local("GET").catch(() => null);+ if (!state) return;+ const mine = cloud(), off = switchedOff();+ const justOn = switchWasOn === false && !off;+ switchWasOn = !off;+ if (!state.on) {+ // A link that ended while its Cloud slept or could not be reached: this computer's server tells that Cloud now.+ if (mine.origin && !mine.asleep && Array.isArray(state.ended) && state.ended.includes(mine.origin)) await local("PUT", { cloud: "awake", origin: mine.origin }).catch(() => {});+ if (wanted() && !mine.signedOut && (justOn || !mine.asleep)) await tryPair(justOn);+ return;+ }+ if (state.role !== "dialer") return;+ const otherCloud = Boolean(mine.origin && state.origin && mine.origin !== state.origin), otherAccount = Boolean(mine.account && state.account && mine.account !== state.account);+ if (off || mine.signedOut || otherCloud || otherAccount) {+ retryAt = -Infinity;+ await local("PUT", { on: false });+ const me = await thisComputer().catch(() => null);+ // This computer's server told its Cloud if it could. Over the person's own sign-in main can make sure, for the same Cloud and account only.+ if (me && mine.origin && mine.origin === state.origin && !mine.asleep && !mine.signedOut && !otherAccount) await forget(mine.origin, me.id);+ return;+ }+ if (!mine.origin) return;+ if (state.needsPairing) { if (!mine.asleep) await tryPair(false); return; }+ // The Admin's word, passed on for this link's own Cloud only, for as long as this computer's end disagrees with it.+ if (mine.asleep && !state.asleep) await local("PUT", { cloud: "asleep", origin: mine.origin });+ else if (!mine.asleep && state.asleep) await local("PUT", { cloud: "awake", origin: mine.origin });+ }+ /** Brings the link in line with the switch, the account and the Cloud: now, when any of them changes, and every minute. */+ function look() {+ looking ??= reconcile().catch((error) => log(`bot link: ${error?.message ?? error}`)).finally(() => { looking = null; });+ return looking;+ }++ const watch = setInterval(() => { void look(); }, watchMs);+ watch.unref?.();+ void look();+ return { look, close: () => clearInterval(watch) };+}diff --git a/electron/bot-link-main.node-test.mjs b/electron/bot-link-main.node-test.mjsnew file mode 100644index 0000000000..fcc24de209--- /dev/null+++ b/electron/bot-link-main.node-test.mjs@@ -0,0 +1,174 @@+import assert from "node:assert/strict";+import test from "node:test";++import { createBotLinkMain, OUTDATED_RETRY_MS, RETRY_MS } from "./bot-link-main.mjs";++const CLOUD = "https://omb-u-1.fly.dev";++function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = false } = {}) {+ const cloudCalls = [], localCalls = [];+ let server = { on: false };+ const the = { switch: on, asleep: false, origin, account: "account-1", signedOut: false, clock: 1_000_000, unreadable: false, putFails };+ const answer = (status, value) => new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json" } });+ const link = createBotLinkMain({+ wanted: () => the.switch && Boolean(the.origin),+ pref: { read: () => { if (the.unreadable) throw new Error("busy"); return { v: 1, on: the.switch }; } },+ localRequest: async (route, init = {}) => {+ if (route === "/.well-known/openmausbot/environment") return answer(200, { environmentId: "11111111-1111-4111-8111-111111111111", label: "Sam's Mac" });+ const sent = init.body ? JSON.parse(init.body) : undefined;+ localCalls.push({ method: init.method ?? "GET", ...(sent ? { body: sent } : {}) });+ if (init.method === "PUT" && sent.on === true) {+ if (the.putFails) return answer(500, { error: "disk full" });+ server = { on: true, role: "dialer", online: true, origin: sent.origin, account: sent.account ?? null, peer: sent.cloud, bots: 0, waiting: 0, asleep: false, needsPairing: false };+ } else if (init.method === "PUT" && sent.on === false) server = { on: false };+ else if (init.method === "PUT" && sent.cloud && server.on && sent.origin === server.origin) server = { ...server, asleep: sent.cloud === "asleep" };+ return answer(200, server);+ },+ fetch: async (url, init) => {+ cloudCalls.push({ url, method: init.method, credentials: init.credentials, background: init.headers["x-omb-background"] === "1", ...(init.body ? { body: JSON.parse(init.body) } : {}) });+ if (init.method === "DELETE") return answer(200, { ok: true });+ return pairStatus === 200 ? answer(200, { token: "link-sign-in-0123456789", place: { id: "cloud-1", name: "My Cloud" } }) : answer(pairStatus, { error: "no" });+ },+ cloud: () => ({ origin: the.origin, account: the.account, asleep: the.asleep, signedOut: the.signedOut }),+ cloudName: () => "My Cloud",+ watchMs: 3_600_000,+ now: () => the.clock,+ });+ const pairs = () => cloudCalls.filter((call) => call.method === "POST").length;+ return { cloudCalls, localCalls, link, the, pairs, set server(next) { server = next; }, get server() { return server; } };+}++test("switch off: My Cloud is never asked and this computer's server is only read", async (t) => {+ const h = harness();+ t.after(() => h.link.close());+ await h.link.look();+ await h.link.look();+ assert.deepEqual(h.cloudCalls, []);+ assert.equal(h.localCalls.every((call) => call.method === "GET"), true);+});++test("switch on: pairs in the background over the person's own sign-in and hands the link's sign-in, bound to this Cloud and account, to this computer's server", async (t) => {+ const h = harness({ on: true });+ t.after(() => h.link.close());+ await h.link.look();+ assert.deepEqual(h.cloudCalls, [{ url: `${CLOUD}/api/bot-link/pair`, method: "POST", credentials: "include", background: true,+ body: { computer: { id: "11111111-1111-4111-8111-111111111111", name: "Sam's Mac" }, name: "My Cloud" } }]);+ assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { on: true, origin: CLOUD, token: "link-sign-in-0123456789", name: "Sam's Mac", cloud: { id: "cloud-1", name: "My Cloud" }, account: "account-1" } });+ await h.link.look();+ assert.equal(h.pairs(), 1);+});++test("a sleeping Cloud is not asked to pair, unless the person has just turned the switch on", async (t) => {+ const h = harness({ on: true });+ t.after(() => h.link.close());+ h.the.asleep = true;+ await h.link.look();+ await h.link.look();+ assert.equal(h.pairs(), 0);+ h.the.switch = false;+ await h.link.look();+ h.the.switch = true;+ await h.link.look();+ assert.equal(h.pairs(), 1);+});++test("a Cloud that refuses is asked again only hours later, one without the link a day later, and turning the switch on again asks at once", async (t) => {+ for (const [pairStatus, wait] of [[403, RETRY_MS], [409, RETRY_MS], [404, OUTDATED_RETRY_MS]]) {+ const h = harness({ on: true, pairStatus });+ t.after(() => h.link.close());+ await h.link.look();+ h.the.clock += wait - 60_000;+ await h.link.look();+ assert.equal(h.pairs(), 1);+ assert.equal(h.localCalls.every((call) => call.method === "GET"), true);+ h.the.clock += 120_000;+ await h.link.look();+ assert.equal(h.pairs(), 2);+ h.the.switch = false;+ await h.link.look();+ h.the.switch = true;+ await h.link.look();+ assert.equal(h.pairs(), 3);+ }+});++test("this computer's server does not take the link: the sign-in just made is ended, and My Cloud is not asked again for hours", async (t) => {+ const h = harness({ on: true, putFails: true });+ t.after(() => h.link.close());+ await h.link.look();+ assert.deepEqual(h.cloudCalls.map((call) => call.method), ["POST", "DELETE"]);+ assert.equal(h.cloudCalls[1].url, `${CLOUD}/api/bot-link/pair?computer=11111111-1111-4111-8111-111111111111`);+ for (let minute = 0; minute < 30; minute += 1) { h.the.clock += 60_000; await h.link.look(); }+ assert.equal(h.pairs(), 1);+});++test("switch turned off: this computer's server is told and My Cloud forgets this computer; My Cloud out of sight or an unreadable switch ends nothing", async (t) => {+ const h = harness({ on: true });+ t.after(() => h.link.close());+ await h.link.look();+ h.the.origin = null;+ await h.link.look();+ h.the.origin = CLOUD;+ h.the.unreadable = true;+ await h.link.look();+ assert.equal(h.server.on, true);+ h.the.unreadable = false;+ h.the.switch = false;+ await h.link.look();+ assert.deepEqual(h.server, { on: false });+ assert.deepEqual([h.cloudCalls.at(-1).method, h.cloudCalls.at(-1).background], ["DELETE", true]);+ await h.link.look();+ assert.equal(h.pairs(), 1);+});++test("signing out, another account or another Cloud ends the link on this computer at once, and the old Cloud is not asked over the new sign-in", async (t) => {+ for (const change of [(the) => { the.signedOut = true; the.account = null; }, (the) => { the.account = "account-2"; }, (the) => { the.origin = "https://omb-u-2.fly.dev"; }]) {+ const h = harness({ on: true });+ t.after(() => h.link.close());+ await h.link.look();+ const asked = h.cloudCalls.length;+ change(h.the);+ await h.link.look();+ assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { on: false } });+ assert.equal(h.cloudCalls.length, asked);+ }+ const h = harness({ on: true });+ t.after(() => h.link.close());+ await h.link.look();+ h.the.account = "account-2";+ await h.link.look();+ assert.deepEqual(h.server, { on: false });+});++test("the Admin's word on sleep goes to this computer's server for its own Cloud, for as long as its end disagrees; a link that ended unheard is told when the Cloud is awake", async (t) => {+ const h = harness({ on: true });+ t.after(() => h.link.close());+ await h.link.look();+ h.the.asleep = true;+ await h.link.look();+ assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "asleep", origin: CLOUD } });+ const puts = h.localCalls.filter((call) => call.method === "PUT").length;+ await h.link.look();+ assert.equal(h.localCalls.filter((call) => call.method === "PUT").length, puts);+ h.the.asleep = false;+ await h.link.look();+ assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "awake", origin: CLOUD } });+ h.server = { ...h.server, asleep: true };+ await h.link.look();+ assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "awake", origin: CLOUD } });+ const asked = h.cloudCalls.length;+ h.server = { ...h.server, needsPairing: true };+ h.the.asleep = true;+ await h.link.look();+ assert.equal(h.cloudCalls.length, asked);++ const ended = harness();+ t.after(() => ended.link.close());+ ended.server = { on: false, ended: [CLOUD, "https://old.example"] };+ ended.the.asleep = true;+ await ended.link.look();+ assert.equal(ended.localCalls.some((call) => call.method === "PUT"), false);+ ended.the.asleep = false;+ await ended.link.look();+ assert.deepEqual(ended.localCalls.filter((call) => call.method === "PUT"), [{ method: "PUT", body: { cloud: "awake", origin: CLOUD } }]);+});diff --git a/electron/main.mjs b/electron/main.mjsindex bbc94689dd..6fe3c43d1c 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -109,7 +109,7 @@ import { cleanWorkspaceDir, createCleanWorkspace, profilesDir } from "./clean-woimport { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";import { createHomeWindow, installHomeWindowIpc, HOME_SCREEN_PATH } from "./home-window.mjs";import { createTeamProfileSeeds } from "./team-profile-seed.mjs";-import { createHomePlaces } from "./home-places.mjs"; import { openStartPlace } from "./start-place.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs"; import { openComputerSettings } from "./open-computer-settings.mjs"; import { createPlacesTogether, installPlacesTogether, PLACES_TOGETHER_FILE } from "./places-together.mjs";+import { createHomePlaces } from "./home-places.mjs"; import { openStartPlace } from "./start-place.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs"; import { openComputerSettings } from "./open-computer-settings.mjs"; import { createPlacesTogether, installPlacesTogether, PLACES_TOGETHER_FILE } from "./places-together.mjs"; import { createBotLinkMain } from "./bot-link-main.mjs";import { createWindowStateFile } from "./window-state-file.mjs"; import { createSystemProxyCache } from "./system-proxy.mjs";import { createEnvironmentsFile, ENVIRONMENTS_SAVE_FAILED } from "./environments-file.mjs";import { createOrgLibrary } from "./org-library.mjs";@@ -271,7 +271,7 @@ let desktopDataDirLease = null;let runningDataDir = null;let localSwitchInFlight = false;let managedDesktop = null;-let cloudAccount = null, updatesConsent = null, desktopPrefs = null, ownHome = null, twoPlaces = null, windowFrameMade = null;+let cloudAccount = null, updatesConsent = null, desktopPrefs = null, ownHome = null, twoPlaces = null, botLink = null, windowFrameMade = null;let cloudAccountStarted = Promise.resolve();let cloudAccountRestoring = false;let cloudSignInRestored = false;@@ -806,7 +806,7 @@ function ensureCloudAccount() {cloudSync.accountChanged(state.account?.id ?? null); rememberCloudHome(state);rememberedHome = rememberedCloudHome(rememberedHome, state);sendUpdaterState();- cloudPower.changed(); computerSharing?.cloudChanged(); try { placesTogether.scopeChanged(); } catch {} try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); railChanged(); } catch {}+ cloudPower.changed(); computerSharing?.cloudChanged(); try { placesTogether.scopeChanged(); } catch {} try { void botLink?.look(); } catch {} try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); railChanged(); } catch {}void includedX.onState(state); void includedPages.onState(state); updatesConsent?.accountChanged(state); accounts.tell();refreshCloudMenus();announceCloudReady(state);@@ -2604,7 +2604,7 @@ const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath(const cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running")));const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });-const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, chooses: true, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });+const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, chooses: true, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); botLink = createBotLinkMain({ wanted: () => placesTogether.on(), pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep(), signedOut: cloudAccount?.state().status === "signed-out" }), cloudName: () => nativeT("cloudSetup.myCloud"), log: slog }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, synced: state => teamLinks.changed(state), log: slog });const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,@@ -2622,7 +2622,7 @@ function showHome(options) {return homeWindow.show(options).catch(error => slog(`home: ${error?.message ?? error}`));}const showStartPlace = () => openStartPlace({ home: homeWindow, places: homePlaces, profiles: localProfiles, log: slog, server: id => { const entry = environmentsState.environments.find(candidate => candidate.id === id && handSaved(candidate)); return entry ? reopenSavedServer(entry, { saved: () => environmentsState.environments.filter(handSaved), fetch: (...args) => session.defaultSession.fetch(...args), opened: async (found) => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); persistEnvironments(withActive(environmentsState, found.id)); return navigateMainWindow(activeOrigin()); } }) : Promise.resolve(false); } }).catch(error => slog(`start: ${error?.message ?? error}`)); const openOwnCloud = id => { homeWindow.cancel(); return showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } }); };-const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() }); const homeOfUrl = url => { let at = null; try { at = new URL(url); } catch { return "other"; } return at.origin === rendererOrigin() ? (at.pathname === HOME_SCREEN_PATH ? "waking" : "computer") : at.origin === myCloud() ? "cloud" : "other"; }; const placeShown = () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; return page && !page.isLoadingMainFrame() ? homeOfUrl(page.getURL()) ?? "other" : null; }; const shownHome = () => { const place = placeShown(); return place === "computer" || place === "cloud" ? place : null; }; const placesTogether = installPlacesTogether({ ipcMain, asking: cloudPageAsking, together: createPlacesTogether({ pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), powerChecked: async () => { const account = cloudAccount; if (!account) return false; await account.refresh(); return Date.now() - (account.state().verifiedAt ?? 0) < 5_000; }, computer: () => !(homeWindow.cloudOrigin() ?? ownHome?.origin()), local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), napped: () => cloudPower.hold(), shown: placeShown, focused: () => powerMonitor.getSystemIdleState(60) !== "locked" && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), openPlace: home => { const entry = home === "cloud" ? environmentsState.environments.find(candidate => candidate.origin === myCloud()) : null; return home === "cloud" && (!entry || myCloud() === homeWindow.cloudOrigin()) ? showHome({ place: "cloud" }) : workspaceMenuAction(() => switchEnvironment(entry?.id ?? LOCAL_ID)); }, send: (channel, value) => { if (shownHome()) mainWindow.webContents.send(channel, value); }, changed: () => { if (shownHome()) mainWindow.webContents.send("places-together:changed"); } }) });+const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() }); const homeOfUrl = url => { let at = null; try { at = new URL(url); } catch { return "other"; } return at.origin === rendererOrigin() ? (at.pathname === HOME_SCREEN_PATH ? "waking" : "computer") : at.origin === myCloud() ? "cloud" : "other"; }; const placeShown = () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; return page && !page.isLoadingMainFrame() ? homeOfUrl(page.getURL()) ?? "other" : null; }; const shownHome = () => { const place = placeShown(); return place === "computer" || place === "cloud" ? place : null; }; const placesTogether = installPlacesTogether({ ipcMain, asking: cloudPageAsking, together: createPlacesTogether({ pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep() }), powerChecked: async () => { const account = cloudAccount; if (!account) return false; await account.refresh(); return Date.now() - (account.state().verifiedAt ?? 0) < 5_000; }, computer: () => !(homeWindow.cloudOrigin() ?? ownHome?.origin()), local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), napped: () => cloudPower.hold(), shown: placeShown, focused: () => powerMonitor.getSystemIdleState(60) !== "locked" && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), openPlace: home => { const entry = home === "cloud" ? environmentsState.environments.find(candidate => candidate.origin === myCloud()) : null; return home === "cloud" && (!entry || myCloud() === homeWindow.cloudOrigin()) ? showHome({ place: "cloud" }) : workspaceMenuAction(() => switchEnvironment(entry?.id ?? LOCAL_ID)); }, send: (channel, value) => { if (shownHome()) mainWindow.webContents.send(channel, value); }, changed: () => { botLink?.look(); if (shownHome()) mainWindow.webContents.send("places-together:changed"); } }) });const localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), remember: homePlaces.remember, changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null }); };// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.const placeSwitch = createPlaceSwitch({ changed: () => railChanged(), stop: () => homeWindow.stopOpening(), kept: () => homePlaces.remembered(), pageSettled: () => { const page = mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null; if (page?.isLoadingMainFrame()) return new Promise(done => { page.once("did-stop-loading", done); page.once("destroyed", done); }); } }); const openPlace = (id, stale) => workspaceMenuAction(async () => { if (id === LOCAL_ID) await cleanWorkspace.settled(); if (!stale()) await switchEnvironment(id, stale); }); const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(), openComputer: (page) => openComputerSettings({ window: () => mainWindow, onLocal: (win) => senderIsLocal({ sender: win.webContents }), showLocal: () => placeSwitch.ask(LOCAL_ID, stale => { localProfiles.cancel(); return openPlace(LOCAL_ID, stale); }) }, page),@@ -3109,7 +3109,7 @@ app.on("before-quit", (e) => {companyBackupSchedule?.close();orgLibrary?.close();managedDesktop?.close();- accountRing.close(); cloudAccount?.close(); oneHome.close(); ownHome?.close(); twoPlaces?.close(); homeWindow.close(); placesTogether.close();+ accountRing.close(); cloudAccount?.close(); oneHome.close(); ownHome?.close(); twoPlaces?.close(); homeWindow.close(); placesTogether.close(); botLink?.close();companyBackupController?.abort();computerSharing?.close();cloudSync.close();diff --git a/electron/updater.test.mjs b/electron/updater.test.mjsindex c248333383..9fd95fa39d 100644--- a/electron/updater.test.mjs+++ b/electron/updater.test.mjs@@ -44,6 +44,8 @@ function mainRule() {const window = { isDestroyed: () => false, webContents: null };const listeners = new Map();const signIn = { options: null, state: { status: "signed-out", message: "restoring" } };+ // The bot link hears every change of the sign-in (bot-link-main.mjs ends a link whose account or Cloud changed).+ const botLink = { look: vi.fn(async () => {}) };const context = vm.createContext({ipcMain: { handle: () => {}, on: (channel, listener) => listeners.set(channel, listener) },senderIsLocal: localOriginModule.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed, cloudPageSenderAllowed, myCloudOrigin, otherOwnClouds,@@ -55,7 +57,7 @@ function mainRule() {// ensureCloudAccount's world: a packaged app, and a sign-in client whose state the test sets.app: { isPackaged: true, getPath: () => "/unused", getVersion: () => "1.0.0" }, process: { platform: "darwin", env: {} }, cloudTarget,path: { join: (...parts) => parts.join("/") }, os: { hostname: () => "mac" }, shell: {}, safeStorage: {},- createCloudAccountStore: () => ({}), cloudEncryption: {}, cloudAccountStore: () => ({}), cloudSync: { accountChanged: () => {} }, accounts: { tell: () => {} }, rememberCloudHome: () => {}, rememberedCloudHome, computerSharing: null, updatesConsent: null,+ createCloudAccountStore: () => ({}), cloudEncryption: {}, cloudAccountStore: () => ({}), cloudSync: { accountChanged: () => {} }, accounts: { tell: () => {} }, rememberCloudHome: () => {}, rememberedCloudHome, computerSharing: null, updatesConsent: null, botLink,sendUpdaterState: () => {}, refreshCloudMenus: () => {}, announceCloudReady: () => {}, installCloudPlanIpc: () => {},includedX: { onState: async () => {} }, includedPages: { onState: async () => {} }, cloudPower: { changed: () => {}, awaiting: () => false }, cloudLogins: { kick: () => {} },createCloudAccountClient: (options) => {@@ -91,7 +93,7 @@ function mainRule() {context.cloudSignInRestored = true;signIn.options.onState(state);};- return { context, window, show, offered, launching, signedIn, pageAllowed: vm.runInContext("updaterPageAllowed", context), serverPage: (event) => vm.runInContext("activePageOrigin", context)(event) ?? null };+ return { context, window, show, offered, launching, signedIn, botLink, pageAllowed: vm.runInContext("updaterPageAllowed", context), serverPage: (event) => vm.runInContext("activePageOrigin", context)(event) ?? null };}async function load(pageAllowed, serverPage = undefined, confirmRestart = undefined) {@@ -190,6 +192,7 @@ it("another server's page never gets the update bridge; My Cloud's does, even whrule.signedIn({ status: "signed-out" });expect(has(CLOUD, "cloud")).toBe(false);+ expect(rule.botLink.look, "a change of the sign-in is told to the bot link").toHaveBeenCalledTimes(1);rule.signedIn({ status: "connected", account: { id: "a1" }, machine: { origin: CLOUD, status: "ready" } });expect(has(CLOUD, "cloud")).toBe(true);diff --git a/server/bot-link.e2e.test.ts b/server/bot-link.e2e.test.tsnew file mode 100644index 0000000000..ff389ad9c8--- /dev/null+++ b/server/bot-link.e2e.test.ts@@ -0,0 +1,102 @@+// 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 { join } from "node:path";+import { expect, it } from "vitest";+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";++type Fixture = Awaited<ReturnType<typeof launchVerificationServer>>;++function place(fixture: Fixture) {+ const { url, dataDir } = fixture.info;+ const planPath = join(dataDir, "room-plan.json");+ const plans: Record<string, { turns: unknown[] }> = {};+ const api = async (method: string, path: string, body?: unknown, options: { status?: number; token?: string } = {}) => {+ const response = await fetch(`${url}${path}`, { method, headers: { "content-type": "application/json", origin: url, ...(options.token ? { authorization: `Bearer ${options.token}` } : {}) },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(10_000) });+ const result = await response.json() as any;+ expect(response.status, `${method} ${path}: ${JSON.stringify(result)}`).toBe(options.status ?? 200);+ return result;+ };+ return {+ url, dataDir, api,+ cli: (...args: string[]) => runControlOmb([...args, "--url", url]) as Promise<any>,+ plan(botId: string, ...turns: unknown[]) { (plans[botId] ??= { turns: [] }).turns.push(...turns); writeFileSync(planPath, JSON.stringify(plans)); },+ providerTurns: (): any[] => existsSync(`${planPath}.evidence.jsonl`)+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [],+ messages: async (threadId: string) => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[],+ };+}++it("a bot on the computer and a bot on the person's own server hand each other work and get the result back", async () => {+ const fixtures = [await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true }),+ await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true })];+ const computer = place(fixtures[0]!), home = place(fixtures[1]!);+ try {+ expect(await computer.api("GET", "/api/bot-link")).toEqual({ on: false });+ expect(existsSync(join(computer.dataDir, "bot-link.json"))).toBe(false);++ const writer = (await computer.cli("new-bot", "--name", "Writer")).bot;+ const atlas = (await home.cli("new-bot", "--name", "Atlas")).bot;++ // Pairing is the owner's: the app does it over the person's own sign-in there. The computer's own page is not one.+ await home.api("POST", "/api/bot-link/pair", { computer: { id: "computer", name: "Sam's Mac" }, name: "My server" }, { status: 403 });+ const pairing = await home.api("POST", "/api/auth/pairing", { label: "The person's app", scopes: ["admin", "client"] });+ const owner = (await home.api("POST", "/api/auth/pair", { code: pairing.code })).token as string;+ const thisComputer = { id: (await computer.api("GET", "/.well-known/openmausbot/environment")).environmentId as string, name: "Sam's Mac" };+ const paired = await home.api("POST", "/api/bot-link/pair", { computer: thisComputer, name: "My server" }, { token: owner });+ await computer.api("PUT", "/api/bot-link", { on: true, origin: home.url, token: paired.token, name: "Sam's Mac", cloud: paired.place });+ await expect.poll(async () => (await computer.api("GET", "/api/bot-link")), { timeout: 15_000 }).toMatchObject({ on: true, role: "dialer", online: true, peer: { name: "My server" } });+ await expect.poll(async () => (await computer.api("GET", "/api/bot-link")).bots, { timeout: 15_000 }).toBeGreaterThan(0);++ // The link's own sign-in opens the link and nothing else of the person's server.+ await home.api("GET", "/api/bots?messages=0", undefined, { token: paired.token, status: 403 });+ await home.api("GET", "/api/auth/session", undefined, { token: paired.token, status: 403 });+ // The standing exchange is held open by design: a backup of the linked server does not wait for it to end.+ // (This fixture's sign-in storage sits inside its data folder, which the backup itself then refuses: that check runs+ // only once the "wait for requests to finish" gate has let the backup through.)+ const backup = await fetch(`${home.url}/api/workspace-backup/export`, { method: "POST", headers: { "content-type": "application/json", origin: home.url, authorization: `Bearer ${owner}` },+ body: JSON.stringify({ password: "correct horse battery staple" }), signal: AbortSignal.timeout(20_000) });+ const backedUp = JSON.stringify(await backup.json());+ expect(backup.status, backedUp).not.toBe(409);+ expect(backedUp).not.toMatch(/Wait for bot turns/);+ await expect.poll(async () => (await computer.api("GET", "/api/bot-link")).online, { timeout: 15_000 }).toBe(true);++ // The computer's bot hands work to the server's bot by name, and is resumed with its result.+ home.plan(atlas.id, { reply: "Atlas counted 42 orders." });+ computer.plan(writer.id,+ { steps: [{ tool: "list_bots", arguments: {} }, { tool: "coordinate_bots", arguments: { bot_ids: ["Atlas"], request_key: "count", message: "Count this week's orders." } }], reply: "Asked Atlas." },+ { reply: "Atlas says 42." });+ await computer.cli("send", "--bot", writer.id, "--task", writer.activeTaskId, "--text", "Ask Atlas for this week's order count.");+ await expect.poll(() => home.providerTurns().find((turn) => turn.botId === atlas.id), { timeout: 30_000 }).toBeTruthy();+ expect((await computer.cli("wait", "--bot", writer.id, "--task", writer.activeTaskId, "--timeout", "30")).status).toBe("settled");+ await expect.poll(async () => (await computer.messages(writer.activeTaskId)).some((message) => message.roomRequest?.phase === "result" && /42 orders/.test(message.tool?.output ?? "")), { timeout: 20_000 }).toBe(true);+ const shown = await computer.messages(writer.activeTaskId);+ expect(shown.find((message) => message.roomRequest?.phase === "result").tool.name).toContain("Atlas (My server)");+ expect(shown.filter((message) => message.kind === "text").at(-1)).toMatchObject({ role: "bot", text: "Atlas says 42." });+ expect(home.providerTurns().filter((turn) => turn.botId === atlas.id)).toHaveLength(1);+ const there = (await home.api("GET", "/api/bots")).bots.find((bot: any) => bot.id === atlas.id);+ const work = there.tasks.find((task: any) => /Writer/.test(task.title ?? ""));+ expect(work, JSON.stringify(there.tasks)).toBeTruthy();+ const worked = await home.messages(work.threadId);+ expect(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);++ // And the other way, over the same link.+ computer.plan(writer.id, { reply: "Writer drafted the summary." });+ home.plan(atlas.id,+ { steps: [{ tool: "coordinate_bots", arguments: { bot_ids: ["Writer"], request_key: "draft", message: "Draft the weekly summary." } }], reply: "Asked Writer." },+ { reply: "Writer drafted it." });+ await home.cli("send", "--bot", atlas.id, "--task", atlas.activeTaskId, "--text", "Have Writer draft the weekly summary.");+ await expect.poll(async () => (await home.messages(atlas.activeTaskId)).some((message) => message.roomRequest?.phase === "result" && /drafted the summary/.test(message.tool?.output ?? "")), { timeout: 40_000 }).toBe(true);+ expect((await home.cli("wait", "--bot", atlas.id, "--task", atlas.activeTaskId, "--timeout", "30")).status).toBe("settled");+ expect((await home.messages(atlas.activeTaskId)).filter((message) => message.kind === "text").at(-1)).toMatchObject({ role: "bot", text: "Writer drafted it." });++ // Off on the computer: the server is told, and neither keeps the link.+ expect(await computer.api("PUT", "/api/bot-link", { on: false })).toEqual({ on: false });+ await expect.poll(() => existsSync(join(home.dataDir, "bot-link.json")), { timeout: 10_000 }).toBe(false);+ await home.api("POST", "/api/bot-link/sync", { ack: 0, frames: [], wait: 0 }, { token: paired.token, status: 401 });+ } finally {+ await Promise.all(fixtures.map((fixture) => fixture.close()));+ }+}, 180_000);diff --git a/server/bot-link/dial.ts b/server/bot-link/dial.tsnew file mode 100644index 0000000000..b85da963b7--- /dev/null+++ b/server/bot-link/dial.ts@@ -0,0 +1,152 @@+// A computer's end of the link (server/bot-link/link.ts): one exchange after another with its Cloud, each held open+// there until it has something to say, so both directions travel over requests this computer makes. It runs in the+// server, so the link holds with the app's window closed for as long as the computer is awake.+//+// A request that fails starts a new session after a wait that doubles up to a minute: each side then sends again whatever+// 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";++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";++export interface DialerOptions {+ link: BotLink;+ fetch?: typeof fetch;+ log?(line: string): void;+ holdMs?: number;+ firstRetryMs?: number;+}++export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS }: DialerOptions) {+ let running = false, stopped = true, asleep = false, needsPairing = false;+ let session = "", ack = 0, fresh = true, retryMs = firstRetryMs;+ let held: AbortController | null = null;+ let wakeUp: (() => void) | null = null;+ const pause = (ms: number) => new Promise<void>((resolve) => {+ const timer = setTimeout(() => { wakeUp = null; resolve(); }, ms);+ timer.unref?.();+ wakeUp = () => { clearTimeout(timer); wakeUp = null; resolve(); };+ });+ const carriesWork = (frames: readonly { frame: Frame }[]) => frames.some(({ frame }) => frame.t === "handoff" || frame.t === "result" || frame.t === "cancel");++ const stopListening = link.onOutgoing(() => { held?.abort(); });+ const stopWanted = link.onWanted(() => { if (stopped) return; asleep = false; retryMs = firstRetryMs; wakeUp?.(); });++ async function exchange(target: { origin: string; token: string }, peer: string): Promise<void> {+ if (fresh) link.sessionStarted(peer);+ const sending = link.outgoing(peer, 0);+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), holdMs + 15_000);+ timeout.unref?.();+ const wait = sending.length > 0 || fresh ? 0 : holdMs;+ if (wait > 0) held = controller;+ let response: Response;+ try {+ response = await fetchImpl(`${target.origin}${SYNC_PATH}`, {+ method: "POST", redirect: "error", cache: "no-store", signal: controller.signal,+ headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${target.token}`, origin: target.origin,+ ...(carriesWork(sending) ? {} : { [BACKGROUND_HEADER]: "1" }) },+ body: JSON.stringify({ fresh, ack, frames: sending.map((entry) => entry.frame), wait }),+ });+ } catch (error) {+ if (held === controller && controller.signal.aborted && !stopped && !asleep && link.hasOutgoing(peer)) return;+ throw error;+ } finally {+ clearTimeout(timeout);+ if (held === controller) held = null;+ }+ if (response.status === 503 && response.headers.get(POWER_HEADER) === "asleep") {+ await response.body?.cancel();+ asleep = true; fresh = true;+ link.setSleeps(true);+ link.setOnline(peer, false);+ return;+ }+ if (response.status === 401 || response.status === 403) {+ await response.body?.cancel();+ needsPairing = true;+ link.setOnline(peer, false);+ return;+ }+ if (!response.ok) { await response.body?.cancel(); throw new Error(`the Cloud answered ${response.status}`); }+ const answer = syncAnswer.safeParse(await response.json());+ if (!answer.success) throw new Error("the Cloud's answer did not parse");+ link.outgoing(peer, sending.at(-1)?.seq ?? 0);+ if (answer.data.session !== session) {+ const restarted = session !== "";+ session = answer.data.session; ack = 0;+ if (restarted && !fresh) { fresh = true; return; }+ }+ fresh = false; retryMs = firstRetryMs;+ link.setOnline(peer, true);+ const news = answer.data.frames.filter((entry) => entry.seq > ack);+ link.receive(peer, news.map((entry) => entry.frame));+ ack = Math.max(ack, ...news.map((entry) => entry.seq));+ }++ async function loop(): Promise<void> {+ if (running) return;+ running = true;+ try {+ while (!stopped) {+ const target = link.dial(), peer = link.cloudPeer();+ if (!target || !peer || needsPairing) break;+ if (asleep) { await pause(24 * 60 * 60_000); continue; }+ try { await exchange(target, peer); } catch (error) {+ if (stopped) break;+ link.setOnline(peer, false);+ fresh = true;+ if (!asleep) log(`bot link: the Cloud could not be reached (${error instanceof Error ? error.message : String(error)}); trying again in ${Math.round(retryMs / 1000)} s`);+ await pause(retryMs * (0.75 + Math.random() / 2));+ retryMs = Math.min(retryMs * 2, MAX_RETRY_MS);+ }+ }+ } finally { running = false; }+ }++ /** One request that says the link is over. True when the Cloud took it, or no longer knows the link. */+ async function bye(ended: Pick<EndedLink, "origin" | "token">): Promise<boolean> {+ try {+ const response = await fetchImpl(`${ended.origin}${SYNC_PATH}`, { method: "POST", redirect: "error", signal: AbortSignal.timeout(5_000),+ headers: { "content-type": "application/json", authorization: `Bearer ${ended.token}`, origin: ended.origin, [BACKGROUND_HEADER]: "1" },+ body: JSON.stringify({ ack: 0, frames: [{ t: "bye" } satisfies Frame], wait: 0 }) });+ await response.body?.cancel();+ return response.ok || response.status === 401 || response.status === 403;+ } catch { return false; }+ }++ return {+ /** Starts asking, or asks again at once: after turning on, after pairing again, or when the app says the Cloud is+ * awake. `gentle`: this server just started, so a Cloud that sleeps is left alone until the app says it is awake or+ * there is work for it. */+ start({ gentle = false }: { gentle?: boolean } = {}): void {+ stopped = false; asleep = gentle && link.sleeps(); needsPairing = false; fresh = true; retryMs = firstRetryMs;+ wakeUp?.();+ void loop();+ },+ /** The app says the Cloud sleeps now: nothing asks it until there is work for it or it is awake again. */+ sleep(): void { if (!stopped) { link.setSleeps(true); asleep = true; fresh = true; const peer = link.cloudPeer(); if (peer) link.setOnline(peer, false); held?.abort(); } },+ /** Stops asking. `bye`: the link was turned off here, so the Cloud is told once, unless it sleeps. True when it knows. */+ async stop({ bye: tell = false }: { bye?: boolean } = {}): Promise<boolean> {+ const target = link.dial(), sleeping = asleep;+ stopped = true;+ held?.abort();+ wakeUp?.();+ return tell && target !== null && !sleeping ? bye(target) : false;+ },+ /** The app says this Cloud is awake: links to it that ended while it could not be told are ended there now. */+ async tellEnded(origin: string): Promise<void> {+ const told: string[] = [];+ for (const ended of link.ended()) if (ended.origin === origin && await bye(ended)) told.push(ended.token);+ if (told.length) link.forgetEnded(told);+ },+ state: () => ({ running: !stopped, asleep, needsPairing }),+ close(): void { stopped = true; held?.abort(); wakeUp?.(); stopListening(); stopWanted(); },+ };+}diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsnew file mode 100644index 0000000000..210e595ddf--- /dev/null+++ b/server/bot-link/link.test.ts@@ -0,0 +1,538 @@+// 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 { 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 { 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 { removeTempDir } from "../testing/cleanup.ts";+import { createDialer } from "./dial.ts";+import { createBotLink, 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";++/** How a place addresses a bot of another: by that place's key and the bot's id there. */+const CLOUD = peerKey("cloud-environment"), COMPUTER = peerKey("computer-environment");+const onCloud = (id: string) => linkedId(CLOUD, id), onComputer = (id: string) => linkedId(COMPUTER, id);++type Bot = { id: string; name: string; hidden?: boolean };+type Run = (node: HandoffView, resumed: boolean, signal: AbortSignal) => Promise<HostTurnResult>;++const until = async (what: () => boolean, label: string, ms = 8_000) => {+ const end = Date.now() + ms;+ while (!what()) {+ if (Date.now() > end) throw new Error(`timed out: ${label}`);+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+};+const call = (botIds: string[], message: string, more: Partial<CoordinateBotsCall> = {}): CoordinateBotsCall =>+ ({ botIds, message, rework: false, thread: "standing", reply: "resume", consult: false, ...more });++/** One place. `boot()` again over the same folder is that place's server restarted. */+function place(label: string, bots: Bot[]) {+ const dir = mkdtempSync(join(tmpdir(), `bot-link-${label}-`));+ const threads = new Set<string>();+ const runs: Array<{ botId: string; threadId: string; text: string; resumed: boolean; requester: string; origin: unknown }> = [];+ const sent: Array<{ recipient: string; threadId: string }> = [];+ const results: Array<{ thread: string; name: string; status: string; result: string }> = [];+ const requests: string[] = [];+ const issued = new Map<string, string>();+ 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;+ const sockets = new Set<import("node:net").Socket>();++ function boot(options: { limits?: { queueMs?: number; stallMs?: number } } = {}) {+ link = createBotLink({+ dataDir: dir, coordinator: () => coordinator, bots: () => bots, bot: (id) => bots.find((bot) => bot.id === id), level: () => "full",+ openThread: (bot) => { const id = `${bot.id}-work-${++opened}`; threads.add(id); return id; },+ hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam",+ sentRow: (input) => { sent.push({ recipient: input.recipient.name, threadId: input.threadId }); },+ resultRow: (parent, child, name) => { results.push({ thread: parent.threadId, name, status: child.status, result: child.result }); },+ 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,+ });+ const inner: CoordinatorHost = {+ validate: () => undefined, busy: () => false, report: () => {}, changed: () => {}, park: () => {},+ names: (node, parent) => ({ requester: parent ? parent.botId : "Sam", assignee: node.botId }),+ levelOf: () => ({ level: "full" }), chiefOf: () => false,+ run: (node, resumed, signal, composed) => {+ runs.push({ botId: node.botId, threadId: node.threadId, text: node.text, resumed, requester: composed.text, origin: node.origin });+ return run(node, resumed, signal);+ },+ };+ coordinator = createCoordinator({ dataDir: dir, host: link.host(inner), log: () => {}, ...(options.limits ? { runtimeLimits: options.limits } : {}) });+ dialer = createDialer({ link, holdMs: 400, firstRetryMs: 20 });+ ticker = setInterval(() => coordinator.tick(), 15);+ return api;+ }++ const auth = (req: IncomingMessage): RequestAuth => {+ const bearer = /^Bearer (.+)$/u.exec(req.headers.authorization ?? "")?.[1];+ if (!bearer) return { kind: "loopback", scopes: ["admin", "client"] };+ const id = bearer === "owner" ? "owner-session" : bearer === "guest" ? "guest-session" : issued.get(bearer) ?? "unknown";+ return { kind: "session", via: "bearer", scopes: ["client"], session: { id, email: "[email protected]" } as SessionRecord };+ };++ async function listen(at = 0): Promise<string> {+ const routes = routesOf({+ link, dialer, environmentId: `${label}-environment`, seenMs: 900, power: () => null,+ local: (who) => who.kind === "loopback", owner: (who) => who.kind === "session" && who.session.id === "owner-session",+ issue: () => { const token = `link-token-${++minted}-0123456789`; issued.set(token, `link-session-${minted}`); return { token, sessionId: issued.get(token)! }; },+ revoke: (sessionId) => { for (const [token, id] of issued) if (id === sessionId) issued.delete(token); },+ });+ const json = (res: ServerResponse, status: number, body: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };+ 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}`);+ 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) }); });+ });+ http.on("connection", (socket) => { sockets.add(socket); socket.on("close", () => sockets.delete(socket)); });+ await new Promise<void>((resolve) => http!.listen(at, "127.0.0.1", resolve));+ port = (http.address() as AddressInfo).port;+ return `http://127.0.0.1:${port}`;+ }+ /** The network goes: every open exchange is cut and nothing answers. */+ async function unplug() {+ for (const socket of sockets) socket.destroy();+ await new Promise<void>((resolve) => { if (http) http.close(() => resolve()); else resolve(); });+ http = undefined;+ }+ async function shutdown() {+ if (ticker) clearInterval(ticker);+ dialer.close();+ await unplug();+ link.close();+ try { coordinator.close(); } catch { /* already closed */ }+ }++ /** One of this place's bots takes a turn in which it hands work on; the turn then ends and waits for it. */+ async function handOff(from: string, input: CoordinateBotsCall, local: (input: CoordinateBotsCall) => Promise<{ status: number; body: Record<string, unknown> }> = async () => ({ status: 200, body: { receipts: [] } })) {+ const id = `${label}-turn-${++generation}`, address = { botId: from, threadId: `${from}-chat` };+ coordinator.beginTurn({ id, address, brief: "Sort it out", level: "full", origin: { kind: "user", request: "Sort it out" } });+ const answer = await link.coordinate(input, { sender: bots.find((bot) => bot.id === from)!, address, generation: id, external: false, handed: () => {} }, local);+ coordinator.endTurn(id, { ok: true, text: "Handed on." });+ return { id, answer, receipts: (answer.body.receipts ?? []) as Array<{ botId: string; outcome: string; detail: string; requestId?: string }> };+ }++ const api = {+ dir, bots, runs, sent, results, requests, boot, listen, unplug, shutdown, handOff,+ 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. */+ later(ms: number) { skew += ms; },+ sessions: () => [...issued.values()],+ async fetch(method: string, path: string, body?: unknown, bearer?: string) {+ const response = await fetch(`http://127.0.0.1:${port}${path}`, { method, headers: { "content-type": "application/json", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return { status: response.status, body: await response.json() as Record<string, any> };+ },+ async restart(options?: Parameters<typeof boot>[0]) { const at = port; const serving = Boolean(http); await shutdown(); boot(options); if (serving) await listen(at); },+ remove() { removeTempDir(dir); },+ };+ return api;+}++const places: Array<ReturnType<typeof place>> = [];+afterEach(async () => {+ for (const each of places.splice(0)) { await each.shutdown(); each.remove(); }+});++/** A computer and a Cloud. The same id, `shared`, is a different bot in each. */+async function two(options: { paired?: boolean; limits?: { queueMs?: number; stallMs?: number } } = {}) {+ const computer = place("computer", [{ id: "shared", name: "Scout" }, { id: "local-writer", name: "Writer" }]).boot(options);+ const cloud = place("cloud", [{ id: "shared", name: "Atlas" }, { id: "cloud-analyst", name: "Analyst" }]).boot(options);+ places.push(computer, cloud);+ const cloudOrigin = await cloud.listen();+ await computer.listen();+ if (options.paired !== false) await pair(computer, cloud, cloudOrigin);+ return { computer, cloud, cloudOrigin };+}+async function pair(computer: ReturnType<typeof place>, cloud: ReturnType<typeof place>, cloudOrigin: string, as = { id: "computer-environment", name: "Sam's Mac" }) {+ const paired = await cloud.fetch("POST", PAIR_PATH, { computer: as, name: "My Cloud" }, "owner");+ expect(paired.status).toBe(200);+ const on = await computer.fetch("PUT", STATE_PATH, { on: true, origin: cloudOrigin, token: paired.body.token, name: as.name, cloud: paired.body.place, account: "account-1" });+ expect(on.status).toBe(200);+ await until(() => computer.link.online() && cloud.link.online(peerKey(as.id)) && computer.link.agents().length > 0 && cloud.link.agents().some((bot) => bot.id.startsWith(`link-${peerKey(as.id)}-`)), "the two places meet");+ return paired.body.token as string;+}++describe("the link between a computer and its Cloud", () => {+ it("off: nothing asks the Cloud, nothing is listed, and coordinate_bots is what it always was", async () => {+ const { computer, cloud } = await two({ paired: false });+ computer.dialer.start({ gentle: true });+ const input = call(["Atlas"], "Count the orders");+ let passed: CoordinateBotsCall | undefined;+ const { answer } = await computer.handOff("local-writer", input, async (through) => { passed = through; return { status: 409, body: { error: "No bot with id or name \"Atlas\"" } }; });+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(passed).toBe(input);+ expect(answer.status).toBe(409);+ expect(cloud.requests).toEqual([]);+ expect(computer.link.agents()).toEqual([]);+ expect(computer.link.status()).toEqual({ on: false });+ expect(existsSync(join(computer.dir, "bot-link.json"))).toBe(false);+ expect(existsSync(join(cloud.dir, "bot-link.json"))).toBe(false);+ const inner: CoordinatorHost = { validate: () => "x", busy: () => true, run: async () => ({ ok: true, text: "" }), report: () => {}, changed: () => {}, names: () => ({ requester: "a", assignee: "b" }), park: () => {}, levelOf: () => ({ level: "ask" }), chiefOf: () => true };+ const wrapped = computer.link.host(inner), node = { botId: "local-writer", threadId: "t", id: "n", parentId: "p" } as HandoffView;+ expect([wrapped.validate(node), wrapped.busy(node), wrapped.away?.(node), wrapped.chiefOf(node)]).toEqual(["x", true, false, true]);+ });++ it("only the owner pairs, only the app on the computer flips the switch, and only the link's own sign-in exchanges", async () => {+ const { computer, cloud, cloudOrigin } = await two({ paired: false });+ expect((await cloud.fetch("POST", PAIR_PATH, { computer: { id: "x", name: "Mac" }, name: "My Cloud" }, "guest")).status).toBe(403);+ expect((await computer.fetch("PUT", STATE_PATH, { on: true, origin: cloudOrigin, token: "0123456789abcdefgh", name: "Mac", cloud: { id: "c", name: "My Cloud" } }, "owner")).status).toBe(403);+ expect((await computer.fetch("PUT", STATE_PATH, { on: true, origin: "http://203.0.113.9", token: "0123456789abcdefgh", name: "Mac", cloud: { id: "c", name: "My Cloud" } })).status).toBe(400);+ expect((await cloud.fetch("POST", SYNC_PATH, { ack: 0, frames: [], wait: 0 }, "owner")).status).toBe(403);+ const token = await pair(computer, cloud, cloudOrigin);+ expect((await cloud.fetch("POST", SYNC_PATH, { ack: 0, frames: [], wait: 0 }, "owner")).status).toBe(403);+ expect((await cloud.fetch("POST", SYNC_PATH, { ack: 0, frames: [], wait: 0 }, token)).status).toBe(200);+ });++ it("each side learns the other's bots, and the same id on both sides is two bots", async () => {+ const { computer, cloud } = await two();+ expect(computer.link.agents().map((bot) => [bot.id, bot.name, bot.statusText])).toEqual([[onCloud("shared"), "Atlas", "on My Cloud"], [onCloud("cloud-analyst"), "Analyst", "on My Cloud"]]);+ expect(cloud.link.agents().map((bot) => [bot.id, bot.name])).toEqual([[onComputer("shared"), "Scout"], [onComputer("local-writer"), "Writer"]]);+ expect(computer.link.resolve("shared")).toBeUndefined();+ expect(computer.link.resolve(onCloud("shared"))?.bot.name).toBe("Atlas");+ expect(computer.link.resolve("@analyst")?.bot.id).toBe("cloud-analyst");+ expect(computer.link.resolve("Scout")).toBeUndefined();+ computer.bots.push({ id: "new", name: "Newcomer" });+ computer.link.botsChanged();+ await until(() => cloud.link.agents().some((bot) => bot.name === "Newcomer"), "the Cloud hears of the new bot");++ const { receipts } = await computer.handOff("shared", call([onCloud("shared")], "Which of us is which?"));+ expect(receipts[0]).toMatchObject({ botId: onCloud("shared"), outcome: "queued" });+ await until(() => computer.results.length === 1, "the answer is back");+ expect(cloud.runs.filter((run) => !run.resumed).map((run) => run.botId)).toEqual(["shared"]);+ expect(computer.runs.filter((run) => run.botId === "shared" && !run.resumed)).toEqual([]);+ expect(computer.results[0]).toMatchObject({ name: "Atlas (My Cloud)", status: "completed", result: "shared did: Which of us is which?" });+ });++ it("work goes from the computer to the Cloud and its result resumes the requester once, as the person's own work", async () => {+ const { computer, cloud } = await two();+ const { receipts, answer } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders", { doneWhen: "a number" }));+ expect(answer.status).toBe(200);+ expect(receipts[0]!.detail).toContain("sent to Analyst on My Cloud");+ await until(() => computer.runs.some((run) => run.resumed), "the requester is resumed");+ expect(computer.sent).toEqual([{ recipient: "Analyst (My Cloud)", threadId: "local-writer-chat" }]);+ expect(computer.results).toEqual([{ thread: "local-writer-chat", name: "Analyst (My Cloud)", status: "completed", result: "cloud-analyst did: Count the orders" }]);+ const worked = cloud.runs.filter((run) => run.botId === "cloud-analyst");+ expect(worked).toHaveLength(1);+ expect(worked[0]).toMatchObject({ threadId: "cloud-analyst-work-1", origin: { kind: "user", request: "Sort it out" } });+ expect(worked[0]!.requester).toContain("Writer (Sam's Mac)");+ expect(computer.runs.filter((run) => run.resumed)).toHaveLength(1);+ expect(computer.runs.find((run) => run.resumed)!.requester).toContain("cloud-analyst did: Count the orders");++ await computer.handOff("local-writer", call(["Analyst"], "Now the refunds"));+ await until(() => computer.results.length === 2, "the second result is back");+ expect(cloud.runs.filter((run) => run.botId === "cloud-analyst").map((run) => run.threadId)).toEqual(["cloud-analyst-work-1", "cloud-analyst-work-1"]);+ });++ it("work goes from the Cloud to the computer over the same link, and a one-way notice returns nothing", async () => {+ const { computer, cloud } = await two();+ await cloud.handOff("cloud-analyst", call(["Writer"], "Draft the summary"));+ await until(() => cloud.results.length === 1, "the Cloud has the computer's result");+ expect(cloud.results[0]).toMatchObject({ name: "Writer (Sam's Mac)", result: "local-writer did: Draft the summary" });+ const { receipts } = await cloud.handOff("cloud-analyst", call(["Writer"], "FYI: the numbers changed", { reply: "none" }));+ expect(receipts[0]!.detail).toContain("nothing comes back");+ await until(() => computer.runs.some((run) => run.text === "FYI: the numbers changed"), "the notice arrives");+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(cloud.results).toHaveLength(1);+ });++ it("a hand-off that arrives twice runs once, and a result that arrives twice resumes once", 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}` }; });+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ await until(() => cloud.runs.length === 1, "the work starts");+ const again: Frame = { t: "handoff", id: receipts[0]!.requestId!, to: "cloud-analyst", from: { botId: "local-writer", name: "Writer", threadId: "local-writer-chat" },+ thread: "x", text: "Count the orders", mode: "work", origin: { kind: "person" } };+ cloud.link.receive(COMPUTER, [again, again]);+ computer.link.sessionStarted(CLOUD);+ await new Promise((resolve) => setTimeout(resolve, 200));+ release();+ await until(() => computer.results.length === 1, "the result is back");+ const result: Frame = { t: "result", id: receipts[0]!.requestId!, ok: true, text: "a second copy" };+ computer.link.receive(CLOUD, [result, result]);+ cloud.link.receive(COMPUTER, [again]);+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(cloud.runs.filter((run) => run.botId === "cloud-analyst")).toHaveLength(1);+ expect(computer.results).toHaveLength(1);+ expect(computer.runs.filter((run) => run.resumed)).toHaveLength(1);+ });++ it("the link drops while the work runs: the result waits and arrives when the link is back, once", 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"));+ await until(() => cloud.runs.length === 1, "the work starts");+ const at = cloud.port;+ await cloud.unplug();+ await until(() => !computer.link.online(), "the computer sees the link gone");+ release();+ await until(() => !cloud.link.online(), "the Cloud sees the computer gone");+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(computer.results).toEqual([]);+ await cloud.listen(at);+ await until(() => computer.results.length === 1, "the result arrives after the link returns");+ expect(computer.results[0]!.result).toBe("cloud-analyst did: Count the orders");+ expect(cloud.runs.filter((run) => run.botId === "cloud-analyst")).toHaveLength(1);+ await until(() => computer.runs.some((run) => run.resumed), "the requester is resumed");+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(computer.runs.filter((run) => run.resumed)).toHaveLength(1);+ });++ it("the computer is off: the Cloud bot is told, the work waits past every clock and a restart of either side, and runs once when it is back", async () => {+ const { computer, cloud } = await two({ limits: { queueMs: 80, stallMs: 1_500 } });+ await computer.dialer.stop();+ await until(() => !cloud.link.online(), "the Cloud sees the computer gone");+ const { receipts, id } = await cloud.handOff("cloud-analyst", call(["Writer"], "Draft the summary"));+ expect(receipts[0]).toMatchObject({ outcome: "queued" });+ expect(receipts[0]!.detail).toContain("Sam's Mac is offline now");+ expect(cloud.link.agents().find((bot) => bot.name === "Writer")!.statusText).toContain("offline now");+ await new Promise((resolve) => setTimeout(resolve, 1_800));+ expect(cloud.coordinator.node(receipts[0]!.requestId!)?.status).toBe("queued");+ expect(cloud.coordinator.node(id)?.status).toBe("waiting");+ expect(cloud.coordinator.pace()).toBe("parked");++ await cloud.restart({ limits: { queueMs: 80, stallMs: 1_500 } });+ await computer.restart({ limits: { queueMs: 80, stallMs: 1_500 } });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(cloud.coordinator.node(receipts[0]!.requestId!)?.status).toBe("queued");+ expect(computer.runs).toEqual([]);++ computer.dialer.start();+ await until(() => cloud.results.length === 1, "the result is back after the computer returns");+ expect(cloud.results[0]).toMatchObject({ name: "Writer (Sam's Mac)", status: "completed", result: "local-writer did: Draft the summary" });+ expect(computer.runs.filter((run) => run.botId === "local-writer")).toHaveLength(1);+ await until(() => cloud.runs.some((run) => run.resumed), "the Cloud bot is resumed");+ expect(cloud.runs.filter((run) => run.resumed)).toHaveLength(1);+ });++ it("the working side restarts after it finished but before the requester heard: the kept result is sent, nothing runs again", async () => {+ const { computer, cloud } = await two();+ await computer.dialer.stop();+ await until(() => !cloud.link.online(), "the link is down");+ const frame: Frame = { t: "handoff", id: "as-1", to: "cloud-analyst", from: { botId: "local-writer", name: "Writer", threadId: "local-writer-chat" },+ thread: "t", text: "Count the orders", mode: "work", origin: { kind: "person", quote: "Sort it out" } };+ cloud.link.receive(COMPUTER, [frame]);+ await until(() => cloud.runs.length === 1, "the work ran");+ await new Promise((resolve) => setTimeout(resolve, 100));+ await cloud.restart();+ cloud.link.sessionStarted(COMPUTER);+ expect(cloud.link.outgoing(COMPUTER, 0).map((entry) => entry.frame).filter((sentFrame) => sentFrame.t === "result")).toEqual([{ t: "result", id: "as-1", ok: true, text: "cloud-analyst did: Count the orders", outcome: "done" }]);+ cloud.link.receive(COMPUTER, [frame, { t: "done", id: "as-1" }]);+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(cloud.runs).toHaveLength(1);+ cloud.link.sessionStarted(COMPUTER);+ expect(cloud.link.outgoing(COMPUTER, 0).some((entry) => entry.frame.t === "result")).toBe(false);+ });++ it("stopping the requester stops the work on the other side", async () => {+ const { computer, cloud } = await two();+ let stopped = false;+ cloud.engine((_node, _resumed, signal) => new Promise((resolve) => { signal.addEventListener("abort", () => { stopped = true; resolve({ ok: false, text: "stopped" }); }); }));+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ await until(() => cloud.runs.length === 1, "the work starts");+ computer.coordinator.cancelDirect("local-writer-chat");+ await until(() => stopped, "the Cloud's turn is stopped");+ expect(computer.results.map((row) => row.status)).not.toContain("completed");+ });++ it("turned off on the computer: the Cloud is told, both forget the link, its sign-in ends and waiting work ends with the reason", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ const token = JSON.parse((await import("node:fs")).readFileSync(join(computer.dir, "bot-link.json"), "utf8")).token as string;+ cloud.engine(() => new Promise(() => {}));+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ await until(() => cloud.runs.length === 1, "the work starts");+ const off = await computer.fetch("PUT", STATE_PATH, { on: false });+ expect(off.body).toEqual({ on: false });+ await until(() => !cloud.link.on(), "the Cloud forgets the link");+ expect(existsSync(join(computer.dir, "bot-link.json"))).toBe(false);+ expect(existsSync(join(cloud.dir, "bot-link.json"))).toBe(false);+ expect((await cloud.fetch("POST", SYNC_PATH, { ack: 0, frames: [], wait: 0 }, token)).status).toBe(403);+ await until(() => computer.results.length === 1, "the waiting work ends");+ expect(computer.results[0]).toMatchObject({ status: "failed" });+ expect(computer.results[0]!.result).toContain("turned off");+ expect(computer.link.agents()).toEqual([]);+ const before = cloud.requests.length;+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(cloud.requests.length).toBe(before);+ expect(cloudOrigin).toContain("127.0.0.1");+ });++ it("two computers on one Cloud: each has its own link, and work, results and stops go only to the computer they belong to", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ const laptop = place("laptop", [{ id: "shared", name: "Scout" }, { id: "laptop-coder", name: "Coder" }]).boot();+ places.push(laptop);+ await laptop.listen();+ const firstSessions = cloud.sessions();+ await pair(laptop, cloud, cloudOrigin, { id: "laptop-environment", name: "Sam's Laptop" });+ const LAPTOP = peerKey("laptop-environment");+ expect(cloud.sessions()).toEqual(expect.arrayContaining(firstSessions));+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(computer.link.online() && laptop.link.online()).toBe(true);+ expect(cloud.link.agents().map((bot) => [bot.id, bot.statusText])).toEqual([+ [onComputer("shared"), "on Sam's Mac"], [onComputer("local-writer"), "on Sam's Mac"], [linkedId(LAPTOP, "shared"), "on Sam's Laptop"], [linkedId(LAPTOP, "laptop-coder"), "on Sam's Laptop"]]);+ expect(cloud.link.resolve("Scout")).toBeUndefined();+ expect(cloud.link.resolve("Coder")?.peer).toBe(LAPTOP);++ await laptop.dialer.stop();+ await until(() => !cloud.link.online(LAPTOP), "the laptop goes");+ const forLaptop = await cloud.handOff("cloud-analyst", call([linkedId(LAPTOP, "shared")], "Laptop: build it"));+ expect(forLaptop.receipts[0]!.detail).toContain("Sam's Laptop is offline now");+ const forMac = await cloud.handOff("cloud-analyst", call([onComputer("shared")], "Mac: write it"));+ expect(forMac.receipts[0]!.detail).toContain("sent to Scout on Sam's Mac");+ await until(() => cloud.results.length === 1, "the Mac's result is back");+ expect(cloud.results[0]).toMatchObject({ name: "Scout (Sam's Mac)", result: "shared did: Mac: write it" });+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(computer.runs.map((run) => run.text)).toEqual(["Mac: write it"]);+ expect(laptop.runs).toEqual([]);+ expect(cloud.coordinator.node(forLaptop.receipts[0]!.requestId!)?.status).toBe("queued");++ // A result or a stop from the wrong computer changes nothing.+ computer.link.receive(CLOUD, []);+ cloud.link.receive(COMPUTER, [{ t: "result", id: forLaptop.receipts[0]!.requestId!, ok: true, text: "not mine to give" }, { t: "cancel", id: forLaptop.receipts[0]!.requestId! }]);+ laptop.dialer.start();+ await until(() => cloud.results.length === 2, "the laptop's result is back");+ expect(cloud.results[1]).toMatchObject({ name: "Scout (Sam's Laptop)", result: "shared did: Laptop: build it" });+ expect(laptop.runs.map((run) => run.text)).toEqual(["Laptop: build it"]);++ // One computer turns its link off: the other's stays.+ expect((await laptop.fetch("PUT", STATE_PATH, { on: false })).body).toEqual({ on: false });+ await until(() => cloud.link.agents().length === 2, "the Cloud forgets the laptop only");+ expect(cloud.link.online(COMPUTER)).toBe(true);+ expect(cloud.sessions()).toEqual(firstSessions);+ });++ it("a computer that goes off while it works for the Cloud holds the work without a clock and without keeping the Cloud busy", async () => {+ const { computer, cloud } = await two();+ // Only the Cloud's clocks are short: the computer's own work is not what is measured.+ await cloud.restart({ limits: { queueMs: 80, stallMs: 2_000 } });+ await until(() => computer.link.online() && cloud.link.online(), "the link is back after the Cloud restarted");+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ computer.engine(async (node) => { await gate; return { ok: true, text: `${node.botId} did: ${node.text}` }; });+ const { receipts } = await cloud.handOff("cloud-analyst", call(["Writer"], "Draft the summary"));+ await until(() => computer.runs.length === 1, "the work starts on the computer");+ expect(cloud.coordinator.pace()).toBe("busy");+ await computer.dialer.stop();+ await until(() => !cloud.link.online(), "the Cloud sees the computer gone");+ await new Promise((resolve) => setTimeout(resolve, 3_000));+ expect(cloud.coordinator.node(receipts[0]!.requestId!)?.status).toBe("running");+ expect(cloud.coordinator.pace()).toBe("parked");+ release();+ computer.dialer.start();+ await until(() => cloud.results.length === 1, "the result is back");+ expect(cloud.results[0]).toMatchObject({ status: "completed", result: "local-writer did: Draft the summary" });+ expect(computer.runs.filter((run) => !run.resumed)).toHaveLength(1);+ });++ it("a computer not heard from for thirty days is unlinked on the Cloud: its sign-in ends and work waiting for it fails with the reason", async () => {+ const { computer, cloud } = await two();+ await computer.dialer.stop();+ await until(() => !cloud.link.online(), "the Cloud sees the computer gone");+ await cloud.handOff("cloud-analyst", call(["Writer"], "Draft the summary"));+ cloud.later(LINK_EXPIRES_MS - 60_000);+ cloud.link.tidy();+ expect(cloud.link.on()).toBe(true);+ cloud.later(120_000);+ cloud.link.tidy();+ expect(cloud.link.on()).toBe(false);+ expect(cloud.sessions()).toEqual([]);+ await until(() => cloud.results.length === 1, "the waiting work ends");+ expect(cloud.results[0]).toMatchObject({ status: "failed" });+ expect(existsSync(join(cloud.dir, "bot-link.json"))).toBe(false);+ });++ it("turned off while the Cloud cannot be told: the Cloud is told when the app next says it is awake, and only for that Cloud", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ const at = cloud.port;+ await cloud.unplug();+ expect((await computer.fetch("PUT", STATE_PATH, { on: false })).body).toEqual({ on: false, ended: [cloudOrigin] });+ expect(JSON.parse(readFileSync(join(computer.dir, "bot-link-ended.json"), "utf8"))).toHaveLength(1);+ await cloud.listen(at);+ expect(cloud.link.on()).toBe(true);+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: "https://another.example" });+ expect(cloud.link.on()).toBe(true);+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin });+ expect(cloud.link.on()).toBe(false);+ expect(cloud.sessions()).toEqual([]);+ expect(existsSync(join(computer.dir, "bot-link-ended.json"))).toBe(false);+ });++ it("the app's word about one Cloud is not fed to a link to another", async () => {+ const { computer, cloudOrigin } = await two();+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: "https://another.example" })).body).toMatchObject({ asleep: false, online: true });+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin })).body).toMatchObject({ asleep: true, online: false });+ expect((await computer.fetch("GET", STATE_PATH)).body).toMatchObject({ origin: cloudOrigin, account: "account-1" });+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin });+ await until(() => computer.link.online(), "the link is back");+ });++ it("more results than one exchange carries go a part at a time, and all arrive", async () => {+ const { computer, cloud } = await two();+ const words = "x".repeat(11_000);+ cloud.engine(async (node) => ({ ok: true, text: `${node.text}:${words}` }));+ await computer.dialer.stop();+ await until(() => !cloud.link.online(), "the link is down");+ const ids = Array.from({ length: 160 }, (_, index) => `big-${index}`);+ cloud.link.receive(COMPUTER, ids.map((id): Frame => ({ t: "handoff", id, to: "cloud-analyst", from: { botId: "local-writer", name: "Writer", threadId: "local-writer-chat" }, thread: `t-${id}`, text: id, mode: "work", origin: { kind: "person" } })));+ await until(() => cloud.coordinator.all().filter((node) => node.botId === "cloud-analyst" && node.status === "completed").length === ids.length, "all the work is done", 30_000);+ await new Promise((resolve) => setTimeout(resolve, 200));+ cloud.link.sessionStarted(COMPUTER);+ const part = cloud.link.outgoing(COMPUTER, 0);+ expect(part.length).toBeLessThan(ids.length);+ expect(JSON.stringify(part).length).toBeLessThan(EXCHANGE_BYTES + 20_000);+ const taken: string[] = [];+ for (let ack = 0, rounds = 0; rounds < 30; rounds += 1) {+ const next = cloud.link.outgoing(COMPUTER, ack);+ if (next.length === 0) break;+ for (const entry of next) if (entry.frame.t === "result") taken.push(entry.frame.id);+ ack = next.at(-1)!.seq;+ }+ expect(taken.sort()).toEqual([...ids].sort());+ computer.dialer.start();+ await until(() => cloud.link.outgoing(COMPUTER, 0).every((entry) => entry.frame.t !== "result") && cloud.link.online(), "the computer took them all", 15_000);+ }, 60_000);++ it("a requester cut by two restarts fails the hand-off and stops the work where it runs", async () => {+ const { computer, cloud } = await two();+ let stopped = false;+ cloud.engine((_node, _resumed, signal) => new Promise((resolve) => { signal.addEventListener("abort", () => { stopped = true; resolve({ ok: false, text: "stopped" }); }); }));+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ await until(() => cloud.runs.length === 1, "the work starts");+ await computer.restart();+ computer.dialer.start();+ await until(() => computer.link.online(), "the computer is back");+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(stopped).toBe(false);+ expect(cloud.runs).toHaveLength(1);+ await computer.restart();+ computer.dialer.start();+ await until(() => stopped, "the Cloud's turn is stopped");+ expect(cloud.runs).toHaveLength(1);+ });++ 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();+ for (const [method, path] of [["GET", "/api/bots"], ["GET", SYNC_PATH], ["POST", PAIR_PATH], ["DELETE", PAIR_PATH], ["GET", STATE_PATH], ["POST", "/api/bots/x/messages"]] as const) {+ expect(linkSessionRefusal(linked, method, path)).toContain("only for the link");+ }+ expect(linkSessionRefusal({}, "GET", "/api/bots")).toBeNull();+ expect(linkSessionRefusal({ userId: "portal:abc" }, "GET", "/api/bots")).toBeNull();+ });+});diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsnew file mode 100644index 0000000000..53c1e237d7--- /dev/null+++ b/server/bot-link/link.ts@@ -0,0 +1,630 @@+// The link between a person's own computers and their own Cloud, so the bots of each work together as bots of one place+// do. A computer's server asks the Cloud (server/bot-link/dial.ts, a home computer has no address to be reached at) and+// both directions travel over that one standing exchange. Nothing here runs until the person turns the link on: without+// its state file no frame is sent, taken or acted on.+//+// The Cloud keeps one link for each computer; a computer keeps one, to its Cloud. A bot of another place is a teammate+// addressed as `link-<that place's key>-<its id there>`. Work handed to one is an assignment in this place's runtime+// whose turn the other place runs: `run` sends the hand-off and resolves with its result. The working side takes a+// hand-off once per assignment id, runs it as work of its own bot, and keeps its result until the requester has it. A+// hand-off, its result and its stop go only to the place they belong to.+//+// 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 { z } from "zod";++import { writeFileAtomic } from "../atomic.ts";+import type { CoordinateBotsCall, Coordinator, CoordinatorHost, HandoffView, HostTurnResult } from "../coordinator.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";++const FILE = "bot-link.json";+const ENDED_FILE = "bot-link-ended.json";+const DAY_MS = 24 * 60 * 60_000;+/** A result the requester has is kept this long, so the same hand-off sent again after a restart is answered from it. */+const KEEP_ACKED_MS = 7 * DAY_MS;+/** One never acknowledged is kept as long as the runtime keeps its row. */+const KEEP_RESULTS_MS = 30 * DAY_MS;+const KEEP_THREADS_MS = 30 * DAY_MS;+const RECORDS_MAX = 1_000;+/** While a hand-off runs in a place that is connected, its node is told it is alive this often; that place's own clocks+ * bound the work. While that place cannot be reached the node is held as `away` instead. */+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 GONE = "The result is no longer kept.";++const workSchema = z.object({+ /** The place it came from: its result goes there and nowhere else. */+ peer: z.string(),+ root: z.string(), from: z.string(), person: z.string().optional(), at: z.number(),+ /** The assignment here that does the work; its words are read from the runtime's own row. */+ child: z.string().optional(),+ done: z.object({ ok: z.boolean(), outcome: z.string().optional(), /** Kept only when no assignment here ran. */ text: z.string().optional() }).optional(),+ /** When the requester said it has the result. */+ ackedAt: z.number().optional(),+});+const peerSchema = z.object({+ place: placeSchema, bots: z.array(linkedBotSchema),+ /** On the Cloud: the one session that may use this computer's link. */+ sessionId: z.string().optional(),+ seenAt: z.number(),+});+const stateSchema = z.object({+ v: z.literal(2),+ /** `dialer`: a computer, which asks. `acceptor`: the Cloud, which answers. */+ role: z.enum(["dialer", "acceptor"]),+ self: placeSchema,+ /** dialer: the Cloud's address, this link's sign-in there, and the account it was made for. */+ origin: z.string().optional(), token: z.string().optional(), account: z.string().optional(),+ /** dialer: the Cloud is on a plan that sleeps, so it is asked only when it is known awake or there is work for it. */+ sleeps: z.boolean().optional(),+ peers: z.record(z.string(), peerSchema),+ /** Another place's thread names, each with the thread here its work runs in. */+ threads: z.record(z.string(), z.object({ threadId: z.string(), at: z.number() })),+ /** Hand-offs taken from another place, by assignment id. */+ work: z.record(z.string(), workSchema),+});+export type LinkState = z.infer<typeof stateSchema>;+type Work = z.infer<typeof workSchema>;+const endedSchema = z.array(z.object({ origin: z.string(), token: z.string(), at: z.number() })).max(10);+/** A link that was turned off while its Cloud could not be told: the Cloud is told when it can next be reached. */+export type EndedLink = z.infer<typeof endedSchema>[number];++interface LocalBot { id: string; name: string; color?: string; hidden?: boolean; title?: string; description?: string; movedTo?: unknown }++export interface BotLinkDeps {+ dataDir: string;+ coordinator(): Coordinator;+ bots(): readonly LocalBot[];+ bot(id: string): LocalBot | null | undefined;+ /** Why this bot takes no work now (it moved away, it is paused), or null. */+ refusal?(bot: LocalBot): string | null;+ model?(bot: LocalBot): string | undefined;+ level(bot: LocalBot): Level;+ /** Opens the thread another place's work runs in, and returns its id. */+ openThread(bot: LocalBot, title: string, opener: { botId: string; name: string; threadId: string }): string | undefined;+ hasThread(botId: string, threadId: string): boolean;+ 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 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. */+ kick(): void;+ /** On the Cloud: ends the session a computer's link used. */+ revoke?(sessionId: string): void;+ now?: () => number;+ log?(line: string): void;+}++export interface CoordinateContext {+ sender: LocalBot;+ address: { groupId?: string; threadId: string; botId: string };+ generation: string;+ parentId?: string;+ /** The caller is not one of this place's own turns. */+ external: boolean;+ handed(nodeId: string): void;+}+type CoordinateResult = { status: number; body: Record<string, unknown> };+type Remote = { peer: string; bot: LinkedBot };+type Live = { online: boolean; seq: number; outbox: Numbered[] };++export type BotLink = ReturnType<typeof createBotLink>;++export function createBotLink(deps: BotLinkDeps) {+ const now = deps.now ?? Date.now;+ const log = deps.log ?? (() => {});+ const file = join(deps.dataDir, FILE), endedFile = join(deps.dataDir, ENDED_FILE);+ let state: LinkState | null = null;+ try {+ const parsed = stateSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));+ state = parsed.success ? parsed.data : null;+ } catch { state = null; }++ const live = new Map<string, Live>();+ 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 };+ 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 = "";++ 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; };+ const isOnline = (peer: string) => live.get(peer)?.online === true;+ const placeName = (peer: string) => state?.peers[peer]?.place.name ?? "the other place";+ const directory = (): LinkedBot[] => deps.bots().filter((bot) => !bot.hidden && !bot.movedTo).map((bot) => ({+ id: bot.id, name: bot.name, ...(bot.title ? { title: bot.title.slice(0, 200) } : {}), ...(bot.description ? { description: bot.description.slice(0, 400) } : {}),+ ...(deps.model?.(bot) ? { model: deps.model(bot)!.slice(0, 200) } : {}), level: deps.level(bot),+ })).slice(0, 500);++ function send(peer: string, frame: Frame): void {+ if (!state?.peers[peer]) return;+ const one = linkOf(peer);+ one.outbox.push({ seq: ++one.seq, frame });+ for (const listener of outboundListeners) listener(peer);+ }+ const hello = (peer: string) => { if (state) { const bots = directory(); toldBots = JSON.stringify(bots); send(peer, { t: "hello", place: state.self, bots }); } };++ function setOnline(peer: string, next: boolean): void {+ const peerState = state?.peers[peer];+ if (!peerState) return;+ if (next && now() - peerState.seenAt > SEEN_WRITE_MS) { peerState.seenAt = now(); save(); }+ const one = linkOf(peer);+ if (one.online === next) return;+ one.online = next;+ deps.kick();+ }++ const remoteOf = (linked: string): Remote | undefined => {+ const address = parseLinked(linked), bot = address ? state?.peers[address.peer]?.bots.find((one) => one.id === address.botId) : undefined;+ return address && bot ? { peer: address.peer, bot } : undefined;+ };+ const fold = (value: string) => value.replace(/^@/u, "").replace(/[-_]+/gu, " ").replace(/\s+/gu, " ").trim().toLowerCase();+ /** The bot of another place `raw` names: by its address here, or by a name no bot here has and only one bot elsewhere has. */+ function resolve(raw: string): Remote | undefined {+ if (!state) return undefined;+ const wanted = raw.trim();+ if (isLinkedId(wanted)) return remoteOf(wanted);+ const local = deps.bots();+ if (local.some((bot) => bot.id === wanted)) return undefined;+ const named = fold(wanted);+ if (!named || local.some((bot) => !bot.hidden && fold(bot.name) === named)) return undefined;+ const matches = Object.entries(state.peers).flatMap(([peer, known]) => known.bots.filter((bot) => fold(bot.name) === named).map((bot) => ({ peer, bot })));+ return matches.length === 1 ? matches[0] : undefined;+ }++ const offlineNote = (peer: string) => `${placeName(peer)} is offline now (off, asleep or not connected), so this waits and is delivered when it is back`;++ function keepAlive(): void {+ if (pending.size === 0) { if (alive) { clearInterval(alive); alive = undefined; } return; }+ if (alive) return;+ alive = setInterval(() => { for (const entry of pending.values()) if (!entry.cancelled && isOnline(entry.peer)) deps.coordinator().progress(entry.threadId); }, ALIVE_EVERY_MS);+ alive.unref?.();+ }++ /** The requester's side of one hand-off: sent now and again at every new session until its result is here. */+ function runRemote(node: HandoffView, signal: AbortSignal): Promise<HostTurnResult> {+ const coordinator = deps.coordinator();+ const address = parseLinked(node.botId)!;+ const parent = node.parentId ? coordinator.node(node.parentId) : undefined;+ const sender = parent ? deps.bot(parent.botId) : undefined;+ const record = coordinator.status(node.id)?.assignment;+ const origin = record?.origin;+ const frame: HandoffFrame = {+ t: "handoff", id: node.id, to: address.botId,+ from: { botId: parent?.botId ?? "unknown", name: (sender?.name ?? "Teammate").slice(0, 120), threadId: parent?.threadId ?? node.threadId },+ thread: node.threadId, text: node.text.slice(0, BRIEF_MAX), mode: node.mode,+ origin: { kind: origin?.kind ?? "outside", ...(origin?.kind === "person" && origin.quote ? { quote: origin.quote.slice(0, 2_000) } : {}) },+ ...(parent && deps.personName(parent.threadId) ? { person: deps.personName(parent.threadId)!.slice(0, 120) } : {}),+ ...(record?.doneWhen ? { doneWhen: record.doneWhen.slice(0, 2_000) } : {}),+ };+ return new Promise<HostTurnResult>((settle) => {+ const entry: Pending = { peer: address.peer, frame, settle, threadId: node.threadId, cancelled: false };+ const abort = () => {+ if (entry.cancelled) return;+ entry.cancelled = true;+ send(entry.peer, { t: "cancel", id: node.id });+ settle({ ok: false, text: STOPPED });+ };+ pending.set(node.id, entry);+ keepAlive();+ if (signal.aborted) { abort(); return; }+ signal.addEventListener("abort", abort, { once: true });+ dispatch(entry);+ });+ }+ function dispatch(entry: Pending): void {+ if (!entry.cancelled) send(entry.peer, entry.frame);+ }++ /** A kept result as the frame its requester gets: the words come from the runtime's own row of the work. */+ function resultFrame(id: string, work: Work): ResultFrame | null {+ if (!work.done) return null;+ 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 } : {}) };+ }+ function dispatchResult(id: string): void {+ const work = state?.work[id], frame = work ? resultFrame(id, work) : null;+ if (work && frame) send(work.peer, frame);+ }++ /** The work ended here. `text` only when no assignment of this place holds the words. */+ function recordResult(id: string, result: { ok: boolean; outcome?: string; text?: string }, childId?: string): void {+ if (!state) return;+ const work = state.work[id];+ if (!work || work.done) return;+ if (childId) work.child = childId;+ work.done = { ok: result.ok, ...(result.outcome ? { outcome: result.outcome } : {}), ...(result.text !== undefined ? { text: result.text.slice(0, 2_000) } : {}) };+ save();+ dispatchResult(id);+ }++ /** The working side of one hand-off. A second arrival of the same id starts nothing: it is answered from the record. */+ function accept(peer: string, frame: HandoffFrame): void {+ if (!state) return;+ const known = state.work[frame.id];+ if (known) { if (known.peer === peer && known.done) dispatchResult(frame.id); return; }+ start(peer, frame);+ }++ function start(peer: string, frame: HandoffFrame): void {+ if (!state || state.work[frame.id]) return;+ const root = linkRoot(frame.id);+ const address = { botId: linkedId(peer, frame.from.botId), threadId: root };+ const work: Work = { peer, root, from: frame.from.name, ...(frame.person ? { person: frame.person } : {}), at: now() };+ const refuse = (text: string) => { state!.work[frame.id] = work; recordResult(frame.id, { ok: false, text, outcome: "refused" }); };+ const bot = deps.bot(frame.to);+ if (!bot || bot.hidden) return refuse("That bot is no longer here.");+ const refusal = deps.refusal?.(bot);+ if (refusal) return refuse(refusal);+ const coordinator = deps.coordinator();+ try {+ coordinator.beginTurn({ id: root, address, brief: frame.text, level: deps.level(bot), opener: {+ requester: { kind: "external_runtime", runId: root, botId: address.botId, threadId: address.threadId },+ origin: { kind: frame.origin.kind, source: frame.origin.kind === "routine" ? "routine" : "peer", ref: frame.from.threadId, ...(frame.origin.quote ? { quote: frame.origin.quote } : {}) },+ } });+ const key = `${peer}:${frame.thread}`;+ let threadId = state.threads[key]?.threadId;+ if (!threadId || !deps.hasThread(bot.id, threadId)) {+ const opened = deps.openThread(bot, `@${frame.from.name} · work`, { botId: address.botId, name: frame.from.name, threadId: address.threadId });+ if (!opened) throw new Error("That bot is no longer here.");+ threadId = opened;+ }+ 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 } : {}) });+ work.child = node.id;+ state.work[frame.id] = work;+ save();+ coordinator.endTurn(root, { ok: true, text: "" });+ if (frame.mode === "notify") recordResult(frame.id, { ok: true, text: "" });+ } catch (error) {+ const said = error instanceof Error ? error.message : String(error);+ try { coordinator.endTurn(root, { ok: false, text: said }); } catch { /* the root never began */ }+ refuse(said);+ }+ }++ function take(peer: string, frame: Frame): void {+ if (!state?.peers[peer]) return;+ switch (frame.t) {+ case "hello": {+ const known = state.peers[peer]!;+ // A computer is the place it paired as: its name may change, its identity may not.+ if (frame.place.id !== known.place.id) { log("bot link: a hello from another place than the one paired was dropped"); return; }+ if (JSON.stringify([frame.place, frame.bots]) !== JSON.stringify([known.place, known.bots])) { known.place = frame.place; known.bots = frame.bots; save(); deps.kick(); }+ return;+ }+ case "handoff": return accept(peer, frame);+ 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.") });+ return;+ }+ case "done": {+ const work = state.work[frame.id];+ if (work?.peer === peer && work.done && work.ackedAt === undefined) { work.ackedAt = now(); save(); }+ return;+ }+ case "cancel": {+ const work = state.work[frame.id];+ if (!work) { state.work[frame.id] = { peer, root: linkRoot(frame.id), from: "", at: now() }; recordResult(frame.id, { ok: false, text: STOPPED, outcome: "stopped" }); return; }+ if (work.peer !== peer) return;+ if (work.done) { dispatchResult(frame.id); return; }+ deps.coordinator().cancelDirect(work.root, `Stopped by ${work.from || "the requester"}`);+ return;+ }+ case "bye": return state.role === "acceptor" ? dropPeer(peer, `The link to ${placeName(peer)} was turned off before the work came back.`) : off(true);+ }+ }++ function prune(): void {+ if (!state) return;+ const at = now();+ let dropped = false;+ for (const [id, work] of Object.entries(state.work)) {+ if (work.done && (work.ackedAt !== undefined ? at - work.ackedAt > KEEP_ACKED_MS : at - work.at > KEEP_RESULTS_MS)) { delete state.work[id]; dropped = true; }+ }+ for (const [key, thread] of Object.entries(state.threads)) if (at - thread.at > KEEP_THREADS_MS) { delete state.threads[key]; dropped = true; }+ const oldest = <T extends { at: number }>(records: Record<string, T>, keep: (record: T) => boolean) => {+ const extra = Object.keys(records).length - RECORDS_MAX;+ if (extra <= 0) return;+ for (const [id] of Object.entries(records).filter(([, record]) => !keep(record)).sort(([, a], [, b]) => a.at - b.at).slice(0, extra)) { delete records[id]; dropped = true; }+ };+ oldest(state.work, (work) => !work.done);+ oldest(state.threads, () => false);+ if (dropped) save();+ }++ /** On the Cloud: a computer that has not asked for LINK_EXPIRES_MS is no longer linked. */+ function expire(): void {+ if (state?.role !== "acceptor") return;+ for (const [peer, known] of Object.entries(state.peers)) {+ if (isOnline(peer) || now() - known.seenAt <= LINK_EXPIRES_MS) continue;+ log(`bot link: ${known.place.name} has not connected for ${Math.round(LINK_EXPIRES_MS / DAY_MS)} days; its link ended`);+ dropPeer(peer, `${known.place.name} has not connected for ${Math.round(LINK_EXPIRES_MS / DAY_MS)} days, so the link to it ended and this was not done.`);+ }+ }++ function failPending(peer: string | null, reason: string): void {+ for (const [id, entry] of pending) {+ if (peer !== null && entry.peer !== peer) continue;+ pending.delete(id);+ resulted.add(id);+ if (!entry.cancelled) entry.settle({ ok: false, text: reason });+ }+ keepAlive();+ }++ /** On the Cloud: one computer's link ends. Its session is revoked and work waiting for it ends with the reason. */+ function dropPeer(peer: string, reason: string): void {+ const known = state?.peers[peer];+ if (!state || !known) return;+ delete state.peers[peer];+ live.delete(peer);+ if (known.sessionId) deps.revoke?.(known.sessionId);+ failPending(peer, reason);+ if (Object.keys(state.peers).length === 0) { off(true); return; }+ save();+ for (const listener of outboundListeners) listener(peer);+ deps.kick();+ }++ function readEnded(): EndedLink[] {+ try { const parsed = endedSchema.safeParse(JSON.parse(readFileSync(endedFile, "utf8"))); return parsed.success ? parsed.data.filter((one) => now() - one.at <= LINK_EXPIRES_MS) : []; } catch { return []; }+ }+ function writeEnded(ended: EndedLink[]): void {+ if (ended.length === 0) { rmSync(endedFile, { force: true }); return; }+ writeFileAtomic(endedFile, JSON.stringify(ended.slice(-10)), { mode: 0o600 });+ }++ /** The link is off here: nothing more is sent, and work waiting on another place ends with the reason. `told`: the other+ * side knows. A computer whose Cloud could not be told keeps what it takes to tell it later. */+ function off(told: boolean): void {+ if (!state) return;+ const was = state;+ state = null;+ try { rmSync(file, { force: true }); } catch (error) { log(`bot link: its record was not removed (${String(error)})`); }+ if (!told && was.role === "dialer" && was.origin && was.token) writeEnded([...readEnded().filter((one) => one.token !== was.token), { origin: was.origin, token: was.token, at: now() }]);+ 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();+ 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();+ }++ function receipt(remote: Remote, outcome: PeerDeliveryReceipt["outcome"], detail: string, more: Partial<PeerDeliveryReceipt> = {}): PeerDeliveryReceipt {+ return { botId: linkedId(remote.peer, remote.bot.id), botName: remote.bot.name, outcome, detail: detail.slice(0, 400), ...more };+ }++ /** coordinate_bots for targets that live in another place; the rest go on as they always did (`local`). */+ async function coordinate(call: CoordinateBotsCall, context: CoordinateContext, local: (call: CoordinateBotsCall) => Promise<CoordinateResult>): Promise<CoordinateResult> {+ if (!state || context.external) return local(call);+ const away = new Map<string, Remote>();+ for (const raw of call.botIds) { const remote = resolve(raw); if (remote) away.set(raw, remote); }+ if (away.size === 0) return local(call);+ const here = call.botIds.filter((raw) => !away.has(raw));+ const receipts: PeerDeliveryReceipt[] = [];+ const refused: string[] = [];+ const targets = [...new Map([...away.values()].map((remote) => [linkedId(remote.peer, remote.bot.id), remote])).values()];+ const mode = call.consult ? "consult" as const : call.reply === "none" ? "notify" as const : "work" as const;+ const coordinator = deps.coordinator();+ for (const remote of targets) {+ const place = placeName(remote.peer), linked = linkedId(remote.peer, remote.bot.id);+ const unsupported = unsupportedHere(call, context, place);+ if (unsupported) { refused.push(unsupported); receipts.push(receipt(remote, "failed", unsupported)); continue; }+ const threadId = `${linked}:${call.thread === "new" ? `${context.generation}:${receipts.length}` : context.address.threadId}`;+ try {+ 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." : "";+ 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}`+ : online ? `sent to ${remote.bot.name} on ${place}; ${returns}.${files}` : `${offlineNote(remote.peer)}; ${returns} then. Finish your turn and tell the person it waits for ${place}.${files}`,+ { requestId: node.id }));+ if (!online) for (const listener of wantedListeners) listener();+ if (!duplicate) {+ context.handed(node.id);+ deps.sentRow({ sender: context.sender, threadId: context.address.threadId, recipient: { id: linked, name: `${remote.bot.name} (${place})` }, workThreadId: threadId, nodeId: node.id,+ ...(call.reason ? { reason: call.reason } : {}), ...(call.doneWhen ? { doneWhen: call.doneWhen } : {}) });+ }+ } catch (error) {+ const said = error instanceof Error ? error.message : String(error);+ refused.push(said);+ receipts.push(receipt(remote, "failed", said));+ }+ }+ const sent = refused.length < receipts.length;+ const mine = sent ? `Handed to the person's other place. ${call.reply === "none" ? "Nothing comes back from a one-way notice." : "Finish your turn now: the result resumes you when it is back."}` : "";+ if (here.length === 0) return { status: sent ? 200 : 409, body: { receipts, ...(sent ? { message: mine } : { error: refused.join("; ") }) } };+ const rest = await local({ ...call, botIds: here });+ const theirs = Array.isArray(rest.body.receipts) ? rest.body.receipts as PeerDeliveryReceipt[] : [];+ const ok = sent || rest.status === 200;+ const errors = [...refused, ...(typeof rest.body.error === "string" ? [rest.body.error] : [])];+ return { status: ok ? 200 : rest.status, body: { ...rest.body, receipts: [...receipts, ...theirs],+ ...(ok ? { message: [mine, rest.body.message].filter(Boolean).join(" "), ...(errors.length ? { notSent: errors.join("; ") } : {}) } : { error: errors.join("; ") }) } };+ }+ /** Why this call cannot go to another place at all, or null. */+ function unsupportedHere(call: CoordinateBotsCall, context: CoordinateContext, place: string): string | null {+ return call.groupId || context.address.groupId ? `Work in a room does not reach ${place} yet: hand it to the bot directly, from your own conversation`+ : call.answers || call.post || call.ownThread ? `That does not reach ${place} yet: send the bot plain work or a question instead`+ : call.consult && call.reply === "none" ? "consult asks a question whose answer comes back to you; leave reply out" : null;+ }+ /** The coordinator's host with other places' bots in it: their nodes run there, every other node as before. */+ function host(inner: CoordinatorHost): CoordinatorHost {+ const awayNode = (node: HandoffView) => isLinkedId(node.botId);+ const peerOf = (node: HandoffView) => parseLinked(node.botId)?.peer ?? "";+ const workOf = (parent: HandoffView | undefined) => (parent && awayNode(parent) ? state?.work[handoffOfRoot(parent.id)] : undefined);+ const nameOf = (linked: string) => { const remote = remoteOf(linked); return remote ? `${remote.bot.name} (${placeName(remote.peer)})` : "Teammate"; };+ return {+ ...inner,+ validate: (node, parent) => {+ if (!awayNode(node)) return inner.validate(node, parent && awayNode(parent) ? undefined : parent);+ if (!node.parentId) return undefined;+ if (!state) return "The link to the person's other place was turned off, so this was not delivered.";+ return remoteOf(node.botId) ? undefined : "That bot's place is no longer linked, or the bot is no longer there.";+ },+ busy: (node) => (awayNode(node) ? !isOnline(peerOf(node)) : inner.busy(node)),+ holdReason: (node) => (awayNode(node) ? offlineNote(peerOf(node)) : inner.holdReason?.(node) as string),+ // Work for a place that cannot be reached, waiting to go or already running there, is held by no clock.+ away: (node) => (awayNode(node) ? Boolean(state) && Boolean(node.parentId) && !isOnline(peerOf(node)) : inner.away?.(node) ?? false),+ run: (node, resumed, signal, composed) => {+ if (!awayNode(node)) return inner.run(node, resumed, signal, composed);+ if (!node.parentId) return Promise.resolve({ ok: true, text: "" });+ return runRemote(node, signal);+ },+ report: (child, parent) => {+ if (awayNode(child)) {+ // It ended here without its result (cut by restarts, refused, failed): the place that runs it is told to stop.+ if (child.parentId && !resulted.delete(child.id) && child.status !== "completed") send(peerOf(child), { t: "cancel", id: child.id });+ if (!parent || child.mode === "notify") return;+ deps.resultRow(parent, child, nameOf(child.botId));+ return;+ }+ inner.report(child, parent);+ if (parent && awayNode(parent) && state?.work[handoffOfRoot(parent.id)]) {+ recordResult(handoffOfRoot(parent.id), { ok: child.status === "completed", ...(child.outcome ? { outcome: child.outcome } : {}) }, child.id);+ }+ },+ names: (node, parent) => {+ if (awayNode(node)) return { requester: (parent && deps.bot(parent.botId)?.name) || "Teammate", assignee: nameOf(node.botId) };+ const work = workOf(parent);+ if (!work) return inner.names(node, parent);+ const { thread: _thread, ...names } = inner.names(node);+ return { ...names, requester: `${work.from} (${placeName(work.peer)})`, ...(work.person ? { person: work.person } : {}) };+ },+ park: (node, question, restored) => { if (!awayNode(node)) inner.park(node, question, restored); },+ remind: (node, closesAt) => { if (!awayNode(node)) inner.remind?.(node, closesAt); },+ levelOf: (target, source) => (isLinkedId(target.botId) ? { level: remoteOf(target.botId)?.bot.level ?? "full" } : inner.levelOf(target, source)),+ chiefOf: (address) => (isLinkedId(address.botId) ? false : inner.chiefOf(address)),+ outward: (node) => (awayNode(node) ? [] : inner.outward?.(node) ?? []),+ shareAnswer: (first, joiner) => (awayNode(first) || awayNode(joiner) ? false : inner.shareAnswer?.(first, joiner) ?? false),+ statusReply: (requester, prompt, signal) => (isLinkedId(requester) ? Promise.resolve(undefined) : inner.statusReply?.(requester, prompt, signal) ?? Promise.resolve(undefined)),+ };+ }++ const cloudPeer = () => (state?.role === "dialer" ? Object.keys(state.peers)[0] ?? null : null);++ return {+ host, coordinate, resolve,+ on: () => state !== null,+ /** This place is linked here now. */+ has: (peer: string) => Boolean(state?.peers[peer]),+ /** One place is connected, or (with no place named) any is. */+ online: (peer?: string) => (peer === undefined ? [...live.values()].some((one) => one.online) : isOnline(peer)),+ role: () => state?.role ?? null,+ /** On a computer: its one link's other end. */+ cloudPeer,+ /** For the transport: where to ask, and as whom. */+ dial: () => (state?.role === "dialer" && state.origin && state.token ? { origin: state.origin, token: state.token } : null),+ /** On the Cloud: the computer whose link this session is. */+ peerOfSession: (sessionId: string) => (state?.role === "acceptor" ? Object.entries(state.peers).find(([, known]) => known.sessionId === sessionId)?.[0] ?? null : null),+ status: () => (state ? { on: true as const, role: state.role, online: [...live.values()].some((one) => one.online), self: state.self,+ ...(state.role === "dialer" ? { origin: state.origin ?? null, account: state.account ?? null, peer: Object.values(state.peers)[0]?.place ?? null } : {}),+ peers: Object.entries(state.peers).map(([peer, known]) => ({ ...known.place, online: isOnline(peer), bots: known.bots.length })),+ bots: Object.values(state.peers).reduce((sum, known) => sum + known.bots.length, 0), waiting: pending.size }+ : (() => { const ended = [...new Set(readEnded().map((one) => one.origin))]; return { on: false as const, ...(ended.length ? { ended } : {}) }; })()),+ /** Other places' bots as list_bots names them. */+ agents: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), name: bot.name, section: "", model: bot.model ?? "", busy: false,+ status: isOnline(peer) ? "linked" : "offline", statusText: isOnline(peer) ? `on ${known.place.name}` : `on ${known.place.name}, offline now: work for it waits until it is back`,+ title: bot.title || undefined, description: bot.description || undefined }))),+ /** Turned on, on a computer: it keeps the Cloud's address, its sign-in there and the account that was for. */+ turnOn(input: { self: Place; origin: string; token: string; account?: string; peer: Place }): void {+ const key = peerKey(input.peer.id);+ const kept = state?.role === "dialer" && state.origin === input.origin && state.peers[key] ? state : null;+ if (state && !kept) off(false);+ state = { v: 2, role: "dialer", self: input.self, origin: input.origin, token: input.token, ...(input.account ? { account: input.account } : {}), ...(kept?.sleeps ? { sleeps: true } : {}),+ peers: { [key]: { place: input.peer, bots: kept?.peers[key]?.bots ?? [], seenAt: now() } }, threads: kept?.threads ?? {}, work: kept?.work ?? {} };+ save();+ deps.kick();+ },+ /** On the Cloud: one computer is paired. The session its link used before is returned, for the caller to end; other+ * computers' links are left as they are. Null when no more computers fit. */+ pair(input: { self: Place; sessionId: string; computer: Place }): { peer: string; replaced?: string } | null {+ const key = peerKey(input.computer.id);+ const known = state?.role === "acceptor" ? state.peers[key] : undefined;+ if (!known && state?.role === "acceptor" && Object.keys(state.peers).length >= PEERS_MAX) return null;+ if (state?.role !== "acceptor") state = { v: 2, role: "acceptor", self: input.self, peers: {}, threads: {}, work: {} };+ state.self = input.self;+ state.peers[key] = { place: input.computer, bots: known?.place.id === input.computer.id ? known.bots : [], sessionId: input.sessionId, seenAt: now() };+ save();+ deps.kick();+ return { peer: key, ...(known?.sessionId ? { replaced: known.sessionId } : {}) };+ },+ /** On the Cloud: one computer's link ends (all of them when none is named). */+ unpair(computerId?: string): void {+ if (state?.role !== "acceptor") return;+ const reason = "The link to that computer was turned off before the work came back.";+ for (const peer of computerId === undefined ? Object.keys(state.peers) : [peerKey(computerId)]) dropPeer(peer, reason);+ },+ /** Turned off on a computer. `told`: its Cloud knows; otherwise the Cloud is told when it can next be reached. */+ turnOff(told: boolean): void { off(told); },+ ended: readEnded,+ /** These ended links' Clouds know now. */+ forgetEnded(tokens: readonly string[]): void { writeEnded(readEnded().filter((one) => !tokens.includes(one.token))); },+ /** A session with a place began: each side sends again what the other has not acknowledged. */+ sessionStarted(peer: string): void {+ if (!state?.peers[peer]) return;+ linkOf(peer).outbox = [];+ prune();+ hello(peer);+ for (const [id, entry] of pending) { if (entry.peer !== peer) continue; if (entry.cancelled) send(peer, { t: "cancel", id }); else dispatch(entry); }+ 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(); },+ /** 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,+ /** 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) {+ const parsed = frameSchema.safeParse(raw);+ if (!parsed.success) { log("bot link: a frame that did not parse was dropped"); continue; }+ try { take(peer, parsed.data); } catch (error) { log(`bot link: ${parsed.data.t} failed (${String(error)})`); }+ }+ },+ /** What waits to go to a place, after `ack` (frames up to it were taken and are dropped), as much as one exchange carries. */+ outgoing(peer: string, ack: number): Numbered[] {+ const one = live.get(peer);+ if (!one) return [];+ one.outbox = one.outbox.filter((entry) => entry.seq > ack);+ const taken: Numbered[] = [];+ let bytes = 0;+ for (const entry of one.outbox) {+ bytes += JSON.stringify(entry.frame).length;+ if (taken.length > 0 && (bytes > EXCHANGE_BYTES || taken.length >= 500)) break;+ taken.push(entry);+ }+ return taken;+ },+ hasOutgoing: (peer: string, ack = 0) => live.get(peer)?.outbox.some((entry) => entry.seq > ack) === true,+ onOutgoing(listener: (peer: string) => void): () => void { outboundListeners.add(listener); return () => outboundListeners.delete(listener); },+ /** Work was handed to a place that is not connected: a computer asks its Cloud for it now. */+ 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(); },+ };+}diff --git a/server/bot-link/protocol.ts b/server/bot-link/protocol.tsnew file mode 100644index 0000000000..7ca9fd0a7f--- /dev/null+++ b/server/bot-link/protocol.ts@@ -0,0 +1,80 @@+// What crosses the link between a person's computer and their Cloud (server/bot-link/link.ts). Every frame may arrive+// twice: a hand-off and its result carry the assignment's id, and the receiving side acts on an id once.+import { createHash } from "node:crypto";+import { z } from "zod";++/** A bot of another place is addressed here as `link-<that place's key>-<its id there>`, so the same id in two places,+ * or on two computers, is as many bots. The key is cut from the place's own identity. */+export const LINK_PREFIX = "link-";+const ADDRESS = /^link-([0-9a-f]{8})-(.+)$/su;+export const peerKey = (placeId: string): string => createHash("sha256").update(placeId).digest("hex").slice(0, 8);+export const linkedId = (peer: string, botId: string): string => `${LINK_PREFIX}${peer}-${botId}`;+export const isLinkedId = (botId: string | undefined): botId is string => typeof botId === "string" && botId.startsWith(LINK_PREFIX);+export const parseLinked = (linked: string): { peer: string; botId: string } | null => { const found = ADDRESS.exec(linked); return found ? { peer: found[1]!, botId: found[2]! } : null; };+/** The root that stands for a hand-off taken from another place, and the hand-off's id behind such a root. */+export const linkRoot = (handoffId: string): string => `${LINK_PREFIX}${handoffId}`;+export const handoffOfRoot = (rootId: string): string => rootId.slice(LINK_PREFIX.length);++export const SYNC_PATH = "/api/bot-link/sync";+export const PAIR_PATH = "/api/bot-link/pair";+export const STATE_PATH = "/api/bot-link";+/** 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. */+export const SEEN_MS = HOLD_MS + 20_000;+/** A link the computer has not used for this long ends on the Cloud: its sign-in is revoked and work waiting for it fails. */+export const LINK_EXPIRES_MS = 30 * 24 * 60 * 60_000;+/** One exchange carries about this much; what is left goes with the next. */+export const EXCHANGE_BYTES = 1_500_000;+/** Computers one Cloud links at a time. */+export const PEERS_MAX = 10;+export const BRIEF_MAX = 12_000;+const RESULT_MAX = 200_000;++const id = z.string().min(1).max(200);+const name = z.string().trim().min(1).max(120);+export const placeSchema = z.object({ id, name }).strict();+export type Place = z.infer<typeof placeSchema>;++const level = z.enum(["ask", "edits", "auto", "full", "custom"]);+export const linkedBotSchema = z.object({+ id, name, title: z.string().max(200).optional(), description: z.string().max(400).optional(), model: z.string().max(200).optional(), level: level.optional(),+}).strict();+export type LinkedBot = z.infer<typeof linkedBotSchema>;++const handoff = z.object({+ t: z.literal("handoff"), id, to: id,+ from: z.object({ botId: id, name, threadId: id }).strict(),+ /** The requester's name for the thread the work runs in: the same one continues the same thread on the working side. */+ thread: id,+ text: z.string().max(BRIEF_MAX),+ mode: z.enum(["work", "consult", "notify"]),+ 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(),+}).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("done"), id }).strict(),+ z.object({ t: z.literal("cancel"), id }).strict(),+ z.object({ t: z.literal("bye") }).strict(),+]);+export type Frame = z.infer<typeof frameSchema>;+export type ResultFrame = Extract<Frame, { t: "result" }>;++export const numbered = z.object({ seq: z.number().int().positive(), frame: z.unknown() }).strict();+export type Numbered = { seq: number; frame: Frame };++export const syncRequest = z.object({+ /** The computer starts a new session: each side sends again what the other has not acknowledged. */+ fresh: z.boolean().optional(),+ /** The highest frame of the Cloud's this computer has taken. */+ ack: z.number().int().nonnegative(),+ frames: z.array(z.unknown()).max(500),+ wait: z.number().int().min(0).max(HOLD_MS),+}).strict();+export const syncAnswer = z.object({ session: z.string().min(1).max(80), frames: z.array(numbered).max(2_000) }).strict();diff --git a/server/cloud-power.ts b/server/cloud-power.tsindex f1fae37b7f..add547ecc8 100644--- a/server/cloud-power.ts+++ b/server/cloud-power.ts@@ -75,7 +75,7 @@ export const CLOUD_BACKGROUND_HEADER = "x-omb-background";export const CLOUD_POWER_HEADER = "x-omb-cloud-power";const MARKER = "cloud-sleep.json";/** Long-polls and streams that stay open by design: never "in flight" work. */-const HELD = [/^\/api\/events$/, /^\/api\/sync\/changes$/, /^\/api\/shared-computers\/asks$/, /^\/api\/shared-computers\/[\w-]+\/(?:poll|link)$/];+const HELD = [/^\/api\/events$/, /^\/api\/sync\/changes$/, /^\/api\/shared-computers\/asks$/, /^\/api\/shared-computers\/[\w-]+\/(?:poll|link)$/, /^\/api\/bot-link\/sync$/];/** The answer a held poll (Files sync, lending) gets once the home agreed to sleep: the desktop pauses until it wakes. */export function answerAsleep(res: ServerResponse, json: (res: ServerResponse, status: number, body: unknown) => void) {diff --git a/server/coordinator.ts b/server/coordinator.tsindex f6543151cb..018d529a88 100644--- a/server/coordinator.ts+++ b/server/coordinator.ts@@ -162,6 +162,8 @@ export interface CoordinatorHost {chiefOf(address: RoomAddress): boolean;/** What the cut turn already did outward (sent, posted, paid): a turn that acted outward is not run again. */outward?(node: HandoffView): string[];+ /** The node's bot lives in a place that cannot be reached now: its queued work waits without a clock (runtime `away`). */+ away?(node: HandoffView): boolean;/** Whether `joiner`'s requester may read the answer `first` gives its own (the same people see both conversations),* so the same request from two teammates is answered once. Absent: never. */shareAnswer?(first: HandoffView, joiner: HandoffView): boolean;diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.tsnew file mode 100644index 0000000000..53238c5bf5--- /dev/null+++ b/server/host/bot-link-host.ts@@ -0,0 +1,80 @@+// 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 { createDialer } from "../bot-link/dial.ts";+import { createBotLink } from "../bot-link/link.ts";+import type { Coordinator, HandoffView } from "../coordinator.ts";+import { redactSecretsInText } from "../redact.ts";+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 { sentRow, teammateResultRow } from "./handoff-sent.ts";++export interface BotLinkHostDeps {+ dataDir: string;+ environmentId: string;+ store: Pick<Store, "bots" | "bot" | "createTask" | "taskByThread" | "appendMessage" | "patchTask" | "onChange">;+ coordinator(): Coordinator;+ kick(): void;+ level(bot: BotRecord): Level;+ refusal(bot: BotRecord): string | null;+ language(threadId: string): string | undefined;+ personName(threadId: string): string | undefined;+ sessions: { issue(input: { label: string; scopes: Array<"admin" | "client">; email?: string; userId?: string }): { token: string; session: { id: string } }; revoke(id: string): boolean };+ local(auth: RequestAuth): boolean;+ owner(auth: RequestAuth): boolean;+ power(): { sleeping(): boolean; sleepSignal(): AbortSignal } | null | undefined;+ log(line: string): void;+}++export function createBotLinkHost(deps: BotLinkHostDeps) {+ const { store } = deps;+ const link = createBotLink({+ dataDir: deps.dataDir, coordinator: deps.coordinator, kick: deps.kick, log: deps.log, revoke: (sessionId) => { deps.sessions.revoke(sessionId); },+ bots: () => store.bots, bot: (id) => store.bot(id),+ refusal: (bot) => deps.refusal(bot as BotRecord),+ model: (bot) => (bot as BotRecord).modelSelection.model,+ level: (bot) => deps.level(bot as BotRecord),+ 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 }) => {+ 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) } : {}) }));+ },+ 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" },+ 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(); }); };+ 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.+ issue: (auth, label, computerId) => {+ const issued = deps.sessions.issue({ label, scopes: [...auth.scopes], userId: linkSessionUser(computerId), ...(auth.kind === "session" && auth.session.email ? { email: auth.session.email } : {}) });+ 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. */+ start(): void {+ 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(); },+ };+}diff --git a/server/host/room-access.ts b/server/host/room-access.tsindex cf4a690cbd..9f05051f97 100644--- a/server/host/room-access.ts+++ b/server/host/room-access.ts@@ -1,3 +1,4 @@+import { isLinkedId } from "../bot-link/protocol.ts";import type { HandoffView, RoomAddress } from "../coordinator.ts";import { peerAllowed, reachRefusal, type LookedAfterBy } from "../peer-roster.ts";import type { BotRecord, GroupRecord, Store } from "../store.ts";@@ -55,7 +56,8 @@ export function createRoomAccess({ store, privateTo = () => null, lookedAfterBy,const laneThread = laneRoomThread(node);const laneRoom = laneThread ? store.groupByThread(laneThread) : undefined;if (laneRoom && !laneRoom.dm && !laneRoom.memberIds.includes(bot.id)) return LEFT_THE_ROOM;- if (parent) {+ // Work the person's other place handed over the link has no sender here to check: the link itself admits it.+ if (parent && !isLinkedId(parent.botId)) {const from = store.bot(parent.botId);const source = parent.groupId ? store.group(parent.groupId) : undefined;if (!from || from.hidden || (parent.groupId ? !source || !source.memberIds.includes(from.id) || !store.groupTaskByThread(source.id, parent.threadId) : !store.taskByThread(from.id, parent.threadId))) return "Source membership or task was removed";diff --git a/server/index.ts b/server/index.tsindex 7fdedac0ea..b6b77b9d1f 100644--- a/server/index.ts+++ b/server/index.ts@@ -584,7 +584,7 @@ import { PhoneSecretBridge, PhoneSecretSubmissionRegistry } from "./phone-secret// Keep these two last, so loading the route table leaves module start-up order as is.import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.ts";import { holdBodyDeadline } from "./body-deadline.ts";-import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";+import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createBotLinkHost } from "./host/bot-link-host.ts"; import { isBotLinkHeldPath, linkSessionRefusal } from "./routes/bot-link.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, botMoveRefusal, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";import { createHostedSlackRoutes } from "./routes/hosted-slack.ts";import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerStore, workspaceBannerSummary } from "./routes/workspace-banner.ts";import { createBotMemoryRoutes } from "./routes/bot-memory.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 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, 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),@@ -3916,7 +3916,7 @@ const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoorstandingThreadOf: botId => botMainThread(botId) ?? store.bot(botId)?.threadId,botOfThread: threadId => store.botByThread(threadId)?.id,},- host: { holdReason: (node) => queuedStatus(node), statusReply: (requester, prompt, signal) => sideJobs.text("status-reply", requester)?.generateText(prompt, { signal, timeoutMs: STATUS_REPLY_TIMEOUT_MS }) ?? Promise.resolve(undefined),+ host: botLink.link.host({ holdReason: (node) => queuedStatus(node), statusReply: (requester, prompt, signal) => sideJobs.text("status-reply", requester)?.generateText(prompt, { signal, timeoutMs: STATUS_REPLY_TIMEOUT_MS }) ?? Promise.resolve(undefined),validate: (node, parent) => node.mode === "notify" && node.status !== "queued" ? undefined: !node.parentId && node.groupId ? roomRootProblem(node): roomHandoffProblem(node, parent),@@ -4102,7 +4102,7 @@ const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoor},shareAnswer: createShareAnswer({ askedFrom: (node) => (node.parentId ? coordinator.node(node.parentId)?.threadId : undefined), audienceOf: teamHost.audienceOf, pinned: (botId, threadId) => store.taskByThread(botId, threadId)?.cwd, botFolder: (botId) => store.bot(botId)?.cwd, privateFolders: TASK_WORKSPACES_DIR }),joined: (node) => { store.appendMessage(node.threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${serverLine(threadLanguage(node.threadId), "server.teammates.sameRequest")}`, ok: true } }); },- },+ }),});threadsAwaitingTeammates = () => coordinator.awaitingTeammateThreads();const groupUsageReader = new GroupUsageReader(DATA_DIR); const chiefRooms = createChiefRooms({ store, updateRoom: updateChannel, published: (group) => broadcast({ kind: "group", group: publicGroupState(group) }) });@@ -12662,7 +12662,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {companionMutationToken,features: { sharedComputers: lendingEnabled() },loopbackTrust: LOOPBACK.trust,- cliOwnerToken, trustLocalBrowser: LOOPBACK.localBrowsers, ...(CLOUD_TEAM ? { restricted: moveInRefusal } : {}), scopeRefusal: (m, p) => liveScopeRefusal(cfg, m, p),+ cliOwnerToken, trustLocalBrowser: LOOPBACK.localBrowsers, restricted: (session, m, p, u) => linkSessionRefusal(session, m, p) ?? (CLOUD_TEAM ? moveInRefusal(session, m, p, u) : null), scopeRefusal: (m, p) => liveScopeRefusal(cfg, m, p),});// The session term slides on use, so re-issue the cookie on every cookie request; handlers that clear it later overwrite this header.if (gate.auth?.kind === "session" && gate.auth.via === "cookie") {@@ -12704,7 +12704,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (await workspaceBackupRoutes(req, res, path, auth)) return;if (cloudMoveRoutes(res, path)) return;// Count requests until their handler returns, not until the browser disconnects: a cancelled upload can still write.- if (path.startsWith("/api/") && path !== "/api/events" && path !== "/api/health" && path !== "/api/sync/changes" && !isLongPollPath(path) && !isWorkspaceBackupSessionControl(method, path)) {+ if (path.startsWith("/api/") && path !== "/api/events" && path !== "/api/health" && path !== "/api/sync/changes" && !isLongPollPath(path) && !isBotLinkHeldPath(path) && !isWorkspaceBackupSessionControl(method, path)) {releaseWorkspaceRequest = workspaceMaintenance.request();}@@ -13175,7 +13175,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {description: b.description || undefined,};});- return json(res, 200, { bots });+ return json(res, 200, { bots: [...bots, ...botLink.link.agents()] });}if (await dispatchRoutes([createInternalThreadRoutes({store, coordinator, from: internalSender, fromThreadId: internalCapability.threadId,@@ -13632,7 +13632,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {});}const EXTERNAL = internalCapability.generation === EXTERNAL_RUNTIME_GENERATION;- const coordinateBots = async (call: CoordinateBotsCall): Promise<{ status: number; body: Record<string, unknown> }> => {+ const coordinateHere = async (call: CoordinateBotsCall): Promise<{ status: number; body: Record<string, unknown> }> => {const refuse = (status: number, error: string, more: Record<string, unknown> = {}) => ({ status, body: { error, ...more } });const source = store.groupByThread(internalCapability.threadId);if (source && (source.dm || !source.memberIds.includes(internalSender.id))) {@@ -13775,7 +13775,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const message = coordinateResultMessage(reply, answeredOnly);return { status: sent ? 200 : 409, body: { receipts, ...(sent ? { message: lead ? `${lead} ${message}` : message } : { error: refused.join("; ") }),...(EXTERNAL && sent ? { rootId: generation } : {}) } };- };+ }, coordinateBots = (call: CoordinateBotsCall) => botLink.link.coordinate(call, { sender: internalSender, address: { groupId: store.groupByThread(internalCapability.threadId)?.id, threadId: internalCapability.threadId, botId: internalSender.id }, generation: internalCapability.generation, parentId: internalCapability.roomHandoffId, external: EXTERNAL, handed: delegatedThisTurn }, coordinateHere);if (method === "GET" && path === "/api/internal/assignment-status") {const id = url.searchParams.get("id")?.trim() ?? "";const fromThreadId = internalCapability.threadId;@@ -15303,7 +15303,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAliveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt()].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },maintenance: () => workspaceMaintenance.active || providerFleetReloading || providerAuthSessions.active || browserEngineInstall !== null } }));-let pausedSent = starterAwake.paused().join(); store.onChange((change) => { if (change.type === "bot.deleted") botHolds.forget("bot", change.botId); if (change.type !== "bot" && change.type !== "bot.deleted") return; const paused = starterAwake.paused().join(); if (paused !== pausedSent) { pausedSent = paused; broadcast({ kind: "config", ...configStatus() }); } });+botLink.start(); let pausedSent = starterAwake.paused().join(); store.onChange((change) => { if (change.type === "bot.deleted") botHolds.forget("bot", change.botId); if (change.type !== "bot" && change.type !== "bot.deleted") return; const paused = starterAwake.paused().join(); if (paused !== pausedSent) { pausedSent = paused; broadcast({ kind: "config", ...configStatus() }); } });server.listen(PORT, listenHost(server), async () => {companyRuntimeReady(); cloudHealth?.speed.ready(); void tailnetShare.start(process.env);console.log(`openmausbot server on http://127.0.0.1:${PORT}`);@@ -15369,7 +15369,7 @@ const gracefulShutdown = createGracefulShutdown({followupsReady = false;companyShutdown = true;// Before any provider is torn down, so what the teardown fails stays cut for the next start.- coordinator.close();+ coordinator.close(); botLink.close();noteTurnsCutByShutdown();if (workspaceAccessTimer) clearInterval(workspaceAccessTimer);// Invalidate turn bearers before any cleanup reaches an await: child MCP processes and the listener may outlive it.diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.tsnew file mode 100644index 0000000000..006ef0de9b--- /dev/null+++ b/server/routes/bot-link.ts@@ -0,0 +1,159 @@+// The routes of the link between a person's computers and their Cloud (server/bot-link/link.ts).+//+// On a computer, /api/bot-link is the one switch, for the app on that computer alone: on (with the Cloud's address, the+// account, and the sign-in the Cloud gave this link), off, and the app's word on whether a Cloud that sleeps is awake.+// On the Cloud, /api/bot-link/pair is asked once by the app over the person's own sign-in there and answers with a+// sign-in for that computer's link alone; /api/bot-link/sync is the standing exchange, taken only from that sign-in.+//+// Security: pairing needs the owner's session on a place that is one person's own (never a team's or a shared server).+// 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 type { ServerResponse } from "node:http";+import { randomUUID } from "node:crypto";+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 { answerAsleep } from "../cloud-power.ts";+import type { RequestAuth } from "../request-auth.ts";+import { PASS, type RouteHandler } from "./table.ts";++const name = z.string().trim().min(1).max(120);+const origin = z.string().max(300).regex(/^https?:\/\/[^/\s]+$/u);+const switchBody = z.union([+ z.object({ on: z.literal(true), origin, token: z.string().min(16).max(512), name, cloud: placeSchema, account: z.string().max(200).optional() }).strict(),+ z.object({ on: z.literal(false) }).strict(),+ z.object({ cloud: z.enum(["asleep", "awake"]), origin }).strict(),+]);+const pairBody = z.object({ computer: placeSchema, name }).strict();++const loopbackHost = (value: string) => /^(?:localhost|127\.0\.0\.1|\[::1\])$/u.test(new URL(value).hostname);++/** What marks a session as one computer's link, in the session's `userId`. */+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 }];+/** 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;+ return LINK_ROUTES.some((route) => route.method === method && route.path === path) ? null : "This sign-in is only for the link between a computer and its Cloud.";+}+/** The standing exchange stays open by design: it is never a request a backup, a restore or an update waits out. */+export const isBotLinkHeldPath = (path: string): boolean => path === SYNC_PATH;++export interface BotLinkRouteDeps {+ link: BotLink;+ dialer: ReturnType<typeof createDialer>;+ /** This server's own identity. */+ environmentId: string;+ /** The app on this computer: the only caller of the switch. */+ local(auth: RequestAuth): boolean;+ /** This place is one person's own Cloud or server, and `auth` is that person's session. */+ owner(auth: RequestAuth): boolean;+ /** A sign-in for one computer's link alone, as the same person. */+ issue(auth: RequestAuth, label: string, computerId: string): { token: string; sessionId: string };+ revoke(sessionId: string): void;+ power(): { sleeping(): boolean; sleepSignal(): AbortSignal } | null | undefined;+ /** The link was turned on here. */+ turnedOn?(): void;+ seenMs?: number;+}++export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {+ const { link, dialer } = deps;+ const session = randomUUID();+ const held = new Map<string, () => void>();+ const gone = new Map<string, NodeJS.Timeout>();+ const seen = (peer: string) => {+ link.setOnline(peer, true);+ clearTimeout(gone.get(peer));+ const timer = setTimeout(() => { gone.delete(peer); link.setOnline(peer, false); }, deps.seenMs ?? SEEN_MS);+ timer.unref?.();+ gone.set(peer, timer);+ };+ /** Until the link has something to send, the wait ends, the computer hangs up or asks again, or the Cloud goes to sleep. */+ const hold = (res: ServerResponse, peer: string, ack: number, wait: number, sleep: AbortSignal | undefined) => new Promise<void>((resolve) => {+ held.get(peer)?.();+ const done = () => { clearTimeout(timer); stop(); res.off("close", done); sleep?.removeEventListener("abort", done); if (held.get(peer) === done) held.delete(peer); resolve(); };+ const timer = setTimeout(done, wait);+ const stop = link.onOutgoing((changed) => { if (changed === peer && (!link.has(peer) || link.hasOutgoing(peer, ack))) done(); });+ res.on("close", done);+ sleep?.addEventListener("abort", done, { once: true });+ held.set(peer, done);+ });+ 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;+ res.setHeader("cache-control", "no-store");++ if (path === STATE_PATH) {+ if (!deps.local(auth)) { req.resume(); return json(res, 403, { error: "Only the app on this computer can turn the link to the Cloud on or off." }); }+ if (method === "GET") return json(res, 200, state());+ if (method !== "PUT") { req.resume(); return json(res, 405, { error: "method not allowed" }); }+ const body = switchBody.safeParse(await readBody(req, 16 * 1024));+ if (!body.success) return json(res, 400, { error: "send { on: true, origin, token, name, cloud: { id, name } }, { on: false } or { cloud: \"asleep\" | \"awake\", origin }" });+ if (!("on" in body.data)) {+ // The word is one Cloud's: a link to another Cloud is not told it.+ if (body.data.cloud === "awake") await dialer.tellEnded(body.data.origin);+ if (link.role() === "dialer" && link.dial()?.origin === body.data.origin) { if (body.data.cloud === "asleep") dialer.sleep(); else dialer.start(); }+ return json(res, 200, state());+ }+ if (!body.data.on) {+ if (link.role() === "dialer") link.turnOff(await dialer.stop({ bye: true }));+ return json(res, 200, link.status());+ }+ if (link.role() === "acceptor") return json(res, 409, { error: "This place already takes a computer's link." });+ if (!body.data.origin.startsWith("https://") && !loopbackHost(body.data.origin)) return json(res, 400, { error: "The Cloud's address must be https." });+ if (link.role() === "dialer" && link.dial()?.origin !== body.data.origin) link.turnOff(await dialer.stop({ bye: true }));+ link.turnOn({ self: { id: deps.environmentId, name: body.data.name }, origin: body.data.origin, token: body.data.token, peer: body.data.cloud, ...(body.data.account ? { account: body.data.account } : {}) });+ deps.turnedOn?.();+ dialer.start();+ return json(res, 200, state());+ }++ if (path === PAIR_PATH) {+ if (!deps.owner(auth)) { req.resume(); return json(res, 403, { error: "Only this place's owner can link their computer to it." }); }+ if (method === "DELETE") {+ req.resume();+ const computer = url.searchParams.get("computer") ?? undefined;+ if (link.role() === "acceptor") link.unpair(computer && computer.length <= 200 ? computer : undefined);+ return json(res, 200, { ok: true });+ }+ if (method !== "POST") { req.resume(); return json(res, 405, { error: "method not allowed" }); }+ const body = pairBody.safeParse(await readBody(req, 16 * 1024));+ if (!body.success) return json(res, 400, { error: "send { computer: { id, name }, name }" });+ if (link.role() === "dialer") return json(res, 409, { error: "This place is linked to a Cloud itself." });+ const issued = deps.issue(auth, `Bot link · ${body.data.computer.name}`, body.data.computer.id);+ const self = { id: deps.environmentId, name: body.data.name };+ const paired = link.pair({ self, sessionId: issued.sessionId, computer: body.data.computer });+ if (!paired) { deps.revoke(issued.sessionId); return json(res, 409, { error: "This Cloud already links as many computers as it can. Turn the link off on one of them first." }); }+ held.get(paired.peer)?.();+ if (paired.replaced) deps.revoke(paired.replaced);+ deps.turnedOn?.();+ 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." }); }+ 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();+ if (power?.sleeping()) return answerAsleep(res, json);+ seen(peer);+ if (body.data.fresh) link.sessionStarted(peer);+ link.receive(peer, body.data.frames);+ const linked = () => auth.kind === "session" && link.peerOfSession(auth.session.id) === peer;+ if (!linked()) { clearTimeout(gone.get(peer)); gone.delete(peer); return json(res, 200, { session, frames: [] }); }+ if (body.data.wait > 0 && !link.hasOutgoing(peer, body.data.ack)) await hold(res, peer, body.data.ack, body.data.wait, power?.sleepSignal());+ if (power?.sleeping()) return answerAsleep(res, json);+ if (res.writableEnded || res.destroyed) return;+ if (!linked()) return json(res, 403, { error: "This link is off. Turn it on again in the app." });+ seen(peer);+ return json(res, 200, { session, frames: link.outgoing(peer, body.data.ack) });+ };+}diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.tsindex 446a220bdd..f40ce70ac6 100644--- a/server/runtime-coordinator.ts+++ b/server/runtime-coordinator.ts@@ -601,6 +601,7 @@ export class RuntimeCoordinator implements Coordinator {},names: (a, parent) => host.names(view(a, parent), parent && this.project(parent)),outward: a => host.outward ? host.outward(this.project(a)) : [],+ away: a => host.away ? host.away(this.project(a)) : false,};}diff --git a/server/runtime/runtime.test.ts b/server/runtime/runtime.test.tsindex 508aac1f50..51fb530de5 100644--- a/server/runtime/runtime.test.ts+++ b/server/runtime/runtime.test.ts@@ -222,6 +222,31 @@ describe("Runtime: one tree, one lane", () => {invariants(w);});+ it("work held for a place that was away is not expired by the look that finds the place back: its queue window starts then", () => {+ const w = world(undefined, { queueMs: 1_000, stallMs: 1e9 });+ let away = true;+ w.runner.away = a => a.assignee.botId === "far" && away;+ w.runner.canStartAnswer = "far is not ready";+ const root = w.runtime.begin(beginReq());+ const held = ok(w.runtime.enqueue(toBot("far", root.id)));+ w.runtime.tick();+ w.clock.advance(50_000);+ w.runtime.tick();+ expect(w.store.get(held.id)).toMatchObject({ status: "queued" });+ // The place comes back, and the next look comes later than the whole queue window.+ w.clock.advance(5_000);+ away = false;+ w.runtime.tick();+ expect(w.store.get(held.id)).toMatchObject({ status: "queued" });+ w.clock.advance(999);+ w.runtime.tick();+ expect(w.store.get(held.id)).toMatchObject({ status: "queued" });+ // From then on it is ordinary queued work, and the queue window is its bound again.+ w.clock.advance(2);+ w.runtime.tick();+ expect(w.store.get(held.id)).toMatchObject({ status: "failed", outcome: "expired", outcomeDetail: "never started" });+ });+it("expires a queue entry that never started and a question nobody answered, never as completed", async () => {const w = world(undefined, { queueMs: 1_000, inputWaitMs: 5_000 });const root = w.runtime.begin(beginReq());diff --git a/server/runtime/runtime.ts b/server/runtime/runtime.tsindex b27a627ebd..2d0069afa1 100644--- a/server/runtime/runtime.ts+++ b/server/runtime/runtime.ts@@ -240,9 +240,10 @@ export class Runtime {* assignment, a report to send); "parked" while live assignments only wait on a person, a teammate or a time limit. */pace(): "busy" | "parked" | "idle" {if (!this.opened) this.open();- if (this.turns.size > 0 || this.reportDue.size > 0) return "busy";+ if (this.reportDue.size > 0) return "busy";const live = this.store.all({ nonTerminal: true });- if (live.some(n => n.status === "queued" || n.status === "resume" || n.status === "running")) return "busy";+ if (live.some(n => n.status === "resume" || ((n.status === "queued" || n.status === "running") && !this.away(n)))) return "busy";+ if ([...this.turns.keys()].some(id => !live.some(n => n.id === id))) return "busy";return live.length > 0 ? "parked" : "idle";}@@ -258,21 +259,42 @@ export class Runtime {}}+ /** When each node was last seen held for a place that could not be reached, queued for it or running there, or first+ * seen with that place back: no window counts time up to then. */+ private readonly heldAway = new Map<string, number>();+ /** The nodes whose place was away when last asked. */+ private readonly awayNow = new Set<string>();++ private away(n: Assignment): boolean {+ if ((n.status !== "queued" && n.status !== "running") || this.runner.away === undefined) return false;+ if (this.safe("away", () => this.runner.away!(n)) !== true) {+ // The place is back: its windows start when that is first seen, not when it was last seen away. However long this+ // look took to come (a slow disk, a busy host), the node is not expired by the look that finds its place again.+ if (this.awayNow.delete(n.id)) this.heldAway.set(n.id, this.clock.now());+ return false;+ }+ this.heldAway.set(n.id, this.clock.now());+ this.awayNow.add(n.id);+ return true;+ }+private tickBody(): void {const now = this.clock.now();const mono = this.clock.monotonic();const live = this.store.all({ nonTerminal: true });+ if (this.heldAway.size > 0) { const ids = new Set(live.map(n => n.id)); for (const id of this.heldAway.keys()) if (!ids.has(id)) { this.heldAway.delete(id); this.awayNow.delete(id); } }// Deepest first, so each node fails with its own reason.for (const snapshot of [...live].sort((a, b) => b.depth - a.depth)) {const n = this.store.get(snapshot.id);if (!n || isTerminal(n)) continue;- if (n.status === "queued" && !n.continuation && now - this.since(n.lastActivityAt) > this.limits.queueMs) {+ if (n.status === "queued" && !n.continuation && !this.away(n) && now - Math.max(this.since(n.lastActivityAt), this.heldAway.get(n.id) ?? 0) > this.limits.queueMs) {this.cancelTree(n, n.executions > 0 ? "not resumed" : "never started", "failed", "expired");} else if (n.status === "needs_input" && this.inputExpires(n)) {this.chaseParked(n, now);} else if (n.status === "running") {const turn = this.turns.get(n.id);- if (turn && mono - turn.activeAt > this.limits.turnStallMs) {+ if (turn && this.away(n)) turn.activeAt = mono;+ else if (turn && mono - turn.activeAt > this.limits.turnStallMs) {this.cancelTree(n, `no activity for ${duration(this.limits.turnStallMs)}`, "failed", "stalled");}}@@ -292,7 +314,8 @@ export class Runtime {const anchor = Math.max(this.since(root.lastActivityAt), this.rootActivity.get(rootId) ?? 0);if (now - anchor <= this.limits.stallMs) continue;const tree = this.store.all({ rootId });- if (tree.some(n => n.status === "needs_input" || (n.status === "queued" && n.continuation !== undefined))) continue;+ if (tree.some(n => n.status === "needs_input" || (n.status === "queued" && (n.continuation !== undefined || this.away(n))) || (n.status === "running" && this.away(n)))) continue;+ if (now - Math.max(anchor, ...tree.map(n => this.heldAway.get(n.id) ?? 0)) <= this.limits.stallMs) continue;this.store.update(root, { kind: "stalled", at: now, detail: `no progress for ${duration(now - anchor)}` });this.cancelTree(root, `no progress for ${duration(this.limits.stallMs)}`, "failed", "stalled");}diff --git a/server/runtime/types.ts b/server/runtime/types.tsindex e7f195b256..8f1c96a038 100644--- a/server/runtime/types.ts+++ b/server/runtime/types.ts@@ -325,6 +325,9 @@ export interface TurnRunner {/** What the cut turn of this node already did outward, as short labels. Read at open() only: a* turn that acted outward is not run again. Absent or empty: the turn reruns once. */outward?(a: Assignment): string[];+ /** The assignee lives in a place that cannot be reached now (a computer that is off or asleep). Queued work for it is+ * held by no window: neither the queue bound nor the tree's stall window runs while this is true. */+ away?(a: Assignment): boolean;}export interface Clock {