Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Work from outside stays with that work
milind-soni257c3a4b612b
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex b5e0c20c86..406f12fa06 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -252,9 +252,10 @@ no line, card answer, conversation or routine recorded under anyone else'skey; and a record that can be read), every routine and conversation runs atits bot's own level, whatever writer it has on record. Only what came in fromoutside stays confined: a routine a bot made or changed in a conversation a-webhook drove (its run, a payload posted into it, or work it handed on) is-recorded as the outside's, and runs without full access until the owner opens-it and saves it once. Routines from before this that a webhook-driven+webhook drove (its run, a payload posted into it, or work it handed on, for good+once that run has ended) is recorded as the outside's, and runs without full+access until the owner opens it and saves it once; what its runs hand a teammate+stays confined too, in that thread, after the work ends. Routines from before this that a webhook-drivenconversation made or changed are recorded the same way, once. The first traceof a second person makes the Cloud shared for good: cloud-owner.json recordswhen, nothing clears it, and a restore never brings or removes it. If that@@ -924,7 +925,11 @@ On the Cloud home (`server/shared-computers.ts`, `server/index.ts`):(docs/runtime-contract.md §4, §9). Work or a question for a teammate runsin the work thread the guest's conversation has with that teammate, openedas the guest's, never in the owner's conversation with it, and is never- folded into a turn running there. It works in a folder of its own, never the bot's+ folded into a turn running there. Such a turn reaches no conversation or room+ of the owner's at all (`retry_thread`, `post_to_room`, `coordinate_bots` with a+ thread or a room, an answer to a question there), and what it writes to a+ room's bulletin waits on the owner's card; of the server's own routes it reaches only those+ `server/host/outside-fence.ts` lists. It works in a folder of its own, never the bot'sproject folder the owner's conversations share, and a card it raisesnever offers "always allow". One that already ran in another folder keepsit, except a conversation a revoked session opened: it is unpinned at boot,diff --git a/docs/runtime-contract.md b/docs/runtime-contract.mdindex d58ab6c64b..8e5a6db7db 100644--- a/docs/runtime-contract.md+++ b/docs/runtime-contract.md@@ -52,7 +52,7 @@ queued ──admit──> running ──turn ends──> completed | failed | ca`level = max(own, inherited)` in the order `ask < edits < auto < full`. `custom` never travels.-`inherited` is the Chief conversation's level only when the origin is `person` or `routine` **and** the requester is a Chief, or a Chief is an ancestor in the same root. Outside lineage inherits nothing.+`inherited` is the Chief conversation's level only when the origin is `person` or `routine` **and** the requester is a Chief, or a Chief is an ancestor in the same root. Outside lineage inherits nothing: a thread a hand-off opens keeps its own level, and no level lands on it (`server/host/delegated-level.ts` asks `handsNoLevel`, the conversation's own record, so this holds after the run ends and after a restart).The inherited level is capped by what the assignee's engine really does (`shared/approval-mode.ts`): `full` passes on every engine (`supportsApprovalMode(kind, "full")` is always true, Full being the default level); `auto` only if `hasNativeAutoReview(kind)`, otherwise `edits` if supported, otherwise `own`. `levelSource` says which rule won. The permission mode a turn runs with must equal the level on its record (invariant I6).diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 368ac5748a..5a59499da9 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -126,6 +126,16 @@ owner" card rule (whoever started a conversation, or an Admin, answers its cardsthe Admin's Team admin → Settings. It is this server's language while its own settings set none (the app's words and thelanguage new bots start in); a value that isn't a locale is ignored, never refused.+## Work from outside stays with that work++What came in from outside (a webhook, an app's event) is confined, and the conversation it reached stays that way for good: a run or a hand-off ends, its words stay in the thread. The record is on the conversation (`outside`, `server/host/outside-lineage.ts`), and every turn is judged from it, at any level and after a restart.++- **What it starts stays outside.** A thread it hands work to, a one-way notice still queued when the run ends, a retry, a wake and a routine it makes or changes all run confined. A routine it made runs without full access until someone opens it and saves it once. An event's own results chat counts too.+- **It reaches nothing else.** A confined turn can't open a thread, hand work to, post to or retry into a conversation or room that isn't already outside, can't answer a question in a person's work or be folded into a turn running there, and can't change, start, pause, resume or delete a person's routine. It hears why in plain words and finishes where it is. Of the server's own routes it reaches only those `server/host/outside-fence.ts` lists; anything else is refused, whether or not its engine pre-allows the tool.+- **What it writes for later turns waits on a card.** A room's bulletin and a bot's memory load into later turns as instructions, so an admin sees a card and nothing is saved until they say yes (`server/host/outside-writes.ts`). A memory log line and a preference are refused, and nothing such a conversation says reaches memory or the daily log on its own.+- **Its problems reach a person.** A confined run that fails or needs someone notifies a person; it starts no turn on a Chief at the Chief's own level. None of what it says lands in a person's inbox thread, by naming them or as a copy of its question or report: the person gets the notification and opens the conversation.+- **A person's own line there runs confined too.** The engine reads the outside words as context, whoever typed last, so the bot works without its shell and says so once. A new conversation with the same bot runs at the bot's own level; it doesn't read that conversation on its own (recall and the recent-work brief leave it out), and a person can paste what they want into it.+## Team admin: the Admin's signed readThe Admin's Team admin pages (openmaus-cloud docs/team-cloud.md "Team admin") show a team's Super admin and Admins whatdiff --git a/docs/team-incidents.md b/docs/team-incidents.mdindex fe1c80659f..d8b05ae389 100644--- a/docs/team-incidents.md+++ b/docs/team-incidents.md@@ -50,6 +50,7 @@ announced twice. A thread running an assignment another bot is waiting onfailure is reported to it and resumes it — so it raises no incident. A runthe person stopped is not an incident.+A confined conversation's problem (work from outside, docs/team-cloud.md) reaches a person, never a Chief's turn.`retry_thread` is Chief-only, for a teammate the Chief can reach, never aroom thread (coordinate in the room instead), never a thread that is stillrunning, and never one that has finished a run since it was last reporteddiff --git a/server/automation-destinations.test.ts b/server/automation-destinations.test.tsnew file mode 100644index 0000000000..4b59f20321--- /dev/null+++ b/server/automation-destinations.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";++import { createAutomationDestinations, type AutomationDestinationDeps } from "./automation-destinations.ts";+import { CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";+import type { Routine } from "./routines.ts";++function world(writer: string) {+ const tasks = new Map([["person-chat", { threadId: "person-chat", title: "Person" }], ["hook-chat", { threadId: "hook-chat", title: "Hook · Results" }]]);+ const opened: Array<[string, string]> = [];+ const outside: string[] = [];+ let made = 0;+ const store = {+ bot: () => ({ id: "bot" }),+ createTask: (_botId: string, title: string) => { const task = { threadId: `made-${++made}`, title }; tasks.set(task.threadId, task); return task; },+ messagesFor: () => [],+ taskByThread: (_botId: string, threadId: string) => tasks.get(threadId),+ } as unknown as AutomationDestinationDeps["store"];+ const destinations = createAutomationDestinations({ store, mainThread: () => "main", runs: () => [],+ cloud: { owner: "owner", opener: () => writer, reportFromOthers: () => false, opened: (threadId, person) => { opened.push([threadId, person]); }, outside: (threadId) => { outside.push(threadId); } } });+ return { destinations, opened, outside };+}+const routine = { id: "r", name: "Daily", botId: "bot", resultsThreadId: "person-chat" } as Routine;++describe("where an automation reports on a Cloud", () => {+ it("keeps the chat a person's routine chose", () => {+ expect(world("p_someone").destinations.routine(routine, false)).toEqual({ threadId: "person-chat" });+ });++ it("gives a routine outside work wrote a chat of its own, whatever chat it names", () => {+ const w = world(CLOUD_OUTSIDE_KEY);+ expect(w.destinations.routine(routine, false)).toEqual({ threadId: "made-1" });+ expect(w.opened).toEqual([["made-1", CLOUD_OUTSIDE_KEY]]);+ });++ it("names an event's own chat, never a person's or the chat a wait reports to", () => {+ const { destinations } = world("owner");+ expect(destinations.eventChat({ botId: "bot", routineName: "Hook", resultsThreadId: "hook-chat" })).toBe("hook-chat");+ expect(destinations.eventChat({ botId: "bot", routineName: "Hook", resultsThreadId: "person-chat" })).toBeUndefined();+ expect(destinations.eventChat({ botId: "bot", routineName: "Hook", resultsThreadId: "hook-chat", eventSource: "wait" })).toBeUndefined();+ });++ it("records an event's own chat as holding outside work", () => {+ const w = world("owner");+ expect(w.destinations.event({ webhookId: "w", webhookName: "Hook", botId: "bot" })).toBe("made-1");+ expect(w.outside).toEqual(["made-1"]);+ });+});diff --git a/server/automation-destinations.ts b/server/automation-destinations.tsindex 82db354012..94fb2ebe79 100644--- a/server/automation-destinations.ts+++ b/server/automation-destinations.ts@@ -1,6 +1,7 @@// Where an automation's runs report: the chat a routine chose, else the bot's main chat. On a Cloud home a chat the// owner writes in never gets words they did not choose, so a Mac they lend stays theirs there: a routine someone else// wrote, and every outside event, report into a chat of their own.+import { CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";import type { Routine, RoutineRun } from "./routines.ts";import { threadTitleFrom, type Message, type Store, type TaskRecord } from "./store.ts";@@ -15,6 +16,8 @@ export interface AutomationDestinationDeps {opener(routineId: string): string;reportFromOthers(line: Message): boolean;opened(threadId: string, person: string): void;+ /** This chat holds what an outside event's run reported. */+ outside(threadId: string): void;} | null;}@@ -30,10 +33,16 @@ export function createAutomationDestinations(deps: AutomationDestinationDeps) {return threadId;};return {+ /** The chat of its own an outside event's run reports into on a Cloud: never the person's, and never a wait's, which reports to the chat that set it. */+ eventChat(run: Pick<RoutineRun, "botId" | "routineName" | "resultsThreadId" | "eventSource">): string | undefined {+ const task = cloud && run.eventSource !== "wait" && run.resultsThreadId ? store.taskByThread(run.botId, run.resultsThreadId) : undefined;+ return task && legacyResultsThread(run.routineName, task) ? task.threadId : undefined;+ },routine(routine: Routine, forceNew: boolean): { threadId: string; main?: true } | undefined {const bot = store.bot(routine.botId);- const chosen = !forceNew && routine.resultsThreadId && bot && !bot.hidden ? store.taskByThread(bot.id, routine.resultsThreadId) : undefined;const opener = cloud?.opener(routine.id);+ // A routine outside work wrote reports nowhere a person already works, whatever chat it names.+ const chosen = !forceNew && opener !== CLOUD_OUTSIDE_KEY && routine.resultsThreadId && bot && !bot.hidden ? store.taskByThread(bot.id, routine.resultsThreadId) : undefined;const main = bot && !bot.hidden ? deps.mainThread(bot.id) : undefined;const mainAllowed = main && (!cloud || opener === cloud.owner);if (chosen && !chosen.routineRunId && !(mainAllowed && legacyResultsThread(routine.name, chosen))) return { threadId: chosen.threadId };@@ -48,8 +57,9 @@ export function createAutomationDestinations(deps: AutomationDestinationDeps) {const earlier = deps.runs().find((run) => run.webhookId === webhookId && run.botId === botId && run.resultsThreadId)?.resultsThreadId;const kept = earlier ? store.taskByThread(botId, earlier) : undefined;const lines = kept && !kept.routineRunId ? store.messagesFor(kept.threadId) : undefined;- if (kept && lines && (lines.length === 0 || lines.some(cloud.reportFromOthers))) return kept.threadId;- return chatOfItsOwn(botId, webhookName, cloud.owner);+ const threadId = kept && lines && (lines.length === 0 || lines.some(cloud.reportFromOthers)) ? kept.threadId : chatOfItsOwn(botId, webhookName, cloud.owner);+ if (threadId) cloud.outside(threadId);+ return threadId;},};}diff --git a/server/cloud-chat-merge.test.ts b/server/cloud-chat-merge.test.tsindex 7d4a83f9c0..d88546f4d0 100644--- a/server/cloud-chat-merge.test.ts+++ b/server/cloud-chat-merge.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { DatabaseSync } from "node:sqlite";import { describe, expect, it } from "vitest";-import { activePath, mergeStagedChats, mergeThread, planChatMerge, type ChatsSide, type ThreadRows } from "./cloud-chat-merge.ts";+import { activePath, applyChatMerge, mergeStagedChats, mergeThread, planChatMerge, type ChatsSide, type ChatStore, type ThreadRows } from "./cloud-chat-merge.ts";import { DATA_DIR } from "./config.ts";import { Store, type Message, type TaskRecord } from "./store.ts";@@ -180,3 +180,16 @@ describe("applied to a live store", () => {expect(existsSync(join(DATA_DIR, "routines.json"))).toBe(false);});});++describe("work from outside", () => {+ it("keeps the record when its lines merge into a conversation the other side already has", () => {+ const own = (more: Partial<TaskRecord> = {}) => ({ threadId: "chat", title: "Chat", createdAt: 1, resumeCursors: {}, ...more }) as TaskRecord;+ const bot = { id: "bot", threadId: "chat", tasks: [own()] };+ const plan = planChatMerge(side([{ id: "bot", threadId: "chat", tasks: [own({ outside: true })] }], [], { chat: [line("a", 1, null), line("b", 2, "a", "bot")] }),+ side([{ id: "bot", threadId: "chat", tasks: [own()] }], [], { chat: [line("a", 1, null)] }));+ expect(plan.threads).toEqual([expect.objectContaining({ threadId: "chat", outside: true })]);+ const store = { bots: [bot], groups: [], bot: () => bot, importTranscript: () => {}, patchBot: () => null, patchGroup: () => null } as unknown as ChatStore;+ applyChatMerge(store, plan);+ expect(bot.tasks[0]!.outside).toBe(true);+ });+});diff --git a/server/cloud-chat-merge.ts b/server/cloud-chat-merge.tsindex 0dcef13370..f4eadc1c06 100644--- a/server/cloud-chat-merge.ts+++ b/server/cloud-chat-merge.ts@@ -20,14 +20,14 @@ export interface ChatsSide {}type Owner = { kind: "bot" | "group"; id: string };type Link = { id: string; parentId: string | null };-export interface ThreadMerge { owner: Owner; threadId: string; task?: TaskRecord | GroupTaskRecord; added: Message[]; relinked: Link[]; leaf: string | null }+export interface ThreadMerge { owner: Owner; threadId: string; task?: TaskRecord | GroupTaskRecord; added: Message[]; relinked: Link[]; leaf: string | null; outside?: true }/** `messages`: text lines (what a person reads as messages); `intoExisting`: of those, the ones added to conversations it already had. */export interface ChatMergeResult { conversations: number; messages: number; intoExisting: number; skippedBots: number; skippedRooms: number; deleted: number }export interface ChatMergePlan extends ChatMergeResult { threads: ThreadMerge[] }export type ChatStore = Pick<Store, "bots" | "groups" | "bot" | "group" | "messagesFor" | "activeLeaf" | "importTranscript" | "patchBot" | "patchGroup" | "createGroup">;const BOT_TASK_KEYS = ["threadId", "title", "createdAt", "titleFromFirstMessage", "openedBy", "closedBy", "archivedAt", "pinned", "link", "linkAuto",- "lastReadMessageId", "pinnedMessageId", "routineRunId", "askedAt", "snoozedUntil"] as const;+ "lastReadMessageId", "pinnedMessageId", "routineRunId", "askedAt", "snoozedUntil", "outside"] as const;const GROUP_TASK_KEYS = ["threadId", "title", "createdAt", "titleFromFirstMessage", "pinned", "pinnedMessageId", "turnTimeoutMinutes"] as const;export const ATTACHMENT_NAME = /^[A-Za-z0-9-]{1,80}\.[A-Za-z0-9]{1,10}$/;@@ -140,7 +140,7 @@ export function planChatMerge(from: ChatsSide, to: ChatsSide, syncedAt = Number.const merged = mergeThread(rows, to.thread(threadId), options);synced = Math.max(synced, merged.synced);if (!merged.added.length) continue;- plan.threads.push({ owner, threadId, added: merged.added, relinked: merged.relinked, leaf: merged.leaf });+ plan.threads.push({ owner, threadId, added: merged.added, relinked: merged.relinked, leaf: merged.leaf, ...(task && "outside" in task && task.outside ? { outside: true as const } : {}) });plan.intoExisting += textLines(merged.added);} else if (home === undefined && task && !to.thread(threadId).rows.length) fresh.push({ owner, threadId, task, rows });}@@ -242,6 +242,7 @@ export function applyChatMerge(store: ChatStore, plan: ChatMergePlan): void {for (const thread of plan.threads) {store.importTranscript(thread.threadId, thread.added, thread.leaf, thread.task ? undefined : thread.relinked);if (!thread.task) touched.set(ownerKey(thread.owner), thread.owner);+ if (thread.outside && thread.owner.kind === "bot") { const task = store.bot(thread.owner.id)?.tasks?.find((one) => one.threadId === thread.threadId); if (task) task.outside = true; }}// Saves the conversations' new activity times and tells open apps about them; no message frame, so nothing is read aloud or notified.for (const owner of touched.values()) {diff --git a/server/cloud-sharing.test.ts b/server/cloud-sharing.test.tsindex 6bc6404974..07f136a10c 100644--- a/server/cloud-sharing.test.ts+++ b/server/cloud-sharing.test.ts@@ -25,11 +25,13 @@ describe("whether anyone but the owner has used a Cloud home", () => {it("calls a conversation outside-driven when a webhook started it, posted into it, or drove the work handed to it", () => {const records = (overrides: Partial<Parameters<typeof outsideDriven>[1]> = {}) => ({- webhookRun: (id: string) => id === "hook-run", webhookPosted: (id: string) => id === "updates", handedFrom: () => [] as string[], ...overrides,+ marked: (id: string) => id === "kept", webhookRun: (id: string) => id === "hook-run", webhookPosted: (id: string) => id === "updates", handedFrom: () => [] as string[], ...overrides,});expect(outsideDriven("chat", records())).toBe(false);expect(outsideDriven("hook-run", records())).toBe(true);expect(outsideDriven("updates", records())).toBe(true);+ expect(outsideDriven("kept", records())).toBe(true);+ expect(outsideDriven("teammate", records({ handedFrom: () => ["kept"] }))).toBe(true);expect(outsideDriven("teammate", records({ handedFrom: () => ["chat", "hook-run"] }))).toBe(true);expect(outsideDriven("teammate", records({ handedFrom: () => ["chat"] }))).toBe(false);});diff --git a/server/cloud-sharing.ts b/server/cloud-sharing.tsindex 5ce7bd6f69..c3fe150f3c 100644--- a/server/cloud-sharing.ts+++ b/server/cloud-sharing.ts@@ -28,12 +28,14 @@ export function cloudShared(evidence: SharingEvidence): boolean {return [...adopted].some(someoneElse) || [...evidence.recorded].some(someoneElse) || [...(evidence.seen ?? [])].some(someoneElse);}-/** A webhook drove this conversation: its run, a payload posted into it, or a conversation that handed it the work. */+/** A webhook drove this conversation: its record, its run, a payload posted into it, or a conversation that handed it the work. */export function outsideDriven(threadId: string, records: {+ /** The durable record, kept once the run or hand-off that brought the work has ended. */+ marked(threadId: string): boolean;webhookRun(threadId: string): boolean;webhookPosted(threadId: string): boolean;handedFrom(threadId: string): Iterable<string>;}): boolean {- const driven = (id: string) => records.webhookRun(id) || records.webhookPosted(id);+ const driven = (id: string) => records.marked(id) || records.webhookRun(id) || records.webhookPosted(id);return driven(threadId) || [...records.handedFrom(threadId)].some(driven);}diff --git a/server/decision-log.ts b/server/decision-log.tsindex 5f653c2330..d2d27723a7 100644--- a/server/decision-log.ts+++ b/server/decision-log.ts@@ -38,6 +38,7 @@ export type DecisionSource =| "connector-scope"| "outbound"| "team-memory"+ | "outside-write"| "auto-review"| "auto-review-shadow";diff --git a/server/host/chief-notices-retry.test.ts b/server/host/chief-notices-retry.test.tsindex 262a016dba..cf72a4db04 100644--- a/server/host/chief-notices-retry.test.ts+++ b/server/host/chief-notices-retry.test.ts@@ -234,3 +234,32 @@ describe("the person's line about an incident", () => {expect(f.turnsOf("chief")[0]!.text).toContain("Ada's run in its thread #Invoices stopped after showing no activity");});});++describe("a problem in a conversation that runs confined", () => {+ it("reaches a person, never a Chief's turn at the Chief's own level", () => {+ const notify = vi.fn();+ const f = fixture({ confined: (threadId) => threadId === "ada-job", notify });+ f.notices.reportIncident({ kind: "failed", bot: f.ada as never, threadId: "ada-job", detail: "the turn stopped" });+ expect(f.startTurn).not.toHaveBeenCalled();+ expect(notify).toHaveBeenCalledOnce();+ });++ it("is not started again by itself through a Chief", () => {+ const f = fixture({ confined: (threadId) => threadId === "ada-job" });+ f.notices.reportIncident({ kind: "failed", bot: f.ada as never, threadId: "ada-job", detail: "the turn stopped" });+ expect(f.turnsOf("ada")).toEqual([]);+ });++ it("leaves an escalation with a person too", () => {+ const notify = vi.fn();+ const f = fixture({ confined: (threadId) => threadId === "ada-job", notify });+ expect(f.notices.reportEscalation({ kind: "needs-input", bot: f.ada as never, threadId: "ada-job", gate: "a card", reason: "waiting", alreadyNotified: false })).toBe("person");+ expect(f.startTurn).not.toHaveBeenCalled();+ });++ it("a conversation that is not confined still reaches its Chief", () => {+ const f = fixture({ confined: () => false });+ f.notices.reportIncident({ kind: "stalled", bot: f.ada as never, threadId: "ada-job", detail: "no activity" });+ expect(f.turnsOf("chief")).toHaveLength(1);+ });+});diff --git a/server/host/chief-notices.ts b/server/host/chief-notices.tsindex 9ff45f2085..c6b3c8406e 100644--- a/server/host/chief-notices.ts+++ b/server/host/chief-notices.ts@@ -43,6 +43,8 @@ export interface ChiefNoticeDeps {quietThread?(botId: string, threadId: string): boolean;/** A person's private chat on a Team Cloud: its notices go to that person, never into a Chief's thread the team reads. */privateThread?(threadId: string): boolean;+ /** Security invariant: a confined conversation's words never start a Chief's turn at its own level, so its notices go to a person. */+ confined?(threadId: string): boolean;/** The language a line about this conversation is written in for its person (server/server-lines.ts). */threadLanguage?(threadId: string): string | undefined;/** A Team Cloud: a notice reaches a Chief only when the conversation's asks are its person's (a member's private chat@@ -118,6 +120,7 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {/** A notice about this thread may go to `chief`: its asks are the Chief's person's, never another person's private chat. */function reachesChief(chief: BotRecord, bot: BotRecord, threadId: string): boolean {const routing = deps.routing;+ if (deps.confined?.(threadId)) return false;return routing ? routing.askedPerson(bot.id, threadId) === routing.personOf(chief) : deps.privateThread?.(threadId) !== true;}diff --git a/server/host/delegated-level.test.ts b/server/host/delegated-level.test.tsindex cb08321ec8..d66f74ffbe 100644--- a/server/host/delegated-level.test.ts+++ b/server/host/delegated-level.test.ts@@ -5,7 +5,7 @@ import type { BotRecord } from "../store.ts";import { createDelegatedLevel, type DelegatedLevelDeps, type Hop } from "./delegated-level.ts";// Clive (a Chief) handed work to Ada, and Ada's turn hands work on: the chain is the hand-off nodes' parents.-function world(levels: Record<string, ApprovalMode>, nodes: Record<string, Hop>, guest = new Set<string>()) {+function world(levels: Record<string, ApprovalMode>, nodes: Record<string, Hop>, guest = new Set<string>(), outside = new Set<string>()) {const bots: Record<string, Partial<BotRecord>> = {clive: { id: "clive", name: "Clive", chiefOfStaff: true }, ada: { id: "ada", name: "Ada" }, bea: { id: "bea", name: "Bea" }, ola: { id: "ola", name: "Ola" },};@@ -21,7 +21,7 @@ function world(levels: Record<string, ApprovalMode>, nodes: Record<string, Hop>,const level = (botId: string, threadId: string) => levels[`${botId}:${threadId}`] ?? levels[botId] ?? "ask";const delegated = createDelegatedLevel({store, node: id => nodes[id], sourceLevel: level, turnLevel: (bot, _peer, threadId) => level(bot.id, threadId),- driverKind: () => "claudeAgent", guestDriven: threadId => guest.has(threadId),+ driverKind: () => "claudeAgent", guestDriven: threadId => guest.has(threadId), handsNoLevel: threadId => outside.has(threadId),});return { ...delegated, patched, lines, bot: (id: string) => bots[id] as BotRecord };}@@ -50,6 +50,17 @@ describe("a Chief's level, every hop down", () => {]);});+ it("brings nothing down from work that came in from outside: the teammate keeps its own level", () => {+ const w = world({ "clive:clive-chat": "full" }, chain, new Set(), new Set(["clive-chat"]));+ w.apply(w.bot("clive"), "clive-chat", "root", w.bot("ada"), "ada-work");+ expect(w.patched).toEqual([]);+ expect(w.lines).toEqual([]);+ expect(w.levelOf({ botId: "ada", threadId: "ada-work" }, chain["to-ada"]).chief).toBeUndefined();+ const below = world({ "clive:clive-chat": "full", "ada:ada-work": "ask" }, chain, new Set(), new Set(["ada-work"]));+ below.apply(below.bot("ada"), "ada-work", "to-ada", below.bot("bea"), "bea-work");+ expect(below.patched).toEqual([]);+ });+it("runs a room turn at the level its hand-off's chain brings down, and a guest's room at Ask", () => {const w = world({ "clive:room": "full" }, chain);expect(w.roomTurn(w.bot("bea"), "room", chain["room-ada"])).toBe("full");diff --git a/server/host/delegated-level.ts b/server/host/delegated-level.tsindex 9e2b3a3a2b..15e56d71d1 100644--- a/server/host/delegated-level.ts+++ b/server/host/delegated-level.ts@@ -19,6 +19,8 @@ export interface DelegatedLevelDeps {turnLevel: (bot: BotRecord, peerInitiated: boolean, threadId: string) => ApprovalMode;driverKind: (bot: BotRecord) => string | undefined;guestDriven: (threadId: string) => boolean;+ /** Outside lineage inherits nothing (docs/runtime-contract.md §3). */+ handsNoLevel: (threadId: string) => boolean;}const NAMES: Partial<Record<ApprovalMode, string>> = { edits: "Auto-accept edits", auto: "Approve for me", full: "Full access" };@@ -41,7 +43,7 @@ export function createDelegatedLevel(deps: DelegatedLevelDeps) {/** The level work `from` hands `target` comes down with, or null to keep `own`. */function handedDown(from: Hop | undefined, target: BotRecord, own: ApprovalMode) {const above = chiefAbove(from);- if (!from || !above) return null;+ if (!from || !above || deps.handsNoLevel(from.threadId) || deps.handsNoLevel(above.threadId)) return null;const chiefMode = deps.sourceLevel(above.chief.id, above.threadId);const level = delegatedApprovalMode({senderIsChief: true, senderMode: chiefMode, sameBot: from.botId === target.id || above.chief.id === target.id,diff --git a/server/host/outside-fence.test.ts b/server/host/outside-fence.test.tsnew file mode 100644index 0000000000..722f45848b--- /dev/null+++ b/server/host/outside-fence.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";++import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./outside-fence.ts";++describe("what a confined turn reaches of OpenMausBot's own routes", () => {+ it("refuses what runs or starts something with no person deciding", () => {+ for (const path of ["vm-exec", "fill-login", "create-room", "computer/select", "phone/claim", "device/mcp", "people/message", "pages/publish", "pages/unpublish", "request-credential", "request-sign-in", "threads/abc/close"]) {+ expect(outsideRouteRefused("POST", `/api/internal/${path}`), path).toBe(true);+ }+ });++ it("refuses a route nobody listed, and a listed path under another method", () => {+ expect(outsideRouteRefused("POST", "/api/internal/brand-new-route")).toBe(true);+ expect(outsideRouteRefused("GET", "/api/internal/coordinate-bots")).toBe(true);+ expect(outsideRouteRefused("DELETE", "/api/internal/memory")).toBe(true);+ });++ it("keeps what finishes the work here, asks a person or carries the lineage", () => {+ expect(outsideRouteRefused("POST", "/api/internal/hook")).toBe(false);+ expect(outsideRouteRefused("GET", "/api/internal/tool-result")).toBe(false);+ expect(outsideRouteRefused("POST", "/api/internal/options-card")).toBe(false);+ expect(outsideRouteRefused("POST", "/api/internal/coordinate-bots")).toBe(false);+ expect(outsideRouteRefused("post", "/api/internal/connectors/mcp")).toBe(false);+ expect(outsideRouteRefused("POST", "/api/internal/mcp-http/server-a")).toBe(false);+ });++ it("speaks plainly and tells the bot to finish where it is", () => {+ expect(OUTSIDE_REFUSAL).toContain("came in from outside");+ expect(OUTSIDE_REFUSAL).toContain("Finish what you can in this conversation");+ });+});diff --git a/server/host/outside-fence.ts b/server/host/outside-fence.tsnew file mode 100644index 0000000000..cf29bb11b4--- /dev/null+++ b/server/host/outside-fence.ts@@ -0,0 +1,71 @@+// Security invariant: a confined turn acts on words nobody here wrote, and every engine pre-allows OpenMausBot's own tools+// (only the harness can tell them apart). So of OpenMausBot's own routes it reaches only what this list names, and a route+// nobody listed is refused:+// - reads of this conversation's own work and what the bot may see;+// - what waits on a person's card (asks, proposed changes, a tool the engine asks about first);+// - handing work on, which carries the lineage (server/host/outside-lineage.ts).+const EXACT: ReadonlySet<string> = new Set([+ "POST /api/internal/hook",+ "POST /api/internal/tool-timing",+ "GET /api/internal/tool-result",+ "POST /api/internal/tool-result",+ "POST /api/internal/options-card",+ "POST /api/internal/escalate",+ "POST /api/internal/attach-file",+ "POST /api/internal/voice-note",+ "GET /api/internal/agents",+ "GET /api/internal/rooms",+ "GET /api/internal/room-targets",+ "GET /api/internal/threads",+ "POST /api/internal/threads",+ "GET /api/internal/assignment-status",+ "GET /api/internal/session-search",+ "GET /api/internal/session-read",+ "GET /api/internal/skills",+ "GET /api/internal/team-setup-catalog",+ "GET /api/internal/team-library",+ "GET /api/internal/engine-limits",+ "GET /api/internal/triggers",+ "GET /api/internal/trigger-events",+ "GET /api/internal/waits",+ "POST /api/internal/waits",+ "POST /api/internal/waits/cancel",+ "POST /api/internal/helpers/decide",+ "POST /api/internal/helpers/extract",+ // Each decides for itself, in plain words: what a confined turn may do there waits on a card, stays confined or is refused.+ "POST /api/internal/coordinate-bots",+ "POST /api/internal/post-to-room",+ "POST /api/internal/retry-thread",+ "POST /api/internal/trigger-requests",+ "POST /api/internal/manage-room",+ "POST /api/internal/memory",+ "POST /api/internal/memory/log",+ "POST /api/internal/team-memory",+ "POST /api/internal/profile-requests",+ "POST /api/internal/model-requests",+ "POST /api/internal/team-setup-requests",+ "POST /api/internal/bot-deletion-requests",+ "POST /api/internal/create-bot",+ "POST /api/internal/skills/stage",+ "POST /api/internal/mcp-servers",+ "GET /api/internal/mcp-servers",+ "GET /api/internal/shared-computers",+ "POST /api/internal/shared-computers",+ // A tool on one of these reaches here only after the engine asked a person: none is pre-allowed in a confined turn.+ "POST /api/internal/browser/mcp",+ "POST /api/internal/computer/mcp",+ "GET /api/internal/computer-control",+ "POST /api/internal/computer-control",+ "POST /api/internal/computer/journal",+ "POST /api/internal/connectors/mcp",+ "POST /api/internal/connectors/request",+ "POST /api/internal/data/mcp",+ "POST /api/internal/highlevel/mcp",+]);+const ASKED_MCP_PREFIX = "/api/internal/mcp-http/";++export const OUTSIDE_REFUSAL = "This work came in from outside, so it can't do that here. Finish what you can in this conversation and say plainly what a person would need to do.";++export function outsideRouteRefused(method: string, path: string): boolean {+ return !EXACT.has(`${method.toUpperCase()} ${path}`) && !path.startsWith(ASKED_MCP_PREFIX);+}diff --git a/server/host/outside-lineage.test.ts b/server/host/outside-lineage.test.tsnew file mode 100644index 0000000000..6510a94234--- /dev/null+++ b/server/host/outside-lineage.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it } from "vitest";++import { CLOUD_OUTSIDE_KEY } from "../cloud-sharing.ts";+import type { HandoffView } from "../coordinator.ts";+import type { RoutineRun } from "../routines.ts";+import { createOutsideLineage, type OutsideLineageDeps } from "./outside-lineage.ts";++function world(over: Partial<OutsideLineageDeps> = {}) {+ const tasks = new Map<string, { threadId: string; outside?: true }>();+ for (const threadId of ["chat", "hook-run", "teammate", "results", "person-work"]) tasks.set(threadId, { threadId });+ const lines = new Map<string, Array<Record<string, unknown>>>();+ const rooms = new Set<string>();+ const nodes = new Map<string, HandoffView>();+ const runs = new Map<string, RoutineRun>();+ const store = {+ botByThread: (threadId: string) => (tasks.has(threadId) ? { id: "bot" } : null),+ taskByThread: (_botId: string, threadId: string) => tasks.get(threadId),+ patchTask: (_botId: string, threadId: string, patch: { outside?: true }) => { Object.assign(tasks.get(threadId)!, patch); },+ messagesFor: (threadId: string) => lines.get(threadId) ?? [],+ groupByThread: (threadId: string) => (rooms.has(threadId) ? { id: threadId } : undefined),+ appendMessage: (threadId: string, row: Record<string, unknown>) => { lines.set(threadId, [...(lines.get(threadId) ?? []), row]); return row; },+ } as unknown as OutsideLineageDeps["store"];+ const lineage = createOutsideLineage({+ home: true, team: true, solo: () => false, store, confinedNow: () => false,+ activeRun: (threadId) => runs.get(threadId) ?? null, writer: () => undefined, starters: () => [], guestOpened: () => false, ownerPerson: () => false,+ node: (id) => nodes.get(id), active: () => [...nodes.values()], language: () => undefined, ...over,+ });+ return { lineage, tasks, lines, rooms, nodes, runs };+}+const webhookRun = (threadId: string, more: Partial<RoutineRun> = {}) => ({ id: "run-1", routineId: "hook", routineName: "Inbox", botId: "bot", threadId, status: "running", triggerSource: "webhook", ...more }) as RoutineRun;++describe("work from outside stays with that work", () => {+ it("keeps a conversation confined after its run has ended, for good", () => {+ const w = world();+ w.runs.set("hook-run", webhookRun("hook-run"));+ expect(w.lineage.cloudGuestDriven("hook-run")).toBe(true);+ w.lineage.mark("hook-run");+ w.runs.delete("hook-run");+ expect(w.lineage.cloudGuestDriven("hook-run")).toBe(true);+ expect(w.lineage.outsideDrivenThread("hook-run")).toBe(true);+ expect(w.lineage.cloudGuestDriven("chat")).toBe(false);+ });++ it("carries the record to what a marked conversation hands on, and no further than that", () => {+ const w = world();+ w.lineage.mark("hook-run");+ w.lineage.carry("hook-run", "teammate");+ expect(w.tasks.get("teammate")?.outside).toBe(true);+ w.lineage.carry("chat", "person-work");+ expect(w.tasks.get("person-work")?.outside).toBeUndefined();+ });++ it("lets confined work reach only what is confined already, and everything else reach anything", () => {+ const w = world();+ w.lineage.mark("hook-run");+ w.lineage.mark("teammate");+ expect(w.lineage.mayReach("hook-run", "person-work")).toBe(false);+ expect(w.lineage.mayReach("hook-run", "teammate")).toBe(true);+ expect(w.lineage.mayReach("chat", "hook-run")).toBe(true);+ expect(w.lineage.mayReach("chat", "person-work")).toBe(true);+ });++ it("counts a routine outside work wrote as confined on every kind of Cloud, and a person's only on a shared personal one when it is not the owner's", () => {+ const team = world({ writer: (id) => (id === "made" ? CLOUD_OUTSIDE_KEY : "p_someone") });+ expect(team.lineage.routineRunsConfined("made")).toBe(true);+ expect(team.lineage.routineRunsConfined("persons")).toBe(false);+ const shared = world({ team: false, writer: (id) => (id === "owners" ? "owner" : "guest"), ownerPerson: (key) => key === "owner" });+ expect(shared.lineage.routineRunsConfined("owners")).toBe(false);+ expect(shared.lineage.routineRunsConfined("guests")).toBe(true);+ });++ it("confines a run of a routine outside work wrote on a Team Cloud, and a conversation it opened", () => {+ const run = world({ writer: () => CLOUD_OUTSIDE_KEY });+ run.runs.set("chat", { ...webhookRun("chat"), triggerSource: "manual" } as RoutineRun);+ expect(run.lineage.cloudGuestDriven("chat")).toBe(true);+ expect(world({ starters: (id) => (id === "chat" ? [CLOUD_OUTSIDE_KEY] : []) }).lineage.cloudGuestDriven("chat")).toBe(true);+ });++ it("keeps a personal Cloud's webhook run at its bot's level, as the owner's", () => {+ const solo = world({ team: false, solo: () => true });+ solo.lineage.mark("hook-run");+ expect(solo.lineage.outsideDrivenThread("hook-run")).toBe(true);+ expect(solo.lineage.cloudGuestDriven("hook-run")).toBe(false);+ expect(solo.lineage.handsNoLevel("hook-run")).toBe(true);+ });++ it("off a Cloud nothing is confined, and the record only stops a level travelling", () => {+ const desktop = world({ home: false, team: false });+ desktop.lineage.mark("hook-run");+ expect(desktop.lineage.cloudGuestDriven("hook-run")).toBe(false);+ expect(desktop.lineage.mayReach("hook-run", "person-work")).toBe(true);+ expect(desktop.lineage.handsNoLevel("hook-run")).toBe(true);+ expect(desktop.lineage.handsNoLevel("chat")).toBe(false);+ });++ it("settles at each start from what ran before: own run threads, an event's own chat, work still handed on", () => {+ const w = world();+ w.nodes.set("root", { id: "root", rootId: "root", threadId: "hook-run", botId: "bot", status: "waiting" } as HandoffView);+ w.nodes.set("kid", { id: "kid", rootId: "root", parentId: "root", threadId: "teammate", botId: "bot", status: "queued" } as HandoffView);+ w.lineage.settle([webhookRun("hook-run")], () => "results");+ expect(w.tasks.get("hook-run")?.outside).toBe(true);+ expect(w.tasks.get("results")?.outside).toBe(true);+ expect(w.tasks.get("teammate")?.outside).toBe(true);+ expect(w.tasks.get("person-work")?.outside).toBeUndefined();+ });++ it("settling off a Cloud leaves the chat a wait's follow-up ran in as it was", () => {+ const desktop = world({ home: false, team: false });+ desktop.lineage.settle([webhookRun("chat", { eventSource: "wait" })], () => undefined);+ expect(desktop.tasks.get("chat")?.outside).toBeUndefined();+ const cloud = world();+ cloud.lineage.settle([webhookRun("hook-run", { eventSource: "wait" })], () => undefined);+ expect(cloud.tasks.get("hook-run")?.outside).toBe(true);+ });++ it("tells a person once why the bot works without its shell here, and only on a Team Cloud", () => {+ const w = world();+ w.lineage.mark("hook-run");+ w.lineage.personLineConfined("hook-run");+ w.lineage.personLineConfined("hook-run");+ expect(w.lines.get("hook-run")).toHaveLength(1);+ w.lineage.personLineConfined("chat");+ expect(w.lines.get("chat")).toBeUndefined();+ const solo = world({ team: false, solo: () => true });+ solo.lineage.mark("hook-run");+ solo.lineage.personLineConfined("hook-run");+ expect(solo.lines.get("hook-run")).toBeUndefined();+ });++ it("names outside work in its own words when the engine can't run confined", () => {+ const w = world();+ w.lineage.mark("hook-run");+ expect(w.lineage.guestEngineRefusal("hook-run")).toContain("Work from outside came into this conversation");+ });+});diff --git a/server/host/outside-lineage.ts b/server/host/outside-lineage.tsnew file mode 100644index 0000000000..2321a03f1c--- /dev/null+++ b/server/host/outside-lineage.ts@@ -0,0 +1,156 @@+// Security invariant: a confined turn is judged from records that stay. A run, a hand-off or a turn ends; the words that+// came in from outside stay in the conversation, so once work traces to outside that conversation, and everything it+// starts, retries, wakes, queues or schedules, stays outside. A person's line in such a conversation runs confined too:+// its engine reads those words as context, whoever typed last.+import { CLOUD_OUTSIDE_KEY, outsideDriven } from "../cloud-sharing.ts";+import type { HandoffView } from "../coordinator.ts";+import type { RoutineRun } from "../routines.ts";+import { serverLine } from "../server-lines.ts";+import type { Store } from "../store.ts";++/** What a turn hears when it tries to carry outside work into a conversation that is not outside. */+export const OUTSIDE_STAYS_HERE = "This work came in from outside, so it stays in this conversation and can't reach that one. Finish it here and say plainly what a person would need to do.";++const ROUTINE_FROM_BEFORE = "This routine was made before this update. Open it and save it once to run it with full access.";+const ROUTINE_FROM_OUTSIDE = "A webhook's run made or changed this routine, so it runs without full access. Open it and save it once to run it with full access.";+const CONVERSATION_FROM_BEFORE = "This conversation is from before My Cloud was only yours, so this bot works in it without a shell. Start a new conversation to use it fully.";+const CONVERSATION_FROM_OUTSIDE = "Work from outside came into this conversation, so this bot works in it without a shell. Start a new conversation to use it fully.";++const MAX_HOPS = 32;++export interface OutsideLineageDeps {+ /** A Cloud home of any kind; off a Cloud nothing is confined, the record only stops a level travelling. */+ home: boolean;+ team: boolean;+ /** A Cloud only its owner has ever used. */+ solo(): boolean;+ store: Pick<Store, "botByThread" | "taskByThread" | "patchTask" | "messagesFor" | "groupByThread" | "appendMessage">;+ /** This conversation's running turn was started confined. */+ confinedNow(threadId: string): boolean;+ activeRun(threadId: string): RoutineRun | null;+ writer(routineId: string): string | undefined;+ starters(threadId: string): (string | undefined)[];+ /** Someone but the owner opened it, on a personal Cloud. */+ guestOpened(threadId: string): boolean;+ ownerPerson(person: string | undefined): boolean;+ // Read lazily: index.ts builds the coordinator after this module.+ node(id: string): HandoffView | undefined;+ active(): HandoffView[];+ language(threadId: string): string | undefined;+}++export function createOutsideLineage(deps: OutsideLineageDeps) {+ const { store } = deps;++ const marked = (threadId: string): boolean => {+ const bot = store.botByThread(threadId);+ return Boolean(bot && store.taskByThread(bot.id, threadId)?.outside);+ };+ /** Once only, and for good: nothing clears it. A room's thread has no record of its own: a payload posted into it is. */+ const mark = (threadId: string): void => {+ const bot = store.botByThread(threadId);+ if (bot && !store.taskByThread(bot.id, threadId)?.outside) store.patchTask(bot.id, threadId, { outside: true });+ };++ /** The conversations that handed this work on, however deep. */+ function handedFrom(nodeId: string | undefined): string[] {+ const sources: string[] = [];+ let node = nodeId ? deps.node(nodeId) : undefined;+ for (let steps = 0; node && steps < MAX_HOPS; steps++) {+ if (node.id !== nodeId) sources.push(node.threadId);+ if (node.id === node.rootId) break;+ node = deps.node(node.parentId ?? node.rootId);+ }+ return sources;+ }++ /** A webhook or app event drove this conversation: its record, its run, a payload posted into it, or a conversation that handed it the work. */+ const outsideDrivenThread = (threadId: string): boolean => outsideDriven(threadId, {+ marked,+ webhookRun: (id) => deps.activeRun(id)?.triggerSource === "webhook",+ webhookPosted: (id) => store.messagesFor(id).some((line) => line.webhookPost),+ handedFrom: (id) => deps.active().filter((node) => node.threadId === id).flatMap((node) => handedFrom(node.id)),+ });++ /** A guest-driven turn runs in Ask whatever the bot's own level, with no shell. On a Cloud only its owner ever used, only what came in from outside is. */+ function cloudGuestDriven(threadId: string): boolean {+ if (!deps.home) return false;+ if (deps.confinedNow(threadId)) return true;+ const run = deps.activeRun(threadId);+ const writer = run ? deps.writer(run.routineId) : undefined;+ const madeFromOutside = writer === CLOUD_OUTSIDE_KEY || deps.starters(threadId).includes(CLOUD_OUTSIDE_KEY);+ if (deps.team) return madeFromOutside || outsideDrivenThread(threadId);+ if (deps.solo()) return madeFromOutside;+ if (deps.guestOpened(threadId)) return true;+ if (writer && !deps.ownerPerson(writer)) return true;+ if (!store.groupByThread(threadId)) return false;+ const person = store.messagesFor(threadId).findLast((line) => line.role === "user" && !line.peerAsk && line.sender?.id)?.sender?.id;+ return person !== undefined && !deps.ownerPerson(person);+ }++ /** Work a guest's turn hands a teammate is the guest's too, however deep. */+ const cloudGuestDrivenHandoff = (nodeId: string | undefined): boolean => deps.home && handedFrom(nodeId).some(cloudGuestDriven);++ /** Where the confinement rests on the conversation's own records, a thread opened from it would start with none, at the bot's own level. */+ const outsideWorkStaysHere = (threadId: string): boolean => cloudGuestDriven(threadId) && (deps.team || deps.solo());++ /** The one rule for every reach: confined work goes nowhere that is not confined already. */+ const mayReach = (fromThreadId: string, toThreadId: string): boolean => !cloudGuestDriven(fromThreadId) || cloudGuestDriven(toThreadId);++ /** A routine's runs are confined as this conversation is, so a confined turn may start it. */+ const routineRunsConfined = (routineId: string): boolean => {+ const writer = deps.writer(routineId);+ if (writer === CLOUD_OUTSIDE_KEY) return true;+ return !deps.team && !deps.solo() && !deps.ownerPerson(writer);+ };++ /** Everything this conversation starts stays what it is. */+ const carry = (fromThreadId: string, toThreadId: string): void => {+ if (outsideDrivenThread(fromThreadId) || outsideWorkStaysHere(fromThreadId)) mark(toThreadId);+ };++ /** A level comes down a hand-off only from work a person or their routine started. */+ const handsNoLevel = (threadId: string): boolean => outsideDrivenThread(threadId) || cloudGuestDriven(threadId);++ function confinedWhy(threadId: string): string {+ const run = deps.activeRun(threadId);+ const writer = run ? deps.writer(run.routineId) : undefined;+ if (run && writer === CLOUD_OUTSIDE_KEY) return ROUTINE_FROM_OUTSIDE;+ if (deps.team && outsideDrivenThread(threadId)) return CONVERSATION_FROM_OUTSIDE;+ return run && !deps.ownerPerson(writer) ? ROUTINE_FROM_BEFORE : CONVERSATION_FROM_BEFORE;+ }++ function guestEngineRefusal(threadId: string): string {+ const why = confinedWhy(threadId);+ return why !== CONVERSATION_FROM_BEFORE ? `This bot's AI can't run it that way. ${why}`+ : "This conversation is from before the Cloud was only yours, and this bot's AI can't work in it. Start a new conversation.";+ }++ /** A person's own line in a conversation outside work reached: once, in their words, why the bot works without its shell here. */+ function personLineConfined(threadId: string): void {+ if (!deps.team || !outsideDrivenThread(threadId)) return;+ const line = serverLine(deps.language(threadId), "server.outside.confinedHere");+ if (store.messagesFor(threadId).some((message) => message.kind === "activity" && message.tool?.name === line)) return;+ store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: line, ok: true } });+ }++ /** At every start: what ran without a record of its own, or was still in flight, keeps its lineage. */+ function settle(runs: readonly RoutineRun[], eventChat: (run: RoutineRun) => string | undefined): void {+ for (const run of runs) {+ if (run.triggerSource !== "webhook" || !run.threadId) continue;+ // Off a Cloud a wait's follow-up runs in the person's own chat.+ if (deps.home || run.eventSource !== "wait") mark(run.threadId);+ const chat = eventChat(run);+ if (chat) mark(chat);+ }+ for (const node of deps.active()) {+ if (handedFrom(node.id).some((threadId) => outsideDrivenThread(threadId))) mark(node.threadId);+ }+ }++ return {+ mark, carry, settle, mayReach, handsNoLevel, routineRunsConfined,+ outsideDrivenThread, cloudGuestDriven, cloudGuestDrivenHandoff, outsideWorkStaysHere,+ confinedWhy, guestEngineRefusal, personLineConfined,+ };+}diff --git a/server/host/outside-writes.test.ts b/server/host/outside-writes.test.tsnew file mode 100644index 0000000000..07c91333c3--- /dev/null+++ b/server/host/outside-writes.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it, vi } from "vitest";++import type { BotRecord } from "../store.ts";+import { createOutsideWrites, type OutsideWriteDeps } from "./outside-writes.ts";++const bot = { id: "chief", name: "Clive", color: "#123" } as unknown as Pick<BotRecord, "id" | "name" | "color">;+const requestOf = (proposed: { body: object }) => (proposed.body as { requestId: string }).requestId;++function world(over: Partial<OutsideWriteDeps> = {}) {+ const lines: Array<{ id: string; from?: { botId: string }; card?: Record<string, any> }> = [];+ const groups = new Map([["room", { id: "room", name: "Ops", bulletin: "as it was" }]]);+ const store = {+ appendMessage: (_threadId: string, row: any) => { const line = { ...row, id: `m${lines.length}` }; lines.push(line); return line; },+ messagesFor: () => lines,+ patchMessage: (_threadId: string, id: string, patch: any) => { Object.assign(lines.find((line) => line.id === id)!, patch); },+ botByThread: () => bot, bot: () => bot,+ group: (id: string) => groups.get(id),+ patchGroup: (id: string, patch: { bulletin: string }) => { const group = groups.get(id); if (group) Object.assign(group, patch); return group; },+ } as unknown as OutsideWriteDeps["store"];+ const writeMemory = vi.fn((): string | null => null);+ const decide = vi.fn();+ const writes = createOutsideWrites({ store, language: () => undefined, writeMemory, decide, notify: () => {}, ...over });+ return { writes, lines, groups, writeMemory, decide };+}++describe("what work from outside writes where later turns read it waits on a card", () => {+ it("leaves a room's bulletin as it was until a person says yes", () => {+ const w = world();+ const proposed = w.writes.submitBulletin(bot, "hook-run", { id: "room", name: "Ops" }, "new text");+ expect(proposed.body).toMatchObject({ state: "pending" });+ expect(w.groups.get("room")!.bulletin).toBe("as it was");+ expect(w.lines[0]!.card).toMatchObject({ options: ["Save", "Skip"], outsideWrite: { kind: "room-bulletin", roomId: "room", bulletin: "new text" } });+ expect(w.writes.resolve("hook-run", requestOf(proposed), "allow")).toMatchObject({ outcome: "allowed-once" });+ expect(w.groups.get("room")!.bulletin).toBe("new text");+ expect(w.lines[0]!.card!.answered).toBe("allow");+ });++ it("writes nothing when a person skips it, and answers twice as once", () => {+ const w = world();+ const proposed = w.writes.submitMemory(bot, "hook-run", { action: "append", text: "a note" });+ expect(w.writeMemory).not.toHaveBeenCalled();+ expect(w.writes.resolve("hook-run", requestOf(proposed), "deny")).toMatchObject({ outcome: "rejected" });+ expect(w.writeMemory).not.toHaveBeenCalled();+ expect(w.writes.resolve("hook-run", requestOf(proposed), "allow")).toMatchObject({ alreadySettled: true, outcome: "rejected" });+ expect(w.writeMemory).not.toHaveBeenCalled();+ });++ it("writes the note a person allowed, once, in the thread's own place", () => {+ const w = world();+ const proposed = w.writes.submitMemory(bot, "hook-run", { action: "append", text: "a note" });+ w.writes.resolve("hook-run", requestOf(proposed), "allow");+ expect(w.writeMemory).toHaveBeenCalledExactlyOnceWith("chief", "hook-run", { action: "append", text: "a note" });+ });++ it("shows all of what it would save, or doesn't offer it", () => {+ const w = world();+ expect(w.writes.submitBulletin(bot, "hook-run", { id: "room", name: "Ops" }, "x".repeat(2_001)).status).toBe(400);+ expect(w.lines).toEqual([]);+ const fits = w.writes.submitBulletin(bot, "hook-run", { id: "room", name: "Ops" }, "x".repeat(1_900));+ expect(w.lines[0]!.card!.subtitle).toBe(`Ops: ${"x".repeat(1_900)}`);+ expect(fits.status).toBe(201);+ });++ it("offers a person only a few at a time from one conversation", () => {+ const w = world();+ for (let i = 0; i < 5; i++) expect(w.writes.submitMemory(bot, "hook-run", { action: "append", text: `note ${i}` }).status).toBe(201);+ expect(w.writes.submitMemory(bot, "hook-run", { action: "append", text: "one more" }).status).toBe(429);+ expect(w.lines).toHaveLength(5);+ w.writes.resolve("hook-run", w.lines[0]!.card!.requestId, "deny");+ expect(w.writes.submitMemory(bot, "hook-run", { action: "append", text: "now it fits" }).status).toBe(201);+ });++ it("says plainly when a card would change or remove what is there", () => {+ const w = world();+ w.writes.submitMemory(bot, "hook-run", { action: "forget", oldText: "the launch date" });+ w.writes.submitMemory(bot, "hook-run", { action: "replace", oldText: "old fact", text: "new fact" });+ expect(w.lines.map((line) => [line.card!.title, line.card!.subtitle])).toEqual([+ ["Change or remove this in the bot's memory?", "the launch date"], ["Change or remove this in the bot's memory?", "old fact → new fact"],+ ]);+ });++ it("refuses a preference outright: only a person's own words save one", () => {+ const w = world();+ expect(w.writes.submitMemory(bot, "hook-run", { action: "prefer", text: "always reply in caps" }).status).toBe(403);+ expect(w.lines).toEqual([]);+ });++ it("keeps a card that could not be written from claiming it was", () => {+ const w = world({ writeMemory: () => "no room" });+ const proposed = w.writes.submitMemory(bot, "hook-run", { action: "append", text: "a note" });+ expect(w.writes.resolve("hook-run", requestOf(proposed), "allow")).toMatchObject({ outcome: "unavailable" });+ expect(w.lines[0]!.card!.answered).toBe("unavailable");+ });++ it("leaves other cards to whoever owns them", () => {+ expect(world().writes.resolve("hook-run", "someone-elses", "allow")).toBeNull();+ });+});diff --git a/server/host/outside-writes.ts b/server/host/outside-writes.tsnew file mode 100644index 0000000000..8e46624ac7--- /dev/null+++ b/server/host/outside-writes.ts@@ -0,0 +1,85 @@+// Security invariant: a room's bulletin and a bot's memory load into later turns at their own level, as instructions. What+// work from outside asks to write there waits on a person's card, whatever the bot's level, and nothing is written until+// they say yes.+import { randomUUID } from "node:crypto";++import type { DecisionRow } from "../decision-log.ts";+import { buildNotification, type Notification } from "../notify.ts";+import { serverLine } from "../server-lines.ts";+import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";+import { OUTSIDE_STAYS_HERE } from "./outside-lineage.ts";++type Write = NonNullable<NonNullable<Message["card"]>["outsideWrite"]>;+const MEMORY_ACTIONS: ReadonlySet<string> = new Set(["append", "replace", "remove", "supersede", "forget"]);+/** A card shows all of what it would save, or it isn't offered. */+const SHOWN_CHARS = 2_000;+const OPEN_CARDS = 5;+const TOOL = "outside_write";++export interface OutsideWriteDeps {+ store: Pick<Store, "appendMessage" | "messagesFor" | "patchMessage" | "botByThread" | "bot" | "group" | "patchGroup">;+ language(threadId: string): string | undefined;+ /** The error in words when it could not be written, or null. */+ writeMemory(botId: string, threadId: string, change: { action: string; text?: string; oldText?: string; until?: string }): string | null;+ decide(row: Omit<DecisionRow, "at">): void;+ notify(notification: Notification | null): void;+}++const speaker = (bot: Pick<BotRecord, "id" | "name" | "color">) => ({ botId: bot.id, name: bot.name, color: bot.color });++export function createOutsideWrites(deps: OutsideWriteDeps) {+ const { store } = deps;++ function apply(write: Write, threadId: string, botId: string | undefined): string | null {+ if (write.kind === "room-bulletin") return store.group(write.roomId) && store.patchGroup(write.roomId, { bulletin: write.bulletin }) ? null : "The room no longer exists.";+ if (!botId) return "The bot no longer exists.";+ const { kind: _kind, ...change } = write;+ return deps.writeMemory(botId, threadId, change);+ }++ function propose(from: Pick<BotRecord, "id" | "name" | "color">, threadId: string, title: string, subtitle: string, write: Write) {+ if (subtitle.length > SHOWN_CHARS) return { status: 400, body: { error: `This is too long for a person to review on a card: keep it under ${SHOWN_CHARS} characters.` } };+ if (store.messagesFor(threadId).filter((line) => line.card?.outsideWrite && !line.card.answered).length >= OPEN_CARDS) {+ return { status: 429, body: { error: "A person already has several of these to look at from this conversation. Finish without saving more." } };+ }+ const requestId = `outside-write-${randomUUID()}`;+ const language = deps.language(threadId);+ const message = store.appendMessage(threadId, {+ role: "bot", kind: "options", from: speaker(from),+ card: { title, subtitle, options: [serverLine(language, "server.outside.save"), serverLine(language, "server.outside.skip")], requestId, tool: TOOL, outsideWrite: write },+ });+ deps.decide({ threadId, requestId, botId: from.id, botName: from.name, tool: TOOL, summary: title, decision: "card-shown", source: "outside-write" });+ deps.notify(buildNotification("approval", { id: from.id, name: from.name }, threadId, title));+ return { status: 201, body: { status: "proposed", state: "pending", requestId, messageId: message.id, message: "This came from outside work, so it is not saved yet: a person sees a card and decides. Do not wait for it and do not try another way." } };+ }++ return {+ submitBulletin(from: Pick<BotRecord, "id" | "name" | "color">, threadId: string, room: Pick<GroupRecord, "id" | "name">, bulletin: string) {+ return propose(from, threadId, serverLine(deps.language(threadId), "server.outside.bulletinTitle"), `${room.name}: ${bulletin}`, { kind: "room-bulletin", roomId: room.id, bulletin });+ },++ submitMemory(from: Pick<BotRecord, "id" | "name" | "color">, threadId: string, body: { action?: unknown; text?: unknown; oldText?: unknown; until?: unknown }) {+ const action = typeof body?.action === "string" ? body.action : "";+ if (!MEMORY_ACTIONS.has(action)) return { status: 403, body: { error: OUTSIDE_STAYS_HERE } };+ const change = { action, ...(typeof body.text === "string" ? { text: body.text } : {}), ...(typeof body.oldText === "string" ? { oldText: body.oldText } : {}), ...(typeof body.until === "string" ? { until: body.until } : {}) };+ const title = serverLine(deps.language(threadId), action === "append" ? "server.outside.memoryTitle" : "server.outside.memoryChangeTitle");+ return propose(from, threadId, title, [change.oldText, change.text].filter(Boolean).join(" → ") || action, { kind: "memory", ...change });+ },++ /** A person's answer to the card; null when the request is not one of these cards. */+ resolve(threadId: string, requestId: string, behavior: string): { ok: true; outcome: string; alreadySettled?: true } | null {+ const message = store.messagesFor(threadId).find((line) => line.card?.requestId === requestId && line.card.outsideWrite);+ const card = message?.card;+ const write = card?.outsideWrite;+ if (!message || !card || !write) return null;+ if (card.answered) return { ok: true, outcome: card.answered === "allow" ? "allowed-once" : "rejected", alreadySettled: true };+ const botId = message.from?.botId ?? store.botByThread(threadId)?.id;+ const bot = botId ? store.bot(botId) : undefined;+ const allowed = behavior === "allow";+ const problem = allowed ? apply(write, threadId, botId) : null;+ store.patchMessage(threadId, message.id, { card: { ...card, answered: !allowed ? "deny" : problem ? "unavailable" : "allow", ...(problem ? { dismissed: true } : {}) } });+ deps.decide({ threadId, requestId, botId, botName: bot?.name, tool: TOOL, summary: card.title, decision: allowed && !problem ? "user-approved" : "user-denied", source: "user" });+ return { ok: true, outcome: !allowed ? "rejected" : problem ? "unavailable" : "allowed-once" };+ },+ };+}diff --git a/server/host/person-inbox.test.ts b/server/host/person-inbox.test.tsindex 5460176adb..20673fd4bb 100644--- a/server/host/person-inbox.test.ts+++ b/server/host/person-inbox.test.ts@@ -249,3 +249,15 @@ describe("the inbox itself", () => {expect(f.team.inbox.personOf(f.inboxOf(CLEO).threadId)).toBe(key(CLEO.email));});});++describe("what a confined conversation says", () => {+ it("reaches the person it asks as a notification, and never lands as a line in anybody's inbox", () => {+ const f = fixture({ confined: ["rep-shared"] });+ f.bots.find((bot) => bot.id === "reporter")!.tasks.push({ threadId: "rep-shared", title: "Weekly numbers" });+ f.store.appendMessage("rep-shared", { role: "bot", kind: "options", text: "Run a command?", card: card("req-1") });+ const question = ask("reporter", "Reporter", "rep-shared");+ expect(f.team.route(question)).toEqual({ ...question, forPerson: key(BEN.email) });+ expect(f.notified).toEqual([]);+ expect(f.team.needsYou(session(BEN.email))).toEqual([]);+ });+});diff --git a/server/host/person-inbox.ts b/server/host/person-inbox.tsindex 548ab708ed..c8fca39dae 100644--- a/server/host/person-inbox.ts+++ b/server/host/person-inbox.ts@@ -89,6 +89,8 @@ export interface Delivery {}export interface PersonInboxDeps {+ /** Security invariant: an inbox is a person's own chat with their Chief at its own level, so what a confined conversation says never lands there. */+ confined?(threadId: string): boolean;team: CloudTeam | null;dataDir: string;store: Pick<Store, "bots" | "bot" | "tasks" | "taskByThread" | "createTask" | "patchTask" | "patchGroup" | "appendMessage" | "patchMessage" | "messagesFor" | "groupByThread" | "onChange">;@@ -377,6 +379,7 @@ export function createPersonInbox(deps: PersonInboxDeps) {if (!team || notification.forPerson || (!ASK_NOTIFICATIONS.has(notification.kind) && !result)) return notification;const person = deps.askedPerson(notification.botId, notification.threadId);if (!person || personOf(notification.threadId)) return notification;+ if (deps.confined?.(notification.threadId)) return { ...notification, forPerson: person };const own = audienceMember(deps.audienceOf(notification.threadId)) === person;if (own && !how.routine && !deps.handedFrom?.(notification.threadId)) return notification;const card = notification.kind === "approval" || notification.kind === "question" ? openCard(notification.botId, notification.threadId) : undefined;diff --git a/server/host/question-routing.test.ts b/server/host/question-routing.test.tsindex 09863dd369..ab27d8d428 100644--- a/server/host/question-routing.test.ts+++ b/server/host/question-routing.test.ts@@ -10,7 +10,7 @@ const FUCHS = bot("fuchs", "Fuchs", { chiefOfStaff: true });const DACHS = bot("dachs", "Dachs");const OTTER = bot("otter", "Otter");-function world(options: { live?: string[]; privateTo?: string; steers?: boolean; takesAnswers?: boolean; unattended?: string[] } = {}) {+function world(options: { live?: string[]; privateTo?: string; steers?: boolean; takesAnswers?: boolean; unattended?: string[]; confined?: string[] } = {}) {const threads = new Map<string, Message[]>();let ids = 0;const rows = (threadId: string) => threads.get(threadId) ?? [];@@ -66,6 +66,7 @@ function world(options: { live?: string[]; privateTo?: string; steers?: boolean;settleSignIns: (parked) => { settled.push(parked.id); },keptPrivate: (child, requester) => child.threadId === options.privateTo && requester.threadId !== options.privateTo,steer: async (threadId, text) => { if (options.steers === false) return false; steered.push({ threadId, text }); return true; },+ mayReach: (fromThreadId, toThreadId) => !(options.confined ?? []).includes(fromThreadId) || (options.confined ?? []).includes(toThreadId),};return { routing: createQuestionRouting(deps), store, rows, node, nodes, answeredNodes, answeredLive, settled, steered };}@@ -286,3 +287,27 @@ describe("a message to the thread where work the sender handed on is running", (expect(w.steered).toEqual([]);});});++describe("work from outside stays out of a person's work", () => {+ it("neither answers a parked question nor steers into running work in a thread that is not confined", async () => {+ const parked = world({ confined: ["inbox"] });+ parked.node({ question: "Which format?" });+ expect(await parked.routing.relay({ sender: FUCHS, senderThreadId: "inbox", target: DACHS, message: "Excel", threadId: "work" })).toBeUndefined();+ expect(parked.answeredNodes).toEqual([]);+ const named = world({ confined: ["inbox"] });+ const asked = named.node({ question: "Which format?" });+ expect(await named.routing.relay({ sender: FUCHS, senderThreadId: "inbox", target: DACHS, message: "Excel", answers: asked.id })).toMatchObject({ outcome: "failed" });+ expect(named.answeredNodes).toEqual([]);+ const running = world({ confined: ["inbox"] });+ running.node({ status: "running" });+ expect(await running.routing.relay({ sender: FUCHS, senderThreadId: "inbox", target: DACHS, message: "Excel", threadId: "work" })).toBeUndefined();+ expect(running.steered).toEqual([]);+ });++ it("still reaches work of its own lineage", async () => {+ const own = world({ confined: ["inbox", "work"] });+ own.node({ status: "running" });+ expect(await own.routing.relay({ sender: FUCHS, senderThreadId: "inbox", target: DACHS, message: "Excel", threadId: "work" })).toMatchObject({ outcome: "injected" });+ expect(own.steered).toHaveLength(1);+ });+});diff --git a/server/host/question-routing.ts b/server/host/question-routing.tsindex 7b53081e73..93057b288d 100644--- a/server/host/question-routing.ts+++ b/server/host/question-routing.ts@@ -36,6 +36,8 @@ export interface QuestionRoutingDeps {/** Hands `text` to the turn running in `threadId`, read at its next step as a person's line sent mid-turn is; false when* its engine cannot take it now. */steer(threadId: string, text: string): Promise<boolean>;+ /** Work the sender's conversation carries may reach this thread: confined work reaches only what is confined already. */+ mayReach(fromThreadId: string, toThreadId: string): boolean;}const ENDED: ReadonlySet<HandoffView["status"]> = new Set(["completed", "failed", "cancelled"]);@@ -94,9 +96,9 @@ export function createQuestionRouting(deps: QuestionRoutingDeps) {async function relay(input: { sender: BotRecord; senderThreadId: string; senderNode?: HandoffView; target: BotRecord; message: string; answers?: string;threadId?: string; sentThisTurn?: ReadonlySet<string> }): Promise<PeerDeliveryReceipt | undefined> {const { sender, target, message } = input;- const waiting = waitingOn(target);+ const waiting = waitingOn(target).filter((one) => deps.mayReach(input.senderThreadId, one.threadId));const ownWork = (node: HandoffView | undefined): node is HandoffView => node !== undefined && node.threadId === input.threadId- && !input.sentThisTurn?.has(node.id) && handedOnBy(node, sender.id);+ && !input.sentThisTurn?.has(node.id) && handedOnBy(node, sender.id) && deps.mayReach(input.senderThreadId, node.threadId);const pick = input.answers !== undefined ? waiting.find((one) => one.node?.id === input.answers): waiting.find((one) => one.node !== undefined && input.senderNode?.carrying?.includes(one.node.id) === true)?? waiting.find((one) => ownWork(one.node) && (one.card !== undefined || !one.node.cards?.length));diff --git a/server/host/team-messages.test.ts b/server/host/team-messages.test.tsindex b224daa851..b448a4c621 100644--- a/server/host/team-messages.test.ts+++ b/server/host/team-messages.test.ts@@ -173,6 +173,13 @@ describe("@Ben", () => {expect(f.continued, "nobody's turn carries on: a person asked").toEqual([]);});+ it("takes no reply from a confined conversation to anybody's inbox, whoever it names", () => {+ const f = fixture({ confined: ["scout-main"] });+ const reply = f.store.appendMessage("scout-main", { role: "bot", kind: "text", text: "Done. @Ben please review.", turnId: "t1" });+ f.store.patchMessage("scout-main", reply.id, { turnTerminal: true, turnSucceeded: true });+ expect(f.notified).toEqual([]);+ });+it("reads a bot's settled reply once, and only where the person can see it", () => {const f = fixture();const reply = f.store.appendMessage("scout-main", { role: "bot", kind: "text", text: "Done. @Ben please review.", turnId: "t1" });diff --git a/server/host/team-messages.ts b/server/host/team-messages.tsindex 9606696b34..3930e52820 100644--- a/server/host/team-messages.ts+++ b/server/host/team-messages.ts@@ -56,6 +56,8 @@ export interface TeamMessagesDeps {starters: { get(threadId: string): string | undefined; set(threadId: string, person: string): void };/** What one person may see, as their own session would. */sees(person: { email: string; role: TeamRole }): { bot(botId: string): boolean; thread(threadId: string): boolean };+ /** Security invariant: a confined conversation's words reach nobody's inbox by naming them. */+ confined?(threadId: string): boolean;notify(notification: Notification): void;/** What the inbox needs from the server: whose asks are whose, hand-offs, a bot carrying on, the assistant's reads. */inbox: Pick<PersonInboxDeps, "askedPerson" | "handedFrom" | "continueTurn"> & Partial<Pick<PersonInboxDeps, "notes" | "ensureOwnBot" | "changed">> & {@@ -94,7 +96,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {const { representative, ...wiring } = deps.inbox;const inbox = createPersonInbox({- notes: (botId) => loadMemory(botId)?.text ?? "", ...wiring, team, dataDir: deps.dataDir, store, starters: deps.starters, audienceOf: deps.audienceOf, personKeyOf: keyOf,+ notes: (botId) => loadMemory(botId)?.text ?? "", ...wiring, ...(deps.confined ? { confined: deps.confined } : {}), team, dataDir: deps.dataDir, store, starters: deps.starters, audienceOf: deps.audienceOf, personKeyOf: keyOf,send: deps.notify, now, person: (key) => byKey(key),sees: (key, threadId) => { const one = byKey(key); return one ? deps.sees(one).thread(threadId) : false; },...(representative ? { representative: createRepresentative({ now, timeZone: () => currentTimeZone(), ...representative }) } : {}),@@ -238,7 +240,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {if (handledTurns.size > MAX_HANDLED_TURNS) handledTurns.delete(handledTurns.values().next().value!);const told = toldThisTurn.get(threadId) ?? new Set<string>();toldThisTurn.delete(threadId);- if (line.turnSucceeded !== true) return;+ if (line.turnSucceeded !== true || deps.confined?.(threadId)) return;const group = store.groupByThread(threadId);const speaker = line.from?.botId ? store.bot(line.from.botId) : store.botByThread(threadId);if (!speaker) return;diff --git a/server/host/work-thread.test.ts b/server/host/work-thread.test.tsindex 9efc051acf..b2854ee065 100644--- a/server/host/work-thread.test.ts+++ b/server/host/work-thread.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import type { TaskRecord } from "../store.ts";+import { OUTSIDE_STAYS_HERE } from "./outside-lineage.ts";import { workThreadFor } from "./work-thread.ts";const by = (botId: string, name: string, threadId: string): TaskRecord["openedBy"] => ({ botId, name, threadId, kind: "work", at: 0 });@@ -20,7 +21,7 @@ const store = {};const fromLiaison = (thread: string, notice: boolean, also: (task: TaskRecord) => boolean = () => true,answering: { botId: string; threadId: string } | undefined = run1) => workThreadFor(store,- { botId: "bugfixer", botName: "Bugfixer", fromBotId: "liaison", fromThreadId: "liaison-work", thread, notice, answering, also });+ { botId: "bugfixer", botName: "Bugfixer", fromBotId: "liaison", fromThreadId: "liaison-work", thread, notice, answering, also, reach: () => true });describe("workThreadFor", () => {it("keeps a thread the sender opened", () => {@@ -35,13 +36,19 @@ describe("workThreadFor", () => {it("takes that notice only for the running assignment's requester, not a stale opener of a reused thread", () => {expect(() => fromLiaison("run-0", true)).toThrow(/is not a thread you opened on Bugfixer/);expect(() => workThreadFor(store, { botId: "bugfixer", botName: "Bugfixer", fromBotId: "liaison", fromThreadId: "liaison-work", thread: "run-1",- notice: true, answering: undefined, also: () => true })).toThrow(/is not a thread you opened on Bugfixer/);+ notice: true, answering: undefined, also: () => true, reach: () => true })).toThrow(/is not a thread you opened on Bugfixer/);expect(() => fromLiaison("run-1", true, () => true, { botId: "someone", threadId: "run-1" })).toThrow(/is not a thread you opened on Bugfixer/);});+ it("says in plain words that confined work stays out of a thread it may not reach, opened by the sender or not", () => {+ const reach = () => false;+ expect(() => workThreadFor(store, { botId: "bugfixer", botName: "Bugfixer", fromBotId: "liaison", fromThreadId: "liaison-chat", thread: "opened-by-liaison", notice: false, answering: undefined, also: () => true, reach })).toThrow(OUTSIDE_STAYS_HERE);+ expect(() => workThreadFor(store, { botId: "bugfixer", botName: "Bugfixer", fromBotId: "liaison", fromThreadId: "liaison-chat", thread: "run-1", notice: true, answering: run1, also: () => true, reach })).toThrow(OUTSIDE_STAYS_HERE);+ });+it("refuses any other thread, an archived one, or one `also` rules out, even for a notice", () => {const anyOther = { ...store, taskByThread: () => task("someone-elses") };- expect(() => workThreadFor(anyOther, { botId: "bugfixer", botName: "Bugfixer", fromBotId: "liaison", fromThreadId: "liaison-chat", thread: "someone-elses", notice: true, answering: run1, also: () => true }))+ expect(() => workThreadFor(anyOther, { botId: "bugfixer", botName: "Bugfixer", fromBotId: "liaison", fromThreadId: "liaison-chat", thread: "someone-elses", notice: true, answering: run1, also: () => true, reach: () => true })).toThrow(/is not a thread you opened on Bugfixer/);expect(() => fromLiaison("archived-run", true, () => true, { botId: "bugfixer", threadId: "archived-run" })).toThrow(/is not a thread you opened/);expect(() => fromLiaison("run-1", true, () => false)).toThrow(/is not a thread you opened/);diff --git a/server/host/work-thread.ts b/server/host/work-thread.tsindex 5ad8c0d255..30acde789c 100644--- a/server/host/work-thread.ts+++ b/server/host/work-thread.ts@@ -1,4 +1,5 @@import type { Store, TaskRecord } from "../store.ts";+import { OUTSIDE_STAYS_HERE } from "./outside-lineage.ts";/** Where coordinate_bots sends to a teammate outside a room, by its `thread`: "standing" is the sender conversation's one* work thread with that teammate (undefined until it is opened), "new" opens one (undefined), and any other value is the id@@ -7,11 +8,14 @@ import type { Store, TaskRecord } from "../store.ts";* never new work.* Throws when it is neither. `also` narrows which threads count. */export function workThreadFor(store: Pick<Store, "workThread" | "taskByThread">, input: { botId: string; botName: string; fromBotId: string; fromThreadId: string;- thread: string; notice: boolean; answering: { botId: string; threadId: string } | undefined; also: (task: TaskRecord) => boolean }): TaskRecord | undefined {- const { botId, thread, also } = input;+ thread: string; notice: boolean; answering: { botId: string; threadId: string } | undefined; also: (task: TaskRecord) => boolean;+ /** Whether the sender's work may reach this thread at all; when it may not, it says so in its own words. */+ reach: (task: TaskRecord) => boolean }): TaskRecord | undefined {+ const { botId, thread, also, reach } = input;if (thread === "new") return undefined;- if (thread === "standing") return store.workThread(botId, input.fromBotId, input.fromThreadId, false, also);+ if (thread === "standing") return store.workThread(botId, input.fromBotId, input.fromThreadId, false, (task) => also(task) && reach(task));const task = store.taskByThread(botId, thread);+ if (task && !reach(task)) throw new Error(OUTSIDE_STAYS_HERE);const usable = task !== undefined && task.archivedAt === undefined && also(task);if (usable && task.openedBy?.botId === input.fromBotId && !task.openedBy.roomLane) return task;const handedWork = usable && input.answering?.botId === botId && input.answering.threadId === thread;diff --git a/server/index.ts b/server/index.tsindex 2f9d2519f7..867058fadb 100644--- a/server/index.ts+++ b/server/index.ts@@ -272,7 +272,7 @@ import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { brokerPaimport { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";import { createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts";-import { CLOUD_PERSONAL_REFUSAL, type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY, outsideDriven } from "./cloud-sharing.ts";+import { CLOUD_PERSONAL_REFUSAL, type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";import { createCloudMoveRoutes } from "./cloud-move-http.ts";import { RESTART_EXIT_CODE } from "./restart.ts";import { applyIncludedXMessage, holdIncludedServices, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { createResearchAvailability } from "./research.ts";@@ -625,6 +625,7 @@ import { createReactionRoutes } from "./routes/reactions.ts";import { createReactions, withReactionNotes, type Reactor } from "./reactions.ts";import { createPersonReplies } from "./person-replies.ts";import { personKey, relayedPersonKey } from "./person-key.ts";+import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts";@@ -1002,19 +1003,6 @@ function cloudGuestOpened(threadId: string): boolean {const guestDrivenTurns = new Map<string, string>();-/** The conversations that handed this work on, however deep. */-function handedFrom(nodeId: string | undefined): string[] {- const sources: string[] = [];- let node = nodeId ? coordinator.node(nodeId) : undefined;- for (let steps = 0; node && steps < 32; steps++) {- if (node.id !== nodeId) sources.push(node.threadId);- if (node.id === node.rootId) break;- node = coordinator.node(node.parentId ?? node.rootId);- }- return sources;-}-/** Work a guest's turn hands a teammate is the guest's too, however deep. */-const cloudGuestDrivenHandoff = (nodeId: string | undefined) => Boolean(CLOUD_HOME) && handedFrom(nodeId).some(cloudGuestDriven);/** Never the owner when a guest drives the source, so the new conversation is confined like it. On a Team Cloud it is the* source's audience: one person's only from their own private chat (else a shared chat's work reads their notes). */@@ -1035,35 +1023,7 @@ function parentThreadModel(botId: string, parentThreadId: string): { modelSelectreturn { modelSelection, ...(needsAsk ? { approvalMode: "ask" as const } : {}) };}-const ROUTINE_FROM_BEFORE = "This routine was made before this update. Open it and save it once to run it with full access.";-const ROUTINE_FROM_OUTSIDE = "A webhook's run made or changed this routine, so it runs without full access. Open it and save it once to run it with full access.";-const CONVERSATION_FROM_BEFORE = "This conversation is from before My Cloud was only yours, so this bot works in it without a shell. Start a new conversation to use it fully.";-function confinedWhy(threadId: string): string {- const run = activeRoutineRunForThread(threadId);- const writer = run ? cloudRoutineAuthors?.writer(run.routineId) : undefined;- return run && writer === CLOUD_OUTSIDE_KEY ? ROUTINE_FROM_OUTSIDE : run && !cloudOwnerPerson(writer) ? ROUTINE_FROM_BEFORE : CONVERSATION_FROM_BEFORE;-}-function guestEngineRefusal(threadId: string): string {- const why = confinedWhy(threadId);- return why !== CONVERSATION_FROM_BEFORE ? `This bot's AI can't run it that way. ${why}`- : "This conversation is from before the Cloud was only yours, and this bot's AI can't work in it. Start a new conversation.";-}-/** A webhook or app event drove this conversation: its run, a payload posted into it, or a conversation that handed it the work. */-const outsideDrivenThread = (threadId: string) => outsideDriven(threadId, { webhookRun: (id) => activeRoutineRunForThread(id)?.triggerSource === "webhook",- webhookPosted: (id) => store.messagesFor(id).some((line) => line.webhookPost), handedFrom: (id) => coordinator.active().filter((node) => node.threadId === id).flatMap((node) => handedFrom(node.id)) });-/** A guest-driven turn runs in Ask whatever the bot's own level, with no shell. On a Cloud only its owner ever used, only what came in from outside is. */-/** Security: where the confinement rests on the conversation's own records, a thread opened from it would start with none, at the bot's own level. */ const outsideWorkStaysHere = (threadId: string) => cloudGuestDriven(threadId) && (Boolean(CLOUD_TEAM) || cloudHome?.solo() === true); function cloudGuestDriven(threadId: string): boolean {- if (!CLOUD_HOME) return false; if (CLOUD_TEAM) return guestDrivenTurns.has(threadId) || outsideDrivenThread(threadId);- const run = activeRoutineRunForThread(threadId);- const writer = run ? cloudRoutineAuthors?.writer(run.routineId) : undefined;- if (cloudHome?.solo()) return guestDrivenTurns.has(threadId) || writer === CLOUD_OUTSIDE_KEY || cloudThreadStarters(threadId).includes(CLOUD_OUTSIDE_KEY);- if (guestDrivenTurns.has(threadId) || cloudGuestOpened(threadId)) return true;- if (writer && !cloudOwnerPerson(writer)) return true;- if (!store.groupByThread(threadId)) return false;- const person = store.messagesFor(threadId).findLast((line) => line.role === "user" && !line.peerAsk && line.sender?.id)?.sender?.id;- return person !== undefined && !cloudOwnerPerson(person);-}/** Loopback is not the owner on a Cloud home: only processes on the machine (a bot's shell) arrive that way. */function cloudOwnerSession(auth: RequestAuth): boolean {@@ -1098,10 +1058,8 @@ function cardAnswerRefusal(auth: RequestAuth, threadId: string, requestId: strin? "A local service can only decline this request. Approve or answer it in OpenMausBot while signed in.": null;}- if (!auth.scopes.includes("admin") && store.messagesFor(threadId).some(message =>- message.card?.requestId === requestId && message.card.teamMemoryRequest)) {- return "Only a workspace admin can review shared team memory.";- }+ const reviewed = auth.scopes.includes("admin") ? undefined : store.messagesFor(threadId).find(message => message.card?.requestId === requestId && (message.card.teamMemoryRequest || message.card.outsideWrite))?.card;+ if (reviewed) return reviewed.outsideWrite ? "Only a workspace admin can save what came in from outside." : "Only a workspace admin can review shared team memory.";// A Cloud guest may read along but never answer: its words would reach the owner's turn and a lent Mac.if (CLOUD_PERSONAL) return cloudCardRefusal(auth);if (auth.scopes.includes("admin") || !sharedMembership()) return null; const setupRefused = CLOUD_TEAM ? botAccess.cardRefusal(auth, threadId, requestId) : null; if (setupRefused) return setupRefused;@@ -1181,7 +1139,7 @@ const { viewerFor, threadOwner, visibleTo, forgetVisibility, threadShown, subjecteam: Boolean(CLOUD_TEAM), audiencesFor: (viewer) => teamHost.audiencesFor(viewer), threadsReferencing }); if (CLOUD_TEAM) hideOthersSyncFolders(() => store.bots, threadShown); const botAccess = createBotAccessHost({ visibleFor: (auth) => visibleTo(viewerFor(auth)), store: () => store, routines: () => routines, threadOwner, routineWriter: (id) => cloudRoutineAuthors?.writer(id) }), { levelOf } = botAccess; const accessRequests = createAccessRequests({ team: CLOUD_TEAM, store: () => store, people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, inbox: () => teamMessages.inbox, visibleTo, levelOf, writeAccess: (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access), record: (row, by) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: by, email: by } }) });function recentWorkFilter(threadId: string): { include?: (threadId: string) => boolean; privateThread?: (threadId: string) => boolean } {- return CLOUD_TEAM ? { include: teamHost.readableFrom(threadId), privateThread: (id) => teamHost.privateTo(id) !== null } : CLOUD_HOME ? { include: cloudOwnerOnlyThread } : {};+ return CLOUD_TEAM ? { include: (id) => teamHost.readableFrom(threadId)(id) && outsideLineage.mayReach(id, threadId), privateThread: (id) => teamHost.privateTo(id) !== null } : CLOUD_HOME ? { include: cloudOwnerOnlyThread } : {};}function recentWorkSources(bot: BotRecord) {@@ -1201,7 +1159,7 @@ function autoRecallPrompt(bot: BotRecord, threadId: string, message: string, optif (bot.memoryEnabled === false || !autoRecallEnabled(cfg)) return "";const roomByThread = opts.conversations ? recallRooms(store.groups, bot, roomFeedsBot) : new Map<string, GroupRecord>();const threadIds = opts.conversations- ? recallThreadIds(bot, roomByThread).filter((id) => id !== threadId && threadReadableFrom(threadId)(id))+ ? recallThreadIds(bot, roomByThread).filter((id) => id !== threadId && threadReadableFrom(threadId)(id) && outsideLineage.mayReach(id, threadId)): [];try {const recalled = buildRecall({@@ -2841,6 +2799,13 @@ const store = new Store(() => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale,() => sharedMembership() ? undefined : cfg.profile?.name,);+const outsideLineage = createOutsideLineage({+ home: Boolean(CLOUD_HOME), team: Boolean(CLOUD_TEAM), solo: () => cloudHome?.solo() === true, store,+ confinedNow: (threadId) => guestDrivenTurns.has(threadId), activeRun: activeRoutineRunForThread,+ writer: (routineId) => cloudRoutineAuthors?.writer(routineId), starters: (threadId) => cloudThreadStarters(threadId), guestOpened: cloudGuestOpened, ownerPerson: cloudOwnerPerson,+ node: (id) => coordinator.node(id), active: () => coordinator.active(), language: (threadId) => threadLanguage(threadId),+});+const { outsideDrivenThread, cloudGuestDriven, cloudGuestDrivenHandoff, outsideWorkStaysHere, confinedWhy, guestEngineRefusal } = outsideLineage;const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusal, cloudThreadStarters, cloudLendingView, cloudReportFromOthers, roomTurnStarted, roomTurnEnded, roomRun } = createCloudLendingTurns({store, cloudHome: CLOUD_HOME !== null, team: CLOUD_TEAM?.name ?? null, directRequest: (threadId) => directRequestOwners.get(threadId), threadStarter: (threadId) => threadStarters.get(threadId),ownerPerson: cloudProvenOwnerPerson, cardAnswerer: cloudCardAnswerer, activeRoutineRun: activeRoutineRunForThread, ownerStartedRun: (runId) => ownerStartedRoutineRuns.has(runId),@@ -2852,7 +2817,7 @@ const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, leconst { stopThreadForPerson, stopOnTypedCommand, restartForPerson, noteTeammatesLeftRunning } = createPersonStop({store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),-}); const teamMessages = createTeamMessages({ team: CLOUD_TEAM, dataDir: DATA_DIR, store, people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });+}); const teamMessages = createTeamMessages({ team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,@@ -3143,7 +3108,7 @@ function peerReviewRequired(bot: BotRecord, threadId: string): boolean {}const delegatedLevel = createDelegatedLevel({ store, node: id => coordinator.node(id), sourceLevel: sourceApprovalMode, turnLevel: approvalModeForTurn,- driverKind: bot => registry.cliTarget(bot.modelSelection.instanceId)?.driverKind, guestDriven: cloudGuestDriven });+ driverKind: bot => registry.cliTarget(bot.modelSelection.instanceId)?.driverKind, guestDriven: cloudGuestDriven, handsNoLevel: outsideLineage.handsNoLevel });const liveApprovalMode = createLiveApprovalMode({ store, turnLevel: approvalModeForTurn });function roomTurnApprovalMode(bot: BotRecord, threadId: string, orchestration?: GroupTurnOrchestration): ApprovalMode {@@ -3935,7 +3900,7 @@ const questionRouting = createQuestionRouting({ store, active: () => coordinatorunattended: (botId, threadId) => teammatePrompts.unattendedWork(botId, threadId),answerLive: async (threadId, requestId, text) => await answerRequest(threadId, botForThread(store.botByThread(threadId)?.id ?? "", threadId)?.modelSelection.instanceId ?? "", requestId, "answer", text) === "answered", settleSignIns: (node) => signInSettle.answeredElsewhere(node),keptPrivate: (node, requester) => keptPrivate({ child: teamHost.privateTo(node.threadId), parent: teamHost.privateTo(requester.threadId) }),- steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused" });+ steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({dataDir: DATA_DIR,now: Date.now, wrote: handoffTicks.kick,@@ -5194,6 +5159,7 @@ const memoryUpkeep = createMemoryUpkeep({sourceLabel: (botId, threadId) => memorySourceLabel({ room: store.groupByThread(threadId), task: store.taskByThread(teamHost.baseBotId(botId), threadId), threadId }),mayCapture: (botId, threadId) => {const room = store.groupByThread(threadId);+ if (cloudGuestDriven(threadId)) return false;return !room || roomCaptureAllowed(room, store.bot(teamHost.baseBotId(botId)));},restoreTurn: (botId, threadId, turnId) => {@@ -5467,7 +5433,7 @@ bus.subscribe((event: RuntimeEvent) => {// A room fewer people can see than this bot leaves no line: session_search would hand it to anyone who sees the bot.const room = store.groupByThread(event.threadId);if (room && !roomFeedsBot(room, bot)) return;- if (CLOUD_PERSONAL && (room || !cloudOwnerOnlyThread(event.threadId))) return;+ if (cloudGuestDriven(event.threadId) || (CLOUD_PERSONAL && (room || !cloudOwnerOnlyThread(event.threadId)))) return;// Lands after this turn's journal diff, so it is journaled here as the turn's own.const now = new Date(), layer = teamHost.layer(bot.id, event.threadId);const writeLine = () => journalTurnWrite(layer, memoryLogPath(now), event.threadId, () => appendMemoryLog(layer, line, {@@ -7062,7 +7028,7 @@ function runtimeWorkPending(threadId: string): boolean {}const { reportIncident, reportEscalation, incidentRefused, retryThread } = createChiefNotices({- store, notify, threadBusy, botAtThreadCapacity, startTurn, quietThread: (_botId, threadId) => proactive.fence.confines(threadId), privateThread: (threadId) => teamHost.ownTurn(threadId), threadLanguage,+ store, notify, threadBusy, botAtThreadCapacity, startTurn, quietThread: (_botId, threadId) => proactive.fence.confines(threadId), privateThread: (threadId) => teamHost.ownTurn(threadId), confined: cloudGuestDriven, threadLanguage,assignerOf: (threadId) => coordinator.assignerOf(threadId),threadSettling: (threadId) => settlingTurns.has(threadId), threadQueued: (botId, threadId) => queuedThreadPosition(botId, threadId) !== null,groupTurnActive: (botId) => Boolean(activeGroupTurnForBot(botId)),@@ -7840,6 +7806,7 @@ async function beginTurn(const dispatchClaimId = randomUUID();if (guestConfined) guestDrivenTurns.set(threadId, dispatchClaimId);+ if (guestConfined && personLine) outsideLineage.personLineConfined(threadId);const resourceOwner: TurnOwner = { threadId, generation: dispatchClaimId };turnResourceOwners.set(threadId, resourceOwner);directTurnGenerationByThread.set(threadId, dispatchClaimId);@@ -8895,7 +8862,7 @@ const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failoverreturn Boolean(checked?.ok && store.switchTaskModel(botId, threadId, checked.selection, false, false, { ...hostedModels?.resetTask(to, checked.selection), rewound: true }));} });const automationDestinations = createAutomationDestinations({ store, mainThread: botMainThread, runs: () => routines?.listRuns() ?? [],- cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: routineOpener, reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person) } : null });+ cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: routineOpener, reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person), outside: (threadId) => outsideLineage.mark(threadId) } : null });routines = new RoutineManager({emit: broadcast, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope, approvalModeFor(bot)).length) : Boolean(bot && startupBackups(bot, cfg.automaticRecovery).length); },@@ -8927,6 +8894,7 @@ routines = new RoutineManager({if (task && CLOUD_HOME && run) {threadStarters.set(task.threadId, run.triggerSource === "webhook" ? CLOUD_OWNER_KEY! : routineOpener(run.routineId));}+ if (task && run?.triggerSource === "webhook") outsideLineage.mark(task.threadId);return task;},joinConversation: (run) => {@@ -9000,7 +8968,7 @@ routines = new RoutineManager({notify(buildNotification("routine-deferred", routineSourceOwner(run)?.bot ?? bot, routineSourceThread(run) ?? bot.threadId, detail));},});-phones.adoptRoutines(); routineHolds?.attach(routines);+phones.adoptRoutines(); routineHolds?.attach(routines); outsideLineage.settle(routines.listRuns(), automationDestinations.eventChat);// Settle Cloud ownership before anything is served and before any routine can run.if (CLOUD_HOME && CLOUD_OWNER_KEY && cloudRoutineAuthors) {cloudHome = settleCloudHome({ file: join(DATA_DIR, "cloud-owner.json"), machineId: CLOUD_HOME.machineId, ownerKey: CLOUD_OWNER_KEY, nobodyKey: CLOUD_NOBODY_KEY,@@ -9320,12 +9288,14 @@ const validateModelProposal = (selection: ModelSelection, current?: BotRecord):};const teamMemory = new TeamMemory(join(DATA_DIR, "team-memory.json"));const teamMemoryRequests = createTeamMemoryRequests({ teamMemory, store, sectionKey: sectionContextKey, decide: (row) => appendDecision(DATA_DIR, row) });+const outsideWrites = createOutsideWrites({ store, notify, language: (threadId) => threadLanguage(threadId), decide: (row) => appendDecision(DATA_DIR, row),+ writeMemory: (botId, threadId, change) => { const written = botMemoryUpdate(teamHost.layer(botId, threadId), change, { source: memorySourceLabel({ room: store.groupByThread(threadId), task: store.taskByThread(teamHost.baseBotId(botId), threadId), threadId }), aboutMe: null, prefer: null }); return written.ok ? null : written.error; } });const outboundRequests = new OutboundRequestService();const outboundCounts = new OutboundCounts(join(DATA_DIR, "outbound-counts.json"));const outboundHold = createOutboundHold({ store, dataDir: DATA_DIR, outboundRequests, outboundCounts, holdMs: OUTBOUND_HOLD_MS, connectorThread, activeGroupTurnForBot, notify });function resolveAndSendTrust(res: ServerResponse, threadId: string, requestId: string, behavior: "allow" | "deny" | "answer"): boolean {- const remembered = teamMemoryRequests.resolve(threadId, requestId, behavior);+ const remembered = teamMemoryRequests.resolve(threadId, requestId, behavior) ?? outsideWrites.resolve(threadId, requestId, behavior);if (remembered) {json(res, 200, remembered);return true;@@ -13093,6 +13063,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 403, { error: "an external runtime can only list its peers, hand them work with coordinate_bots and read assignment_status" });}if (proactive.fence.refusesRoute(internalSender, internalCapability.threadId, method, path)) return json(res, 403, { error: READ_AND_DRAFT_REFUSAL });+ if (cloudGuestDriven(internalCapability.threadId) && outsideRouteRefused(method, path)) return json(res, 403, { error: OUTSIDE_REFUSAL });const requiredCapabilityKind = path === "/api/internal/hook"? "hooks": path === "/api/internal/browser/mcp"@@ -13238,6 +13209,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (internalSender.memoryEnabled === false) {return json(res, 403, { error: "Memory is disabled for this bot." });}+ if (cloudGuestDriven(internalCapability.threadId)) {+ const proposed = path.endsWith("/log") ? { status: 403, body: { error: OUTSIDE_STAYS_HERE } } : outsideWrites.submitMemory(internalSender, internalCapability.threadId, await readInternalBody());+ return json(res, proposed.status, proposed.body);+ }const room = store.groupByThread(internalCapability.threadId);if (room && !roomFeedsBot(room, internalSender)) {return json(res, 403, { error: "This room is visible to fewer people than you are, so notes from it can't go into your memory. Keep them in the room." });@@ -13539,6 +13514,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 201, { ...applied, ...(applied.action === "create" && hookOwner ? addressFor({ from, owner: hookOwner, guestDriven: false, outsideDriven: outsideDrivenThread(fromThreadId) }, webhooks, applied.resultId, webhookIngressStatus().baseUrl) : {}) });}const proposedInput = { ...request.proposal, forBot };+ if (proposedInput.action !== "create" && (proposedInput.action === "update" ? outsideWorkStaysHere(fromThreadId) : cloudGuestDriven(fromThreadId)) && !outsideLineage.routineRunsConfined(String(proposedInput.routineId))) return json(res, 403, { error: OUTSIDE_STAYS_HERE });const wasOwners = proposedInput.action !== "create" && typeof proposedInput.routineId === "string" ? cloudRoutineIsOwners(proposedInput.routineId) : false;const run = activeRoutineRunForThread(fromThreadId);const outside = Boolean(CLOUD_HOME) && outsideDrivenThread(fromThreadId);@@ -13876,6 +13852,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const groupId = call.groupId ?? source?.id;const destination = groupId ? store.group(groupId) : undefined;if (groupId && !destination) return refuse(404, "No such room; use list_room_targets.");+ if (destination && destination.id !== source?.id && !outsideLineage.mayReach(address.threadId, destination.threadId)) return refuse(403, OUTSIDE_STAYS_HERE);const botIds: string[] = [];for (const raw of call.botIds) {const resolved = resolveTeammate(store.bots, internalSender, raw, placesElsewhere.explain, (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null));@@ -13942,7 +13919,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const forPerson = EXTERNAL || room || fresh || call.answers || mode !== "work" || call.thread === "standing" || !teammatePrompts.actsForPerson(internalSender, internalCapability.threadId) || !canManage(internalSender, recipient) || !threadReadableFrom(internalCapability.threadId)(call.thread) ? undefined : await questionRouting.answerForPerson({ sender: internalSender, senderThreadId: address.threadId, target: recipient, threadId: call.thread, message: call.message });if (forPerson) { if (forPerson.outcome === "failed") refused.push(forPerson.detail); receipts.push(forPerson); continue; }const continued = room || fresh ? undefined : workThreadFor(store, { botId: target.botId, botName: recipient.name, fromBotId: internalSender.id, fromThreadId: address.threadId, thread: call.thread, notice: mode === "notify",- answering: coordinator.answersTo(internalCapability.roomHandoffId ?? generation), also: (task) => !CLOUD_TEAM || threadStarters.get(task.threadId) === opener });+ answering: coordinator.answersTo(internalCapability.roomHandoffId ?? generation), also: (task) => !CLOUD_TEAM || threadStarters.get(task.threadId) === opener, reach: (task) => outsideLineage.mayReach(address.threadId, task.threadId) });const relayed = EXTERNAL || (!call.answers && (room || fresh || mode === "consult")) ? undefined : await questionRouting.relay({ sender: internalSender, senderThreadId: address.threadId,senderNode: coordinator.node(internalCapability.roomHandoffId ?? generation), target: recipient, message: call.message, ...(call.answers ? { answers: call.answers } : {}), ...(continued ? { threadId: continued.threadId } : {}),...(internalCapability.delegatedThisTurn ? { sentThisTurn: internalCapability.delegatedThisTurn } : {}) });@@ -13962,6 +13939,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {delegatedLevel.apply(internalSender, internalCapability.threadId, internalCapability.roomHandoffId ?? generation, recipient, target.threadId);}const routed = lane ? { botId: target.botId, threadId: lane.threadId } : target;+ outsideLineage.carry(address.threadId, routed.threadId);const { node, duplicate } = coordinator.enqueue(address, generation, internalCapability.roomHandoffId, routed, call.message, {mode, reply, thread: lane || fresh ? "new" : "standing", approvalGranted, rework: call.rework, ...(lane ? {} : { requestBatchKey }),...(call.doneWhen ? { doneWhen: call.doneWhen } : {}),@@ -14122,6 +14100,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (store.groupByThread(threadId)) return json(res, 400, { error: "that is a room thread — use coordinate_bots in the room instead" });const task = store.taskByThread(target.id, threadId);if (!task || (CLOUD_TEAM && !teamHost.readableFrom(fromThreadId)(threadId))) return json(res, 404, { error: "no such thread on that bot" });+ if (!outsideLineage.mayReach(fromThreadId, threadId)) return json(res, 403, { error: OUTSIDE_STAYS_HERE });requireActiveInternalCapability();try {await retryThread({ chief: from, bot: target, threadId, note, unattended: isUnattended(from.id, fromThreadId) });@@ -14166,6 +14145,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}let room = store.group(groupId);if (!room) return json(res, 404, { error: "no such room — call list_rooms and copy the exact id from the result" });+ if (!outsideLineage.mayReach(fromThreadId, room.threadId)) return json(res, 403, { error: OUTSIDE_STAYS_HERE });if (room.id === owner.group?.id) {return json(res, 409, { error: "you are already speaking in that room — say it in your reply instead" });}@@ -14490,6 +14470,11 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 403, { error: "you can only manage rooms you belong to in your own department, whose members you can all reach; no bot needs adding to get work, since coordinate_bots reaches bots outside the room directly" });}const { action, memberIds, name, bulletin } = parsed.data;+ if (cloudGuestDriven(internalCapability.threadId)) {+ if (action !== "set_bulletin" || bulletin === undefined) return json(res, 403, { error: OUTSIDE_STAYS_HERE });+ const proposed = outsideWrites.submitBulletin(chief, internalCapability.threadId, room, redactSecretsInText(bulletin));+ return json(res, proposed.status, proposed.body);+ }if (action === "new_thread") {const opened = openRoomThread({ store, turn: internalCapability, room, name, savingCredential: phoneSecretSubmissions.hasGroup(room.id) });return json(res, opened.status, opened.body);@@ -14881,7 +14866,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const ownerAuthors = cloudOwnerSession(auth) && (wasOwners || ownerWriterOnly ||(body && typeof body === "object" && "prompt" in body));const writer = ownerAuthors && CLOUD_OWNER_KEY ? CLOUD_OWNER_KEY- : auth.kind === "session" && !cloudOwnerSession(auth) ? actorKey(auth)+ : previous === CLOUD_OUTSIDE_KEY && !(body && typeof body === "object" && "prompt" in body) ? previous+ : auth.kind === "session" && (!cloudOwnerSession(auth) || (CLOUD_TEAM && previous === CLOUD_OUTSIDE_KEY)) ? actorKey(auth): previous && !cloudOwnerPerson(previous) ? previous : CLOUD_NOBODY_KEY;const routine = withRoutineWriter(writer, () => routines!.update(routineMatch![1], body));// Anyone else's edit, of any field, makes the routine no longer the owner's until the owner rewrites it; off a Cloud home the same for the desktop owner's phones.diff --git a/server/outside-lineage.e2e.test.ts b/server/outside-lineage.e2e.test.tsnew file mode 100644index 0000000000..1e15126e48--- /dev/null+++ b/server/outside-lineage.e2e.test.ts@@ -0,0 +1,509 @@+// Work that came in from outside stays with that work, on a real Team Cloud, a personal Cloud someone else has used and a+// desktop, with the fake engine: the level each turn really got, read from what the engine was started with.+import { randomBytes } from "node:crypto";+import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { OUTSIDE_REFUSAL } from "./host/outside-fence.ts";+import { OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts";+import { markLeftBehind } from "./testing/cloud-left-behind.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const tag = randomBytes(6).toString("hex");+const dump = join(tmpdir(), `outside-${tag}.json`), release = join(tmpdir(), `outside-${tag}.release`), failing = join(tmpdir(), `outside-${tag}.fail`), notes = join(tmpdir(), `outside-${tag}.notes`),+ holding = join(tmpdir(), `outside-${tag}.holding`), held = join(tmpdir(), `outside-${tag}.held`);+const engine = `const { existsSync: __has } = await import("node:fs"); process.env.FAKE_CLAUDE_MODE = __has(${JSON.stringify(failing)}) ? "exit-early" : "hang"; process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(dump)}; process.env.FAKE_CLAUDE_RELEASE = __has(${JSON.stringify(holding)}) ? ${JSON.stringify(held)} : ${JSON.stringify(release)}; process.env.FAKE_CLAUDE_TEXT_FILE = ${JSON.stringify(notes)}; process.env.FAKE_CLAUDE_TEXT_DUMP = ${JSON.stringify(`${notes}.dump`)};`;+const KEY = randomBytes(16).toString("hex");+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+const read = () => { try { return JSON.parse(readFileSync(dump, "utf8")); } catch { return null; } };+async function until<V>(what: string, fn: () => Promise<V> | V, ms = hostTimeout(30_000)): Promise<V> {+ const end = Date.now() + ms;+ for (;;) {+ const value = await fn();+ if (value) return value;+ if (Date.now() > end) throw new Error(`timed out: ${what}`);+ await sleep(100);+ }+}+const said = (marker: string, where: "prompt" | "systemPrompt" = "prompt") => { const turn = read(); return turn && JSON.stringify(turn[where] ?? "").includes(marker) ? turn : null; };+const turnWith = (marker: string, where: "prompt" | "systemPrompt" = "prompt") => until(`a turn with ${marker}`, () => said(marker, where));+const confined = (turn: { argv: string[] }) => turn.argv.includes("--restricted");+const atFull = (turn: { argv: string[] }) => turn.argv[turn.argv.indexOf("--permission-mode") + 1] === "bypassPermissions";++let fx: CloudSendFixture, team: CloudTeamFixture, ada: string;+beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-${randomBytes(8).toString("hex")}`, cloudEngine: engine, desktopEngine: engine, env: { OMB_TEST_INTERNAL_CAPABILITY_KEY: KEY },+ team: { id: "team-acme-1", name: "Acme", engine } });+ team = fx.team!;+ ada = (await team.pair({ email: "[email protected]", role: "admin" })).token!;+}, hostTimeout(180_000));+afterAll(async () => {+ writeFileSync(release, "");+ await sleep(500);+ await fx?.close?.();+ for (const file of [dump, release, failing, notes, `${notes}.dump`, holding, held]) rmSync(file, { force: true });+});++const newBot = async (name: string, level = "full") => {+ const bot = (await team.as(ada, "POST", "/api/bots", { name })).body.bot as { id: string; threadId: string };+ expect((await team.as(ada, "PATCH", `/api/bots/${bot.id}`, { approvalMode: level, applyToAllThreads: true })).status).toBe(200);+ return bot;+};+const newChief = async (name: string) => {+ const bot = await newBot(name);+ expect((await team.as(ada, "PATCH", `/api/bots/${bot.id}`, { chiefOfStaff: true })).status).toBe(200);+ return bot;+};+const hookOn = async (botId: string, name: string) => (await team.as(ada, "POST", "/api/webhooks", { name, prompt: "Handle the event.", botId })).body;+const deliver = async (hook: any, text: string) => {+ const receiver = team.base.replace(/:(\d+)$/, (_: string, port: string) => `:${Number(port) + 1}`);+ const delivered = await fetch(`${receiver}/hooks/${hook.webhook.endpointId}/${encodeURIComponent(hook.credential.secret)}`, { method: "POST",+ headers: { "content-type": "application/json", "idempotency-key": randomBytes(6).toString("hex") }, body: JSON.stringify({ text }) });+ expect(delivered.status).toBe(202);+};+const runOf = async (hook: any) => ((await team.as(ada, "GET", "/api/routines")).body.runs as any[]).find((run) => run.webhookId === hook.webhook.id);+const internal = async (botId: string, thread: string, path: string, body: unknown, capability?: string) => {+ const token = capability ?? await team.capability(botId, thread);+ const response = await fetch(`${team.base}${path}?fromBotId=${botId}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },+ body: JSON.stringify({ fromBotId: botId, fromThreadId: thread, ...(body as object) }) });+ return { status: response.status, body: await response.json().catch(() => null) as any };+};+const idle = (...ids: string[]) => until(`${ids} idle`, async () => {+ const bots = (await team.as(ada, "GET", "/api/bots")).body.bots as any[];+ return ids.every((id) => !bots.find((bot) => bot.id === id)?.busy);+}, hostTimeout(40_000));+const finish = async (...ids: string[]) => {+ writeFileSync(release, ""); writeFileSync(held, "");+ await idle(...ids);+ await sleep(300);+ for (const file of [release, held, holding, dump]) rmSync(file, { force: true });+};+const linesOf = async (threadId: string) => (await team.as(ada, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages as any[];+/** The webhook's turn is running on `bot`. */+const webhookTurn = async (botId: string, name: string, marker: string) => {+ const hook = await hookOn(botId, name);+ await deliver(hook, marker);+ const turn = await turnWith(marker);+ const run = await until("the run", () => runOf(hook));+ return { hook, run, turn, thread: run.threadId as string };+};++describe("a Team Cloud", () => {+ it("runs a routine a confined turn makes confined, however it is started", async () => {+ const scout = await newBot("Routine maker");+ const { thread, turn } = await webhookTurn(scout.id, "Routine hook", "marker-routine");+ expect(confined(turn)).toBe(true);+ const made = await internal(scout.id, thread, "/api/internal/trigger-requests", { action: "create", kind: "schedule", routine: { name: "From outside", instructions: "routine-made-outside", schedule: { type: "interval", everyMinutes: 60 } } });+ expect(made.body?.state).toBe("applied");+ expect((await internal(scout.id, thread, "/api/internal/trigger-requests", { action: "run_now", triggerId: made.body.result.resultId })).status).toBe(201);+ const routineTurn = await turnWith("routine-made-outside");+ expect(confined(routineTurn)).toBe(true);+ expect(atFull(routineTurn)).toBe(false);+ const mate = await newBot("Routine mate");+ const runs = (await team.as(ada, "GET", "/api/routines")).body.runs as any[];+ const runThread = runs.find((one) => one.routineId === made.body.result.resultId).threadId as string;+ const handed = await internal(scout.id, runThread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "brief-from-routine", reply: "none" });+ expect(confined(await turnWith("brief-from-routine"))).toBe(true);+ await finish(scout.id, mate.id);+ expect((await team.as(ada, "POST", `/api/bots/${mate.id}/messages`, { text: "person-after-routine", threadId: handed.body.receipts[0].threadId })).status).toBe(202);+ expect(confined(await turnWith("person-after-routine"))).toBe(true);+ await finish(mate.id);+ // Saved by a person, it is theirs, as its card says.+ const id = made.body.result.resultId as string;+ expect((await team.as(ada, "PATCH", `/api/routines/${id}`, { prompt: "routine-saved-by-a-person" })).status).toBe(200);+ expect((await team.as(ada, "POST", `/api/routines/${id}/run`)).status).toBe(201);+ const saved = await turnWith("routine-saved-by-a-person");+ expect(confined(saved)).toBe(false);+ expect(atFull(saved)).toBe(true);+ await finish(scout.id);+ }, hostTimeout(120_000));++ it("keeps a confined turn from starting or changing a person's routine", async () => {+ const scout = await newBot("Routine starter");+ const mine = (await team.as(ada, "POST", "/api/routines", { name: "Ada's", prompt: "routine-of-a-person", botId: scout.id, enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } })).body.routine;+ const { thread } = await webhookTurn(scout.id, "Starter hook", "marker-starter");+ const refused = await internal(scout.id, thread, "/api/internal/trigger-requests", { action: "run_now", triggerId: mine.id });+ expect(refused).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });+ await sleep(800);+ expect(said("routine-of-a-person")).toBeNull();+ const changed = await internal(scout.id, thread, "/api/internal/trigger-requests", { action: "update", triggerId: mine.id, changes: { instructions: "routine-changed-from-outside" } });+ expect(changed).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });+ expect(((await team.as(ada, "GET", "/api/routines")).body.routines as any[]).find((one) => one.id === mine.id).prompt).toBe("routine-of-a-person");+ await finish(scout.id);+ }, hostTimeout(120_000));++ it("refuses a retry from a confined turn into a person's thread, and keeps its own work confined when it retries that", async () => {+ const chief = await newChief("Retry chief");+ const mate = await newBot("Retry mate");+ const { thread } = await webhookTurn(chief.id, "Retry hook", "marker-retry");+ const capability = await team.capability(chief.id, thread);+ const sent = await internal(chief.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "brief-retry", reply: "none" }, capability);+ expect(confined(await turnWith("brief-retry"))).toBe(true);+ const child = sent.body.receipts[0].threadId as string;+ expect((await team.as(ada, "POST", `/api/bots/${mate.id}/interrupt`, { threadId: child })).status).toBe(200);+ await idle(mate.id);+ await sleep(500);+ const refused = await internal(chief.id, thread, "/api/internal/retry-thread", { toBotId: mate.id, toThreadId: mate.threadId, note: "note-into-main" }, capability);+ expect(refused).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });+ await sleep(800);+ expect(said("note-into-main")).toBeNull();+ expect((await internal(chief.id, thread, "/api/internal/retry-thread", { toBotId: mate.id, toThreadId: child, note: "note-own-work" }, capability)).status).toBe(200);+ expect(confined(await turnWith("note-own-work"))).toBe(true);+ await finish(chief.id, mate.id);+ }, hostTimeout(120_000));++ it("keeps one-way work confined after the run that sent it has ended", async () => {+ const scout = await newBot("Notice sender");+ const mate = await newBot("Notice mate");+ const { hook, thread } = await webhookTurn(scout.id, "Notice hook", "marker-notice");+ const capability = await team.capability(scout.id, thread);+ // The first notice outlasts the run that sent it, so the second starts with that run over.+ writeFileSync(holding, "");+ expect((await internal(scout.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "notice-first", reply: "none" }, capability)).status).toBe(200);+ expect(confined(await turnWith("notice-first"))).toBe(true);+ expect((await internal(scout.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "notice-second", reply: "none" }, capability)).status).toBe(200);+ writeFileSync(release, "");+ await until("the run to end", async () => (await runOf(hook)).status === "completed");+ writeFileSync(held, "");+ expect(confined(await turnWith("notice-second"))).toBe(true);+ await finish(scout.id, mate.id);+ }, hostTimeout(120_000));++ it("tells a person, not a Chief, when a confined run fails, and a person's retry of that run stays confined", async () => {+ const chief = await newChief("Failure chief");+ const mate = await newBot("Failure mate");+ const hook = await hookOn(mate.id, "Failure hook");+ rmSync(dump, { force: true });+ writeFileSync(failing, "");+ await deliver(hook, "marker-failure");+ const run = await until("the run to fail", async () => { const one = await runOf(hook); return one && ["failed", "missed"].includes(one.status) ? one : null; }, hostTimeout(60_000));+ rmSync(failing, { force: true });+ await sleep(1_000);+ const bots = (await team.as(ada, "GET", "/api/bots")).body.bots as any[];+ expect(bots.find((bot) => bot.id === chief.id).tasks.map((task: any) => task.title), "no notices chat on the Chief").not.toEqual(expect.arrayContaining([expect.stringMatching(/Problems to look at|Team incidents/)]));+ expect((await internal(chief.id, chief.threadId, "/api/internal/retry-thread", { toBotId: mate.id, toThreadId: run.threadId, note: "person-chief-retry" })).status).toBe(200);+ expect(confined(await turnWith("person-chief-retry"))).toBe(true);+ await finish(chief.id, mate.id);+ }, hostTimeout(180_000));++ it("keeps a person's line in a conversation outside work reached confined, and says why once", async () => {+ const scout = await newBot("Follow-up bot");+ const { thread } = await webhookTurn(scout.id, "Follow-up hook", "marker-followup");+ await finish(scout.id);+ expect((await team.as(ada, "POST", `/api/bots/${scout.id}/messages`, { text: "person-line-here", threadId: thread })).status).toBe(202);+ const turn = await turnWith("person-line-here");+ expect(confined(turn)).toBe(true);+ expect(atFull(turn)).toBe(false);+ const told = (await linesOf(thread)).filter((line) => line.kind === "activity" && /Work from outside came into this conversation/.test(line.tool?.name ?? ""));+ expect(told).toHaveLength(1);+ await finish(scout.id);+ const bots = (await team.as(ada, "GET", "/api/bots")).body.bots as any[];+ const results = bots.find((bot) => bot.id === scout.id).tasks.find((task: any) => task.title === "Follow-up hook · Results");+ expect((await team.as(ada, "POST", `/api/bots/${scout.id}/messages`, { text: "person-line-in-results", threadId: results.threadId })).status).toBe(202);+ expect(confined(await turnWith("person-line-in-results"))).toBe(true);+ await finish(scout.id);+ }, hostTimeout(120_000));++ it("keeps a person's own new conversation with the same bot at the bot's level, without its brief reading outside work", async () => {+ const scout = await newBot("Own chat bot");+ const { thread } = await webhookTurn(scout.id, "Own chat hook", "marker-ownchat");+ const handedTo = await newBot("Own chat mate");+ expect((await internal(scout.id, thread, "/api/internal/coordinate-bots", { botIds: [handedTo.id], message: "brief-ownchat", reply: "none" })).status).toBe(200);+ await turnWith("brief-ownchat");+ await finish(scout.id, handedTo.id);+ const theirs = (await team.as(ada, "POST", `/api/bots/${handedTo.id}/tasks`, { title: "Theirs" })).body.task.threadId as string;+ expect((await team.as(ada, "POST", `/api/bots/${handedTo.id}/messages`, { text: "person-chat-with-mate", threadId: theirs })).status).toBe(202);+ const brief = await turnWith("person-chat-with-mate");+ expect(confined(brief)).toBe(false);+ expect(JSON.stringify(brief.systemPrompt)).not.toContain("· work");+ await finish(handedTo.id);+ const mine = (await team.as(ada, "POST", `/api/bots/${scout.id}/tasks`, { title: "Mine" })).body.task.threadId as string;+ expect(mine).not.toBe(thread);+ expect((await team.as(ada, "POST", `/api/bots/${scout.id}/messages`, { text: "person-new-chat", threadId: mine })).status).toBe(202);+ const turn = await turnWith("person-new-chat");+ expect(confined(turn)).toBe(false);+ expect(atFull(turn)).toBe(true);+ await finish(scout.id);+ }, hostTimeout(120_000));++ it("waits on a card for what a confined turn writes to a room's bulletin or a bot's memory", async () => {+ const chief = await newChief("Writer chief");+ const mate = await newBot("Writer mate");+ const room = (await team.as(ada, "POST", "/api/groups", { name: "Writer room", memberIds: [chief.id, mate.id], setup: { bulletin: "as it was", defaultResponder: { kind: "member", botId: mate.id } } })).body.group;+ const { thread } = await webhookTurn(chief.id, "Writer hook", "marker-writer");+ const capability = await team.capability(chief.id, thread);+ const bulletin = await internal(chief.id, thread, "/api/internal/manage-room", { roomId: room.id, action: "set_bulletin", bulletin: "bulletin-from-outside" }, capability);+ expect(bulletin.body).toMatchObject({ state: "pending" });+ const note = await internal(chief.id, thread, "/api/internal/memory", { action: "append", text: "memory-from-outside" }, capability);+ expect(note.body).toMatchObject({ state: "pending" });+ expect((await internal(chief.id, thread, "/api/internal/memory/log", { text: "log-from-outside" }, capability)).status).toBe(403);+ await finish(chief.id, mate.id);+ expect((await team.as(ada, "POST", `/api/groups/${room.id}/messages`, { text: "room-before-card" })).status).toBeLessThan(300);+ const roomTurn = await turnWith("room-before-card");+ expect(JSON.stringify(roomTurn.systemPrompt)).not.toContain("bulletin-from-outside");+ expect(JSON.stringify(roomTurn.systemPrompt)).toContain("as it was");+ await finish(chief.id, mate.id);+ expect((await team.as(ada, "POST", `/api/bots/${chief.id}/messages`, { text: "chief-before-card", threadId: chief.threadId })).status).toBe(202);+ const before = await turnWith("chief-before-card");+ expect(JSON.stringify({ system: before.systemPrompt, prompt: before.prompt })).not.toContain("memory-from-outside");+ await finish(chief.id);+ const member = (await team.pair({ email: "[email protected]", role: "member" })).token!;+ const answer = (token: string, requestId: string) => team.as(token, "POST", `/api/threads/${thread}/respond`, { requestId, behavior: "allow" });+ expect((await answer(member, bulletin.body.requestId)).status).toBe(403);+ expect((await answer(ada, bulletin.body.requestId)).status).toBe(200);+ expect((await answer(ada, note.body.requestId)).status).toBe(200);+ expect(((await team.as(ada, "GET", "/api/bots?messages=0")).body.groups as any[]).find((group) => group.id === room.id).bulletin).toBe("bulletin-from-outside");+ expect((await team.as(ada, "POST", `/api/bots/${chief.id}/messages`, { text: "chief-after-card", threadId: chief.threadId })).status).toBe(202);+ const after = await turnWith("chief-after-card");+ expect(JSON.stringify({ system: after.systemPrompt, prompt: after.prompt })).toContain("memory-from-outside");+ await finish(chief.id);+ }, hostTimeout(180_000));++ it("keeps outside text out of work a person started, by thread and by question", async () => {+ const chief = await newChief("Fold chief");+ const mate = await newBot("Fold mate");+ expect((await team.as(ada, "POST", `/api/bots/${chief.id}/messages`, { text: "person-line-fold", threadId: chief.threadId })).status).toBe(202);+ await turnWith("person-line-fold");+ const handed = await internal(chief.id, chief.threadId, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "person-work-fold" });+ expect(confined(await turnWith("person-work-fold"))).toBe(false);+ const work = handed.body.receipts[0].threadId as string;+ const { thread } = await webhookTurn(chief.id, "Fold hook", "marker-fold");+ const sent = await internal(chief.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], thread: work, message: "line-for-the-work" });+ expect(sent.body.receipts[0]).toMatchObject({ outcome: "failed", detail: OUTSIDE_STAYS_HERE });+ await sleep(800);+ expect(JSON.stringify(await linesOf(work))).not.toContain("line-for-the-work");+ const named = await internal(chief.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "line-as-answer", answers: handed.body.receipts[0].requestId });+ expect(named.body.receipts[0].outcome).toBe("failed");+ expect(JSON.stringify(await linesOf(work))).not.toContain("line-as-answer");+ await finish(chief.id, mate.id);+ }, hostTimeout(120_000));++ it("refuses a confined post into a room people work in, leaving nothing there", async () => {+ const chief = await newChief("Post chief");+ const mate = await newBot("Post mate");+ const room = (await team.as(ada, "POST", "/api/groups", { name: "Post room", memberIds: [chief.id, mate.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: mate.id } } })).body.group;+ const { thread } = await webhookTurn(chief.id, "Post hook", "marker-post");+ const capability = await team.capability(chief.id, thread);+ expect(await internal(chief.id, thread, "/api/internal/post-to-room", { groupId: room.id, message: "post-from-outside" }, capability)).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });+ const handed = await internal(chief.id, thread, "/api/internal/coordinate-bots", { groupId: room.id, botIds: [mate.id], message: "room-work-from-outside" }, capability);+ expect(handed).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });+ expect(JSON.stringify(await linesOf(room.threadId))).not.toContain("from-outside");+ await finish(chief.id, mate.id);+ }, hostTimeout(120_000));++ it("refuses what a confined turn could run or start with nobody deciding", async () => {+ const chief = await newChief("Fence chief");+ const { thread } = await webhookTurn(chief.id, "Fence hook", "marker-fence");+ const capability = await team.capability(chief.id, thread);+ for (const route of ["vm-exec", "fill-login", "create-room", "people/message", "request-credential"]) {+ expect(await internal(chief.id, thread, `/api/internal/${route}`, { name: "x", command: "true", to: "[email protected]", message: "x" }, capability), route).toMatchObject({ status: 403, body: { error: OUTSIDE_REFUSAL } });+ }+ await finish(chief.id);+ }, hostTimeout(120_000));++ it("saves nothing from a confined conversation into a bot's memory or log on its own, where a person's own chat is saved", async () => {+ writeFileSync(notes, JSON.stringify({ facts: [{ text: "fact-from-a-chat", kind: "decision" }] }));+ expect((await team.as(ada, "PUT", "/api/config", { memory: { captureQuietMs: 1_000 } })).status).toBe(200);+ const saved = (botId: string) => {+ const root = join(team.home, ".openmausbot", "workspaces");+ return readdirSync(root).filter((name) => name.startsWith(botId)).flatMap((name) => {+ const logs = join(root, name, "memory", "log");+ return [join(root, name, "MEMORY.md"), ...(existsSync(logs) ? readdirSync(logs).map((file) => join(logs, file)) : [])];+ }).filter((file) => existsSync(file)).map((file) => readFileSync(file, "utf8")).join("\n");+ };+ const scout = await newBot("Capture scout");+ const mate = await newBot("Capture mate");+ const { thread } = await webhookTurn(scout.id, "Capture hook", "marker-capture");+ const sent = await internal(scout.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "brief-capture", reply: "none" });+ await turnWith("brief-capture");+ await finish(scout.id, mate.id);+ expect((await team.as(ada, "POST", `/api/bots/${mate.id}/messages`, { text: "I like my answers short, person-line-capture.", threadId: sent.body.receipts[0].threadId })).status).toBe(202);+ await turnWith("person-line-capture");+ await finish(mate.id);+ const own = await newBot("Capture control");+ expect((await team.as(ada, "POST", `/api/bots/${own.id}/messages`, { text: "I like my answers short, person-own-chat.", threadId: own.threadId })).status).toBe(202);+ await turnWith("person-own-chat");+ await finish(own.id);+ await until("a person's own chat saved", () => saved(own.id).includes("fact-from-a-chat"));+ expect(saved(own.id)).toContain("released");+ expect(saved(mate.id)).not.toContain("fact-from-a-chat");+ expect(saved(mate.id)).not.toContain("released");+ expect((await team.as(ada, "PUT", "/api/config", { memory: { captureQuietMs: 600_000 } })).status).toBe(200);+ rmSync(notes, { force: true });+ }, hostTimeout(120_000));++ it("judges work again after a restart as it stood before", async () => {+ const scout = await newBot("Restart bot");+ const mate = await newBot("Restart mate");+ const { thread } = await webhookTurn(scout.id, "Restart hook", "marker-restart");+ const capability = await team.capability(scout.id, thread);+ writeFileSync(holding, "");+ const sent = await internal(scout.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "work-across-restart", reply: "none" }, capability);+ expect(confined(await turnWith("work-across-restart"))).toBe(true);+ expect((await internal(scout.id, thread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "work-queued-at-restart", reply: "none" }, capability)).status).toBe(200);+ const child = sent.body.receipts[0].threadId as string;+ rmSync(dump, { force: true });+ await team.relaunch();+ ada = (await team.pair({ email: "[email protected]", role: "admin" })).token!;+ writeFileSync(held, "");+ expect(confined(await turnWith("work-queued-at-restart"))).toBe(true);+ await finish(scout.id, mate.id);+ expect((await team.as(ada, "POST", `/api/bots/${mate.id}/messages`, { text: "person-after-restart", threadId: child })).status).toBe(202);+ expect(confined(await turnWith("person-after-restart"))).toBe(true);+ await finish(mate.id);+ expect((await team.as(ada, "POST", `/api/bots/${scout.id}/messages`, { text: "person-in-run-thread", threadId: thread })).status).toBe(202);+ expect(confined(await turnWith("person-in-run-thread"))).toBe(true);+ await finish(scout.id);+ }, hostTimeout(180_000));++ it("counts a run from before the conversation kept its own record", async () => {+ const scout = await newBot("Earlier bot");+ const { thread } = await webhookTurn(scout.id, "Earlier hook", "marker-earlier");+ await finish(scout.id);+ const file = join(team.home, ".openmausbot", "bots.json");+ const before = readFileSync(file, "utf8");+ expect(before).toContain('"outside":true');+ writeFileSync(file, before.replaceAll('"outside":true', '"unmarked":true'));+ await team.relaunch();+ ada = (await team.pair({ email: "[email protected]", role: "admin" })).token!;+ expect((await team.as(ada, "POST", `/api/bots/${scout.id}/messages`, { text: "person-line-earlier", threadId: thread })).status).toBe(202);+ expect(confined(await turnWith("person-line-earlier"))).toBe(true);+ await finish(scout.id);+ }, hostTimeout(180_000));++ it("leaves a person's own work as it was: their level, hand-offs, threads, posts, notes and retries", async () => {+ const chief = await newChief("Person chief");+ const mate = await newBot("Person mate");+ const room = (await team.as(ada, "POST", "/api/groups", { name: "Person room", memberIds: [chief.id, mate.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: mate.id } } })).body.group;+ expect((await team.as(ada, "POST", `/api/bots/${chief.id}/messages`, { text: "person-line-own", threadId: chief.threadId })).status).toBe(202);+ const turn = await turnWith("person-line-own");+ expect(confined(turn)).toBe(false);+ expect(atFull(turn)).toBe(true);+ const capability = await team.capability(chief.id, chief.threadId);+ const handed = await internal(chief.id, chief.threadId, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "person-handed-work", reply: "none" }, capability);+ const handedTurn = await turnWith("person-handed-work");+ expect(confined(handedTurn)).toBe(false);+ expect(atFull(handedTurn)).toBe(true);+ expect((await internal(chief.id, chief.threadId, "/api/internal/post-to-room", { groupId: room.id, message: "person-room-post" }, capability)).status).toBe(201);+ expect(((await internal(chief.id, chief.threadId, "/api/internal/memory", { action: "append", text: "person-note" }, capability)).body as any)?.state).not.toBe("pending");+ expect((await internal(chief.id, chief.threadId, "/api/internal/manage-room", { roomId: room.id, action: "set_bulletin", bulletin: "person-bulletin" }, capability)).status).toBe(200);+ await team.as(ada, "POST", `/api/bots/${mate.id}/interrupt`, { threadId: handed.body.receipts[0].threadId });+ await idle(mate.id);+ await sleep(500);+ expect((await internal(chief.id, chief.threadId, "/api/internal/retry-thread", { toBotId: mate.id, toThreadId: handed.body.receipts[0].threadId, note: "person-retry" }, capability)).status).toBe(200);+ const retried = await turnWith("person-retry");+ expect(confined(retried)).toBe(false);+ await finish(chief.id, mate.id);+ }, hostTimeout(180_000));+});++describe("a personal Cloud only its owner has used", () => {+ it("runs a webhook at the bot's level, and keeps what a routine it made hands on confined after that work ends", async () => {+ rmSync(dump, { force: true });+ const cloud = fx.onCloud;+ const scout = (await cloud("POST", "/api/bots", { name: "Solo scout" })).body.bot;+ const mate = (await cloud("POST", "/api/bots", { name: "Solo mate" })).body.bot;+ for (const bot of [scout, mate]) expect((await cloud("PATCH", `/api/bots/${bot.id}`, { approvalMode: "full", applyToAllThreads: true })).status).toBe(200);+ const hook = (await cloud("POST", "/api/webhooks", { name: "Solo hook", prompt: "Handle the event.", botId: scout.id })).body;+ const receiver = fx.cloudBase.replace(/:(\d+)$/, (_: string, port: string) => `:${Number(port) + 1}`);+ expect((await fetch(`${receiver}/hooks/${hook.webhook.endpointId}/${encodeURIComponent(hook.credential.secret)}`, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": randomBytes(6).toString("hex") }, body: JSON.stringify({ text: "marker-solo" }) })).status).toBe(202);+ const webhook = await turnWith("marker-solo");+ expect(confined(webhook)).toBe(false);+ const capabilityFor = async (botId: string, threadId: string) => ((await (await fetch(`${fx.cloudBase}/api/testing/internal-capability`, { method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": KEY }, body: JSON.stringify({ botId, threadId }) })).json()) as any).token as string;+ const call = async (from: string, path: string, body: object) => {+ const response = await fetch(`${fx.cloudBase}${path}?fromBotId=${scout.id}`, { method: "POST", headers: { authorization: `Bearer ${await capabilityFor(scout.id, from)}`, "content-type": "application/json" }, body: JSON.stringify({ fromBotId: scout.id, fromThreadId: from, ...body }) });+ return { status: response.status, body: await response.json().catch(() => null) as any };+ };+ const runs = async () => (await cloud("GET", "/api/routines")).body.runs as any[];+ const hookThread = (await runs()).find((run) => run.webhookId === hook.webhook.id).threadId as string;+ const made = await call(hookThread, "/api/internal/trigger-requests", { action: "create", kind: "schedule", routine: { name: "Solo routine", instructions: "solo-routine-run", schedule: { type: "interval", everyMinutes: 60 } } });+ expect((await call(hookThread, "/api/internal/trigger-requests", { action: "run_now", triggerId: made.body.result.resultId })).status).toBe(201);+ expect(confined(await turnWith("solo-routine-run"))).toBe(true);+ const runThread = (await runs()).find((run) => run.routineId === made.body.result.resultId).threadId as string;+ const handed = await call(runThread, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "solo-brief", reply: "none" });+ expect(confined(await turnWith("solo-brief"))).toBe(true);+ writeFileSync(release, "");+ await sleep(2_500);+ rmSync(release, { force: true });+ rmSync(dump, { force: true });+ expect((await cloud("POST", `/api/bots/${mate.id}/messages`, { text: "owner-line-solo", threadId: handed.body.receipts[0].threadId })).status).toBe(202);+ expect(confined(await turnWith("owner-line-solo"))).toBe(true);+ writeFileSync(release, "");+ await sleep(1_500);+ rmSync(release, { force: true });+ }, hostTimeout(120_000));+});++describe("a personal Cloud someone else has used", () => {+ it("keeps a confined turn out of the owner's conversations and their room's instructions", async () => {+ rmSync(dump, { force: true });+ const cloud = fx.onCloud;+ const chief = (await cloud("POST", "/api/bots", { name: "Chief" })).body.bot;+ expect((await cloud("PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: true })).status).toBe(200);+ const mate = (await cloud("POST", "/api/bots", { name: "Mate" })).body.bot;+ expect((await cloud("PATCH", `/api/bots/${mate.id}`, { approvalMode: "full", applyToAllThreads: true })).status).toBe(200);+ const room = (await cloud("POST", "/api/groups", { name: "Owner's room", memberIds: [chief.id, mate.id], setup: { bulletin: "as it was", defaultResponder: { kind: "member", botId: mate.id } } })).body.group;+ const theirs = (await cloud("POST", `/api/bots/${chief.id}/tasks`, { title: "Left behind" })).body.task.threadId as string;+ markLeftBehind(join(fx.root, "cloud", ".openmausbot"), { threadIds: [theirs] });+ await fx.relaunch({ kill: false, cloud: {} });+ const capabilityFor = async (botId: string, threadId: string) => ((await (await fetch(`${fx.cloudBase}/api/testing/internal-capability`, { method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": KEY }, body: JSON.stringify({ botId, threadId }) })).json()) as any).token as string;+ const call = async (capability: string, from: string, path: string, body: object) => {+ const response = await fetch(`${fx.cloudBase}${path}?fromBotId=${chief.id}`, { method: "POST", headers: { authorization: `Bearer ${capability}`, "content-type": "application/json" }, body: JSON.stringify({ fromBotId: chief.id, fromThreadId: from, ...body }) });+ return { status: response.status, body: await response.json().catch(() => null) as any };+ };+ expect((await cloud("POST", `/api/bots/${chief.id}/messages`, { text: "their-line", threadId: theirs })).status).toBe(202);+ expect(confined(await turnWith("their-line"))).toBe(true);+ const capability = await capabilityFor(chief.id, theirs);++ expect(await call(capability, theirs, "/api/internal/retry-thread", { toBotId: mate.id, toThreadId: mate.threadId, note: "note-for-owner" })).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });+ await sleep(800);+ expect(said("note-for-owner")).toBeNull();++ expect(await call(capability, theirs, "/api/internal/vm-exec", { command: "true" })).toMatchObject({ status: 403, body: { error: OUTSIDE_REFUSAL } });+ expect(await call(capability, theirs, "/api/internal/post-to-room", { groupId: room.id, message: "post-for-owner" })).toMatchObject({ status: 403, body: { error: OUTSIDE_STAYS_HERE } });++ const bulletin = await call(capability, theirs, "/api/internal/manage-room", { roomId: room.id, action: "set_bulletin", bulletin: "bulletin-for-owner" });+ expect(bulletin.body).toMatchObject({ state: "pending" });+ expect(((await cloud("GET", "/api/bots?messages=0")).body.groups as any[]).find((group) => group.id === room.id).bulletin).toBe("as it was");++ expect((await cloud("POST", `/api/bots/${chief.id}/messages`, { text: "owner-line", threadId: chief.threadId })).status).toBe(202);+ await turnWith("owner-line");+ const ownerCapability = await capabilityFor(chief.id, chief.threadId);+ const handed = await call(ownerCapability, chief.threadId, "/api/internal/coordinate-bots", { botIds: [mate.id], message: "owner-work" });+ expect(confined(await turnWith("owner-work"))).toBe(false);+ const work = handed.body.receipts[0].threadId as string;+ const sent = await call(capability, theirs, "/api/internal/coordinate-bots", { botIds: [mate.id], thread: work, message: "line-for-owner-work" });+ expect(sent.body.receipts[0]).toMatchObject({ outcome: "failed", detail: OUTSIDE_STAYS_HERE });+ expect(JSON.stringify((await cloud("GET", `/api/threads/${work}/messages`)).body.messages)).not.toContain("line-for-owner-work");++ writeFileSync(release, "");+ await sleep(2_000);+ rmSync(release, { force: true });+ rmSync(dump, { force: true });+ }, hostTimeout(180_000));+});++describe("a desktop", () => {+ it("brings no level down from a webhook's Chief: the teammate keeps its own", async () => {+ const local = fx.local;+ const chief = (await local("POST", "/api/bots", { name: "Desk chief" })).body.bot;+ expect((await local("PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: true, approvalMode: "full", applyToAllThreads: true })).status).toBe(200);+ const mate = (await local("POST", "/api/bots", { name: "Desk mate" })).body.bot;+ expect((await local("PATCH", `/api/bots/${mate.id}`, { approvalMode: "ask", applyToAllThreads: true })).status).toBe(200);+ const hook = (await local("POST", "/api/webhooks", { name: "Desk hook", prompt: "Handle the event.", botId: chief.id })).body;+ const port = Number(new URL(fx.desktopBase).port) + 1;+ expect((await fetch(`http://127.0.0.1:${port}/hooks/${hook.webhook.endpointId}/${encodeURIComponent(hook.credential.secret)}`, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": randomBytes(6).toString("hex") }, body: JSON.stringify({ text: "marker-desktop" }) })).status).toBe(202);+ expect(atFull(await turnWith("marker-desktop"))).toBe(true);+ const thread = ((await local("GET", "/api/routines")).body.runs as any[]).find((run) => run.webhookId === hook.webhook.id).threadId as string;+ const minted = await (await fetch(`${fx.desktopBase}/api/testing/internal-capability`, { method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": KEY }, body: JSON.stringify({ botId: chief.id, threadId: thread }) })).json() as any;+ const sent = await fetch(`${fx.desktopBase}/api/internal/coordinate-bots?fromBotId=${chief.id}`, { method: "POST", headers: { authorization: `Bearer ${minted.token}`, "content-type": "application/json" }, body: JSON.stringify({ fromBotId: chief.id, fromThreadId: thread, botIds: [mate.id], message: "brief-desktop", reply: "none" }) });+ expect(sent.status).toBe(200);+ expect(atFull(await turnWith("brief-desktop"))).toBe(false);+ writeFileSync(release, "");+ await sleep(1_500);+ rmSync(release, { force: true });+ }, hostTimeout(120_000));+});diff --git a/server/store.ts b/server/store.tsindex 9cde89b0b6..eb3945bce2 100644--- a/server/store.ts+++ b/server/store.ts@@ -104,7 +104,7 @@ const ASK_NOW = { approvalMode: "ask" as const, autoApprove: false, alwaysAllow:const TASK_PATCH_FIELDS = ["title", "projectId", "modelSelection", "approvalMode", "autoApprove", "alwaysAllow","unread", "lastReadMessageId", "rewound", "archivedAt", "pinned", "pinnedMessageId", "resumeCursors", "lastInstanceId", "cwd",- "routineRunId", "surface", "surfaceSource", "snoozedUntil", "link", "linkAuto", "appliedCompactionId", "contextFloor", "lastContextModel", "setupRequest",+ "routineRunId", "surface", "surfaceSource", "snoozedUntil", "link", "linkAuto", "appliedCompactionId", "contextFloor", "lastContextModel", "setupRequest", "outside",] as const satisfies readonly (keyof TaskRecord)[];export type TaskPatch = Partial<Pick<TaskRecord, typeof TASK_PATCH_FIELDS[number]>>;diff --git a/server/testing/team-inbox-fixture.ts b/server/testing/team-inbox-fixture.tsindex ae89988119..d51b899159 100644--- a/server/testing/team-inbox-fixture.ts+++ b/server/testing/team-inbox-fixture.ts@@ -23,7 +23,7 @@ export const session = (email: string) => ({ kind: "session", scopes: ["client"]type Task = { threadId: string; title: string; archivedAt?: number; activity?: string; routineRunId?: string };type Bot = Partial<Omit<BotRecord, "tasks">> & { id: string; name: string; threadId: string; tasks: Task[] };-export function teamInbox(options: { team?: boolean; representative?: TeamMessagesDeps["inbox"]["representative"]; noChiefFor?: string[]; handed?: Record<string, string> } = {}) {+export function teamInbox(options: { team?: boolean; representative?: TeamMessagesDeps["inbox"]["representative"]; noChiefFor?: string[]; handed?: Record<string, string>; confined?: string[] } = {}) {const dataDir = mkdtempSync(join(tmpdir(), "omb-team-inbox-"));const listeners = new Set<(change: StoreChange) => void>();const emit = (change: StoreChange) => { for (const listener of listeners) listener(change); };@@ -92,6 +92,7 @@ export function teamInbox(options: { team?: boolean; representative?: TeamMessagdataDir,now: tick,store: store as never,+ confined: (threadId) => (options.confined ?? []).includes(threadId),people: { everyone: () => people.map(({ email, role, leftAt }) => ({ email, role, firstSeenAt: 1, lastSeenAt: 1, ...(leftAt ? { leftAt } : {}) })) },personName: (person) => people.find((one) => key(one.email) === person)?.name,audienceOf,diff --git a/shared/wire.ts b/shared/wire.tsindex d72e1629e1..9b6c52b6c0 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -143,6 +143,8 @@ export interface WireTask extends InboxTask {projectId?: string;/** Detached routine execution, reachable through its visible results card. */routineRunId?: string;+ /** Work from outside (a webhook, an app's event) reached this conversation: what it starts or runs stays confined, for good. */+ outside?: true;/** Set when a bot, not a person, opened this thread. */openedBy?: TaskOpenedBy;/** On a team's server: one person's conversation, seen by them alone (never by another member or an admin). */@@ -655,6 +657,8 @@ export interface OptionCardData extends WaitCardField, ComputerAskField, AccessRoutboundRequest?: { tool: string; app: string | null; calls?: Array<{ app: string | null; label: string }> };/** `revision`: the entry as it applied without a person, so Undo can tell it changed since. */teamMemoryRequest?: { section: string; entryId: string; kind: string; revision?: string };+ /** What work from outside asked to write where later turns read it; nothing is written until a person says yes. */+ outsideWrite?: { kind: "room-bulletin"; roomId: string; bulletin: string } | { kind: "memory"; action: string; text?: string; oldText?: string; until?: string };title: string;subtitle: string;options: string[];diff --git a/src/locales/de.json b/src/locales/de.jsonindex 69ff67dbcc..00f52498c0 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -178,6 +178,12 @@"server.rooms.noneActive": "Kein aktives Raummitglied kann antworten. Stelle einen archivierten Bot wieder her oder füge ein aktives Mitglied hinzu.","server.rooms.stillStopping": "{bot} wird noch gestoppt, diese Nachricht wurde nicht zugestellt","server.rooms.someoneStillStopping": "Ein Raummitglied wird noch gestoppt, diese Nachricht wurde nicht zugestellt",+ "server.outside.confinedHere": "Arbeit von außen ist in dieses Gespräch gekommen, deshalb arbeitet dieser Bot hier ohne Shell. Starte ein neues Gespräch, um ihn voll zu nutzen.",+ "server.outside.bulletinTitle": "Die Anweisungen dieser Gruppe ändern?",+ "server.outside.memoryTitle": "Das im Gedächtnis des Bots speichern?",+ "server.outside.memoryChangeTitle": "Das im Gedächtnis des Bots ändern oder entfernen?",+ "server.outside.save": "Speichern",+ "server.outside.skip": "Überspringen","server.rooms.postedIn": "Gepostet in {room}","server.rooms.openedThread": "Thread #{title} geöffnet","server.rooms.held": "{bot} ist angehalten (von dir gestoppt). Erwähne ihn mit @ oder schreib „resume“",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 2dc463d346..9dbe6cb489 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -274,6 +274,12 @@"server.rooms.noneActive": "No active room members can respond — restore an archived bot or add an active member.","server.rooms.stillStopping": "{bot} is still stopping — this message was not dispatched","server.rooms.someoneStillStopping": "A room member is still stopping — this message was not dispatched",+ "server.outside.confinedHere": "Work from outside came into this conversation, so this bot works here without a shell. Start a new conversation to use it fully.",+ "server.outside.bulletinTitle": "Change this group chat's instructions?",+ "server.outside.memoryTitle": "Save this to the bot's memory?",+ "server.outside.memoryChangeTitle": "Change or remove this in the bot's memory?",+ "server.outside.save": "Save",+ "server.outside.skip": "Skip","server.rooms.postedIn": "Posted in {room}","server.rooms.openedThread": "Opened thread #{title}","server.rooms.held": "{bot} is held (stopped by you) — @mention it or say resume",