Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
bot link: bound the wake for work, end it on a sign-in refusal, and wake only for a person's work
milind-soni6ea0fdcc0644
diff --git a/server/bot-link/dial.test.ts b/server/bot-link/dial.test.tsindex 8b141a69a6..8f44407989 100644--- a/server/bot-link/dial.test.ts+++ b/server/bot-link/dial.test.ts@@ -2,7 +2,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:htimport type { AddressInfo } from "node:net";import { afterEach, describe, expect, it, vi } from "vitest";-import { createDialer } from "./dial.ts";+import { createDialer, WAKE_MS, WAKE_TRIES, WAKES_PER_HOUR } from "./dial.ts";import type { BotLink } from "./link.ts";import { HOLD_MS, type Numbered } from "./protocol.ts";@@ -231,7 +231,7 @@ async function sleepyCloud(answer: (request: { background: boolean; wait: number/** A computer's link whose Cloud sleeps: work can be wanted, and what the dialer says of waking is kept. */function sleepyLink(origin: string) {- let wanted: () => void = () => {};+ let wanted: (person: boolean) => void = () => {};const waking: boolean[] = [];const link = {dial: () => ({ origin, token: "fixture-link-token" }),@@ -247,11 +247,11 @@ function sleepyLink(origin: string) {setWaking: (_peer: string, on: boolean) => { waking.push(on); },setTransfer: vi.fn(),onOutgoing: () => () => {},- onWanted: (listener: () => void) => { wanted = listener; return () => { wanted = () => {}; }; },+ onWanted: (listener: (person: boolean) => void) => { wanted = listener; return () => { wanted = () => {}; }; },ended: () => [],forgetEnded: vi.fn(),};- return { link: link as unknown as BotLink, observed: link, want: () => wanted(), waking };+ return { link: link as unknown as BotLink, observed: link, want: (person = true) => wanted(person), waking };}const settle = () => new Promise((resolve) => setTimeout(resolve, 150));@@ -349,3 +349,120 @@ describe("a Cloud that sleeps", () => {expect(dialer.state()).toMatchObject({ asleep: true });});});++/** A transport to a Cloud that cannot answer (a network error, or the provider's 502), with a clock each request moves on. */+function unanswering(kind: "network" | "502", clock: { at: number }, step: number, answerAfter = Infinity) {+ const calls: Array<{ foreground: boolean }> = [];+ const fetchImpl = (async (_url: string, init: RequestInit) => {+ calls.push({ foreground: !(init.headers as Record<string, string>)["x-omb-background"] });+ clock.at += step;+ // Once it answers, it answers that exchange, then holds each idle poll open until it is hung up.+ if (calls.length > answerAfter + 1) return new Promise<Response>((_resolve, reject) => init.signal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true }));+ if (calls.length > answerAfter) return new Response(JSON.stringify({ session: "session-1", frames: [] }), { status: 200, headers: { "content-type": "application/json" } });+ if (kind === "network") throw new TypeError("fetch failed");+ return new Response("bad gateway", { status: 502 });+ }) as unknown as typeof fetch;+ return { fetch: fetchImpl, calls };+}++describe("a wake for work is bounded", () => {+ it("fails once, then answers: the work still goes, and the app's asleep meanwhile parks nothing", async () => {+ const clock = { at: 1_000_000 };+ const cloudSide = unanswering("502", clock, 1_000, 1);+ const { link, observed, want } = sleepyLink("https://cloud.invalid");+ const dialer = createDialer({ link, fetch: cloudSide.fetch, firstRetryMs: 1, holdMs: 60_000, now: () => clock.at });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ want();+ await vi.waitFor(() => expect(observed.setOnline).toHaveBeenCalledWith("cloud-peer", true));+ expect(cloudSide.calls.slice(0, 2)).toEqual([{ foreground: true }, { foreground: true }]);+ dialer.sleep(clock.at - 10_000);+ expect(dialer.state()).toMatchObject({ asleep: false });+ });++ for (const kind of ["network", "502"] as const) {+ it(`never answers (${kind}): at most ${WAKE_TRIES} foreground asks a wake, then it parks; the app's asleep parks it; ${WAKES_PER_HOUR} wakes an hour`, async () => {+ const clock = { at: 1_000_000 };+ const cloudSide = unanswering(kind, clock, 1_000);+ const { link, want, waking } = sleepyLink("https://cloud.invalid");+ const dialer = createDialer({ link, fetch: cloudSide.fetch, firstRetryMs: 1, now: () => clock.at });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ const foreground = () => cloudSide.calls.filter((call) => call.foreground).length;+ for (let wake = 1; wake <= WAKES_PER_HOUR; wake += 1) {+ clock.at += 60_000;+ want();+ await vi.waitFor(() => expect(dialer.state().asleep).toBe(true), { timeout: 5_000 });+ expect(foreground()).toBe(wake * WAKE_TRIES);+ expect(waking.at(-1)).toBe(false);+ }+ await settle();+ expect(cloudSide.calls).toHaveLength(WAKES_PER_HOUR * WAKE_TRIES);+ // A fourth in the same hour is no wake: it asks in the background as before, and the app's asleep parks it.+ want();+ await vi.waitFor(() => expect(cloudSide.calls.length).toBeGreaterThan(WAKES_PER_HOUR * WAKE_TRIES));+ dialer.sleep(clock.at);+ expect(dialer.state()).toMatchObject({ asleep: true });+ expect(foreground()).toBe(WAKES_PER_HOUR * WAKE_TRIES);+ // An hour on, work may wake it again.+ clock.at += 60 * 60_000;+ want();+ await vi.waitFor(() => expect(foreground()).toBe((WAKES_PER_HOUR + 1) * WAKE_TRIES), { timeout: 5_000 });+ });+ }++ it("a wake that runs out of time parks, and the app's asleep is no longer put off", async () => {+ const clock = { at: 1_000_000 };+ const cloudSide = unanswering("network", clock, 0);+ const { link, want } = sleepyLink("https://cloud.invalid");+ const dialer = createDialer({ link, fetch: cloudSide.fetch, firstRetryMs: 60_000, now: () => clock.at });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ want();+ await vi.waitFor(() => expect(cloudSide.calls).toHaveLength(1));+ dialer.sleep(clock.at);+ expect(dialer.state()).toMatchObject({ asleep: false });+ clock.at += WAKE_MS;+ dialer.sleep(clock.at);+ expect(dialer.state()).toMatchObject({ asleep: true });+ expect(cloudSide.calls).toHaveLength(1);+ });++ it("work no person waits on (a routine's) unparks with background asks, as before, and the app's asleep parks it", async () => {+ const sleepy = await sleepyCloud(() => "asleep");+ const { link, want, waking } = sleepyLink(sleepy.origin);+ const dialer = createDialer({ link });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ want(false);+ await sleepy.requests(1);+ await settle();+ expect(sleepy.seen).toEqual([{ background: true, wait: 0 }]);+ expect(waking).toEqual([]);+ expect(dialer.state()).toMatchObject({ asleep: true });+ });++ it("asked to sign in again while waking: the wake ends, and after pairing again the first ask is background", async () => {+ let status = 401;+ const seen: boolean[] = [];+ const origin = await cloud((request, response) => {+ request.resume();+ seen.push(request.headers["x-omb-background"] === "1");+ if (status === 200 && seen.length > 2) return;+ response.writeHead(status, { "content-type": "application/json" });+ response.end(status === 200 ? JSON.stringify({ session: "session-1", frames: [] }) : JSON.stringify({ error: "no" }));+ });+ const { link, want, waking } = sleepyLink(origin);+ const dialer = createDialer({ link, holdMs: 5_000 });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ want();+ await vi.waitFor(() => expect(dialer.state().needsPairing).toBe(true));+ expect(seen).toEqual([false]);+ expect(waking).toEqual([true, false]);+ status = 200;+ dialer.start();+ await vi.waitFor(() => expect(seen.length).toBeGreaterThan(1));+ expect(seen[1]).toBe(true);+ });+});diff --git a/server/bot-link/dial.ts b/server/bot-link/dial.tsindex 03813174db..609bdff50b 100644--- a/server/bot-link/dial.ts+++ b/server/bot-link/dial.ts@@ -7,11 +7,14 @@// 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.//-// Work a person waits on (a hand-off, a room turn: `onWanted`) may wake a sleeping Cloud: the exchanges that follow are-// not marked background until one is answered, so the Cloud counts them as use and answers them even if it has not yet-// noticed it was woken. Everything else (directory news, idle polls) stays background and is never sent while parked,-// so it never wakes the Cloud or keeps it awake. An answer to such an exchange is the Cloud's own word that it is awake:-// the app's "asleep" heard before it is stale and parks nothing; only one heard after it does.+// Work a person waits on (a hand-off or room turn from a person's own line: `onWanted(true)`) may wake a parked Cloud:+// the exchanges that follow are not marked background until one is answered, so the Cloud counts them as use and answers+// them even if it has not yet noticed it was woken. Such a wake is bounded: WAKE_TRIES exchanges within WAKE_MS, and+// WAKES_PER_HOUR wakes an hour; one that gets no answer parks the link again until new work or the app's "awake".+// Work no person waits on (a routine's, a scheduled run's) unparks the link with background exchanges, as before.+// Everything else (directory news, idle polls) stays background and is never sent while parked, so it never wakes the+// Cloud or keeps it awake. An answer to a foreground exchange is the Cloud's own word that it is awake: the app's+// "asleep" heard before it is stale and parks nothing; only one heard after it does.import { createWriteStream, openAsBlob, rmSync } from "node:fs";import { stat } from "node:fs/promises";import { Readable, Transform } from "node:stream";@@ -27,6 +30,10 @@ const POWER_HEADER = "x-omb-cloud-power";const BACKGROUND_HEADER = "x-omb-background";/** One file may take this long to cross. */const FILE_MS = 10 * 60_000;+/** A wake for work a person waits on: this long and this many exchanges at most (a stopped Cloud takes about 20 s to+ * start), and this many wakes in any hour. */+export const WAKE_MS = 150_000, WAKE_TRIES = 6, WAKES_PER_HOUR = 3;+const HOUR_MS = 60 * 60_000;export interface DialerOptions {link: BotLink;@@ -41,10 +48,12 @@ export interface DialerOptions {export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS, level = PROTOCOL_LEVEL, now = Date.now }: DialerOptions) {let running = false, stopped = true, asleep = false, needsPairing = false;- /** `wake`: work a person waits on wants the Cloud, so exchanges are not background until one is answered. `provedAt`:- * when the Cloud last answered such an exchange (its own word that it is awake); `staleSaid`: the app's last "asleep"+ /** `wake`: work a person waits on is waking the Cloud until `wakeUntil` or WAKE_TRIES exchanges (`wakeTries`), so+ * exchanges are not background until one is answered; `wakes`: when each wake of the last hour began. `provedAt`: when+ * the Cloud last answered a foreground exchange (its own word that it is awake); `staleSaid`: the app's last "asleep"* that was older, so it is logged once. */- let wake = false, provedAt = -Infinity, staleSaid: number | undefined | null = null;+ let wake = false, wakeUntil = 0, wakeTries = 0, provedAt = -Infinity, staleSaid: number | undefined | null = null;+ const wakes: number[] = [];let session = "", ack = 0, fresh = true, retryMs = firstRetryMs;let active: AbortController | null = null, held: AbortController | null = null;let wakeUp: (() => void) | null = null;@@ -104,18 +113,29 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h};link.setTransfer(transfer);const stopListening = link.onOutgoing(() => { held?.abort(); });- const stopWanted = link.onWanted(() => {+ /** The wake had its time or its tries without an answer. */+ const wakeOver = () => wake && (now() >= wakeUntil || wakeTries >= WAKE_TRIES);+ const endWake = (peer: string | null) => { if (!wake) return; wake = false; if (peer) link.setWaking(peer, false); };+ const stopWanted = link.onWanted((person) => {if (stopped) return;- const peer = link.cloudPeer();- if (asleep && peer && !needsPairing && link.dial()) link.setWaking(peer, true);- asleep = false; wake = true; retryMs = firstRetryMs;+ if (wake && !wakeOver()) { wakeUp?.(); return; }+ const peer = link.cloudPeer(), at = now();+ while (wakes.length && at - wakes[0]! >= HOUR_MS) wakes.shift();+ if (person && asleep && peer && !needsPairing && link.dial() && wakes.length < WAKES_PER_HOUR) {+ wakes.push(at);+ wake = true; wakeUntil = at + WAKE_MS; wakeTries = 0;+ link.setWaking(peer, true);+ }+ asleep = false; retryMs = firstRetryMs;wakeUp?.();});- /** The Cloud answered that it sleeps, or the app's word parks the link: nothing asks it until work or the app wakes it. */+ /** The Cloud answered that it sleeps, the app's word parks the link, or a wake got no answer: nothing asks it until+ * there is new work for it or the app says it is awake. */const park = (peer: string | null) => {- asleep = true; fresh = true; wake = false; provedAt = -Infinity;+ asleep = true; fresh = true; provedAt = -Infinity;+ endWake(peer);link.setSleeps(true);- if (peer) { link.setWaking(peer, false); link.setOnline(peer, false); }+ if (peer) link.setOnline(peer, false);};async function exchange(target: { origin: string; token: string }, peer: string): Promise<void> {@@ -128,6 +148,7 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hconst wait = sending.length > 0 || fresh ? 0 : holdMs;if (wait > 0) held = controller;const foreground = wake || carriesWork(sending);+ if (wake) wakeTries += 1;try {const response = await fetchImpl(`${target.origin}${SYNC_PATH}`, {method: "POST", redirect: "error", cache: "no-store", signal: controller.signal,@@ -144,6 +165,7 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hif (response.status === 401 || response.status === 403) {await response.body?.cancel();needsPairing = true;+ endWake(peer);link.setOnline(peer, false);return;}@@ -183,11 +205,17 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hconst target = link.dial(), peer = link.cloudPeer();if (!target || !peer || needsPairing) break;if (asleep) { await pause(24 * 60 * 60_000); continue; }+ if (wakeOver()) { park(peer); continue; }try { await exchange(target, peer); } catch (error) {if (stopped) break;link.setOnline(peer, false);// The Cloud no longer answers, so its last answer proves nothing about now: the app's word governs again.fresh = true; provedAt = -Infinity;+ if (wakeOver()) {+ log("bot link: the Cloud did not answer while it was woken for work; it is left asleep until there is new work or the app says it is awake");+ park(peer);+ continue;+ }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);@@ -213,15 +241,16 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h* there is work for it. */start({ gentle = false }: { gentle?: boolean } = {}): void {stopped = false; asleep = gentle && link.sleeps(); needsPairing = false; fresh = true; retryMs = firstRetryMs;+ endWake(link.cloudPeer());wakeUp?.();void loop();},/** The app says the Cloud sleeps now: nothing asks it until there is work for it or it is awake again. `heardAt`: when* the app first heard that word (this computer's clock). It parks nothing while work a person waits on is waking the- * Cloud, or when the Cloud has answered such work since: the Admin's word lags the Cloud's own. */+ * Cloud (within the wake's bounds), or when the Cloud has answered such work since: the Admin's word lags the Cloud's. */sleep(heardAt?: number): void {if (stopped) return;- if (wake || (heardAt !== undefined && heardAt <= provedAt)) {+ if ((wake && !wakeOver()) || (heardAt !== undefined && heardAt <= provedAt)) {if (staleSaid !== heardAt) log(`bot link: the app says the Cloud sleeps, but it has answered since${wake ? " (waking it for work)" : ""}; the link stays up`);staleSaid = heardAt;return;@@ -231,9 +260,9 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h},/** 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, peer = link.cloudPeer();- stopped = true; wake = false;- if (peer) link.setWaking(peer, false);+ const target = link.dial(), sleeping = asleep;+ stopped = true;+ endWake(link.cloudPeer());active?.abort();wakeUp?.();return tell && target !== null && !sleeping ? bye(target) : false;diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsindex 99e8bb6383..e5496ae3b3 100644--- a/server/bot-link/link.test.ts+++ b/server/bot-link/link.test.ts@@ -98,7 +98,7 @@ function place(label: string, bots: Bot[], version?: number) {const sockets = new Set<import("node:net").Socket>();function boot(options: { limits?: { queueMs?: number; stallMs?: number } } = {}) {- rooms = createLinkedRooms({ dataDir: dir, store: roomStore as never, coordinator: () => coordinator, on: () => link.on(), linked: (peer) => link.has(peer), online: (peer) => link.online(peer), linkedBots: () => link.linked(), selfName: () => link.selfName(), wanted: () => link.wanted(),+ rooms = createLinkedRooms({ dataDir: dir, store: roomStore as never, coordinator: () => coordinator, on: () => link.on(), linked: (peer) => link.has(peer), online: (peer) => link.online(peer), linkedBots: () => link.linked(), selfName: () => link.selfName(), wanted: (person) => link.wanted(person),window: (threadId, reader) => createRoomTranscript({ store: roomStore as never, teammateReportContext: () => "" }).window(threadId, "Sam", undefined, reader),opener: (botId, threadId) => (routineThreads.has(threadId) ? { requester: { kind: "routine_run", runId: "run-1", botId, threadId }, origin: { kind: "routine", source: "routine", ref: "routine-1" } } : undefined),personName: () => "Sam", line: (_threadId, key, params) => `${key} ${params.bot ?? params.bots}${params.place ? ` [${params.place}]` : ""}`, follow: (_groupId, _threadId, speaker, text, hop) => { followed.push(`${speaker.name} at ${hop}: ${text}`); } });@@ -183,9 +183,10 @@ function place(label: string, bots: Bot[], version?: number) {/** 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: [] } }),- room?: { id: string; problem?: string }) {+ room?: { id: string; problem?: string }, byRoutine = false) {const id = `${label}-turn-${++generation}`, address = room ? { groupId: room.id, botId: from, threadId: `${room.id}-thread` } : { botId: from, threadId: `${from}-chat` };- coordinator.beginTurn({ id, address, brief: "Sort it out", level: "full", origin: { kind: "user", request: "Sort it out" } });+ // A person's own line, or a routine's run (whose work no person waits on).+ coordinator.beginTurn({ id, address, brief: "Sort it out", level: "full", origin: byRoutine ? { kind: "outside" } : { 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: () => {}, ...(room?.problem ? { problem: room.problem } : {}) }, 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 }> };@@ -1284,6 +1285,22 @@ describe("a Cloud that sleeps", () => {expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: Date.now() + 60_000 })).body).toMatchObject({ asleep: true, online: false });});+ it("a routine's hand-off is not work a person waits on: it does not wake the Cloud past the Admin's word, and the bot is told it waits", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ const home = sleepyHome(cloud);+ await asleep(computer, cloudOrigin, home);+ const before = cloud.syncs.length;+ home.jump(12_000);+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders"), undefined, undefined, true);+ expect(receipts[0]!.detail).toContain("My Cloud is offline now");+ expect(receipts[0]!.detail).not.toContain("waking");+ // As before this change: one background exchange, which a Cloud that sleeps answers with asleep, and the link parks again.+ await until(() => cloud.syncs.length > before && computer.dialer.state().asleep, "the link asks once and parks again");+ expect(cloud.syncs.slice(before).every((one) => one.background)).toBe(true);+ expect(home.power.sleeping()).toBe(true);+ expect(computer.results).toEqual([]);+ });+it("background link traffic never wakes a sleeping Cloud or keeps one awake", async () => {const { computer, cloud, cloudOrigin } = await two();const home = sleepyHome(cloud);diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex 187da3f48b..d7751397a3 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -187,7 +187,8 @@ export function createBotLink(deps: BotLinkDeps) {const live = new Map<string, Live>();const outboundListeners = new Set<(peer: string) => void>();- const wantedListeners = new Set<() => void>();+ /** `person`: the work traces to a person's own line, so they wait on it (dial.ts may wake a sleeping Cloud for it). */+ const wantedListeners = new Set<(person: boolean) => void>();/** Hand-offs this side sent whose result has not come back. */type Pending = { peer: string; frame: HandoffFrame; files: readonly PassedFile[]; settle(result: HostTurnResult): void; threadId: string; cancelled: boolean; busy?: boolean; tries: number };const pending = new Map<string, Pending>();@@ -659,8 +660,10 @@ export function createBotLink(deps: BotLinkDeps) {if (!duplicate && call.files?.length) deps.files?.crossed(node.id, "sent", { botId: context.sender.id, name: context.sender.name }, call.files);const files = call.files?.length && !deps.files ? " Its files were not sent: files do not cross to the other place here, so put what it needs in the message." : "";const online = isOnline(remote.peer);- // Said first, so a computer whose Cloud sleeps has asked it to wake before the bot is told what happens next.- if (!online) for (const listener of wantedListeners) listener();+ // Said first, so a computer whose Cloud sleeps has asked it to wake before the bot is told what happens next. Only+ // work a person's own line started may wake it; a routine's or a scheduled run's waits as before.+ const person = coordinator.status(node.id)?.assignment?.origin?.kind === "person";+ if (!online) for (const listener of wantedListeners) listener(person);const told = !online && waking.has(remote.peer) ? `Finish your turn and tell the person ${place} is waking up for it.` : `Finish your turn and tell the person it waits for ${place}.`;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}`@@ -884,8 +887,8 @@ export function createBotLink(deps: BotLinkDeps) {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. *//** There is work for a place that is not connected, handed over outside `coordinate` (a room turn). */- wanted(): void { for (const listener of wantedListeners) listener(); },- onWanted(listener: () => void): () => void { wantedListeners.add(listener); return () => wantedListeners.delete(listener); },+ wanted(person = false): void { for (const listener of wantedListeners) listener(person); },+ onWanted(listener: (person: boolean) => void): () => void { wantedListeners.add(listener); return () => wantedListeners.delete(listener); },/** The dialer is waking this place, asleep, for work a person waits on (until it answers or parks again). */setWaking(peer: string, on: boolean): void { if (on) waking.add(peer); else waking.delete(peer); },sleeps: () => state?.sleeps === true,diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.tsindex 9437ce4048..d4bb511aa3 100644--- a/server/host/bot-link-host.ts+++ b/server/host/bot-link-host.ts@@ -87,7 +87,7 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {};/** What the app was last told of each room's far members. */const farTold = new Map<string, string>();- const rooms = createLinkedRooms({ dataDir: deps.dataDir, store, coordinator: deps.coordinator, on: () => link.on(), linked: (peer) => link.has(peer), online: (peer) => link.online(peer), linkedBots: () => link.linked(), selfName: () => link.selfName(), wanted: () => link.wanted(),+ const rooms = createLinkedRooms({ dataDir: deps.dataDir, store, coordinator: deps.coordinator, on: () => link.on(), linked: (peer) => link.has(peer), online: (peer) => link.online(peer), linkedBots: () => link.linked(), selfName: () => link.selfName(), wanted: (person) => link.wanted(person),personName: deps.personName, line: deps.roomLine, window: deps.roomWindow, log: deps.log, ...(deps.roomOpener ? { opener: deps.roomOpener } : {}), ...(deps.roomFollow ? { follow: deps.roomFollow } : {}) });const link = createBotLink({dataDir: deps.dataDir, coordinator: deps.coordinator, kick: deps.kick, log: deps.log, rooms, directoryChanged: () => { syncStandIns(); }, revoke: (sessionId) => { deps.sessions.revoke(sessionId); },diff --git a/server/host/bot-link-rooms.ts b/server/host/bot-link-rooms.tsindex d0c2506951..d594b654ac 100644--- a/server/host/bot-link-rooms.ts+++ b/server/host/bot-link-rooms.ts@@ -75,7 +75,8 @@ export interface LinkedRoomsDeps {linkedBots(): ReadonlyArray<{ id: string; peer: string; place: { name: string }; kind?: "computer" | "cloud"; bot: { id: string; name: string; color?: string; title?: string; mascotBody?: string; mascotFaceColor?: string; mascotBodyColor?: string; mascotMaterial?: string } }>;selfName(): string;/** There is work for a place that is not connected: a computer asks its Cloud for it now, as for any hand-off. */- wanted(): void;+ /** `person`: the room's last line is a person's own, so they wait on the turn. */+ wanted(person: boolean): void;personName(threadId: string): string | undefined;line(threadId: string, key: ServerLineKey, params: Record<string, string>): string;/** The room's lines as a member of it reads them (server/host/room-transcript.ts): each with the note that says who it@@ -235,7 +236,7 @@ export function createLinkedRooms(deps: LinkedRoomsDeps) {return true;}}- if (!online) deps.wanted();+ if (!online) deps.wanted(workOrigin(store.activePath(threadId).findLast((message) => message.role === "user" && message.kind === "text" && Boolean(message.text))).kind === "user");// Said once for each wait: a second message written while the place is away adds no second line.if (!online && !waiting) note(threadId, member.id, "server.rooms.linkedAway", { ok: true });return true;