Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.
Let a Bot at its own endpoint hand work to another Bot (#718)
David McKay39489d8fdd39
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c7d9d9df..5f8d0515 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,14 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged.## Unreleased+### A coworker at its own endpoint can hand work to another Bot++A grant letting a remote Bot (a coworker at its own endpoint) hand work to another Bot was accepted and stored, but the grant read kept only built-in Bots, so the remote Bot was never+offered `message_bot` and a call it made anyway was refused as not granted. The read now counts a+grant whatever the Bot's type, so a remote Bot hands work on through the same signed callback, grant+check, caps and audit rows as a built-in one, to a built-in Bot or to another remote Bot. The+coworker's handoff panel now offers it the same switches.+### A channel cursor with a malformed time reads as the first page, not a 500`GET /api/channels` only checked that a cursor's time was a string before casting it withdiff --git a/app/src/components/agents/handoff-panel.tsx b/app/src/components/agents/handoff-panel.tsxindex 39397172..d16e764b 100644--- a/app/src/components/agents/handoff-panel.tsx+++ b/app/src/components/agents/handoff-panel.tsx@@ -106,9 +106,9 @@ export function HandoffPanel({ agentId }: { agentId: string }) {<ItemTitle>This coworker cannot hand work on</ItemTitle>{/* Unclamped for the same reason as above: three lines, and the third is the useful one. */}<ItemDescription className="line-clamp-none">- Handing work on is a tool that runs inside this deployment's own- loop, and this coworker runs as its own agent — so there is- nothing to grant it. It can still be asked by Bots that can.+ This deployment has nowhere to record which Bots it may hand work+ to, so there is nothing to grant it. It can still be asked by Bots+ that can.</ItemDescription></ItemContent></Item>diff --git a/server/src/agents/profile-store.ts b/server/src/agents/profile-store.tsindex 426bb67a..eda2f224 100644--- a/server/src/agents/profile-store.ts+++ b/server/src/agents/profile-store.ts@@ -261,9 +261,8 @@ export type AgentRun = {* do-not-fabricate instruction. Copy it and you get a coworker with the name, the title, the avatar,* and none of that.*- * The type is carried too, not only the configuration. A copy written as `remote_ag_ui` also cannot- * be granted handoff for the rest of its life: `agentRunsHere` and `botsReachableFrom` both key on- * `agents.type == "built_in"`, so the original may hand work on and its copy silently may not.+ * The type is carried too, not only the configuration, so a copy runs the same way its original+ * does.** `null` means there is nothing to run this copy on, which the caller turns into* {@link ManagedAgentUnavailableError}. That can now only happen for a source that had neither andiff --git a/server/src/agents/routes.ts b/server/src/agents/routes.tsindex c5009c02..7c7be199 100644--- a/server/src/agents/routes.ts+++ b/server/src/agents/routes.ts@@ -264,12 +264,11 @@ export function createAgentRoutes(/** The Bots this one may address today, read per call so a revoked grant stops showing. */reachableFrom: (agentId: string) => Promise<readonly string[]>;/**- * Whether this Bot can be a grantee at all — the handing-on tool executes inside this- * deployment's own run loop, so only a Bot that runs in it can be offered one. Exposed so the- * screen can say that once, instead of letting every switch fail with the same refusal.- * Optional so a caller without a plugin store answers "no" rather than crashing the read.+ * Whether this Bot can be a grantee at all: any Bot that exists, built in or at its own+ * endpoint, since both reach the same handoff desk. Optional so a caller without a plugin store+ * answers "no" rather than crashing the read.*/- runsHere?: (agentId: string) => Promise<boolean | undefined>;+ canHandOn?: (agentId: string) => Promise<boolean | undefined>;},/*** Whether a coworker can run on this deployment's own Bot, i.e. be created with no endpoint.@@ -720,8 +719,8 @@ export function createAgentRoutes(reachable: handoff ? await handoff.reachableFrom(agentId) : [],// Whether this Bot can hold such a grant at all; the write path refuses one that cannot,// and the screen should say so before a person flips switches that can only bounce.- grantable: handoff?.runsHere- ? ((await handoff.runsHere(agentId)) ?? false)+ grantable: handoff?.canHandOn+ ? ((await handoff.canHandOn(agentId)) ?? false): false,},});diff --git a/server/src/app.ts b/server/src/app.tsindex ca7f16a7..d43e5d79 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -1308,7 +1308,7 @@ export function createApp(reachableFrom: (agentId) =>pluginStore.botsReachableFrom(agentId),// The same answer the write path checks, read up front so the screen can say it once.- runsHere: (agentId) => pluginStore.agentRunsHere(agentId),+ canHandOn: (agentId) => pluginStore.agentCanHandOn(agentId),}: undefined,// Whether "built-in" is a kind of coworker this deployment can actually make: the creatediff --git a/server/src/plugins/store.ts b/server/src/plugins/store.tsindex 9174d1c2..4fa01f02 100644--- a/server/src/plugins/store.ts+++ b/server/src/plugins/store.ts@@ -4230,22 +4230,21 @@ export function createPluginStore(options: PluginStoreOptions) {* "may this person put their skill on that Bot", and a whole profile is more than that needs.*//**- * Whether this Bot's run happens in this process, rather than at an endpoint somewhere.+ * Whether this Bot can be granted handing work on, or `undefined` if there is no such Bot.*- * Undefined for a Bot nobody has heard of. Asked because a tool this deployment executes can- * only be offered to a run it builds: a Bot at an endpoint runs its own loop and is handed- * descriptions of what it may call back for, and handing work to another Bot is not one of them.+ * Any Bot that exists can: a built-in Bot runs `message_bot` in this process, and a Bot at its+ * own endpoint calls back for it through the signed tool callback, which reaches the same desk.*/- async agentRunsHere(agentId: string): Promise<boolean | undefined> {+ async agentCanHandOn(agentId: string): Promise<boolean | undefined> {const [row] = await database- .select({ type: agents.type })+ .select({ id: agents.id }).from(agents).innerJoin(agentProfiles, eq(agentProfiles.agentId, agents.id))// A deleted Bot is not one anybody may be given, and answering about it at all would say it// had existed..where(and(eq(agents.id, agentId), isNull(agentProfiles.deletedAt))).limit(1);- return row ? row.type === "built_in" : undefined;+ return row ? true : undefined;},/**@@ -4418,17 +4417,15 @@ export function createPluginStore(options: PluginStoreOptions) {* is a single indexed read, which is the right price for that.*//**- * The Bots this one may hand work to, and can actually reach.+ * The Bots this one may hand work to.*- * FILTERED AT READ TIME, not only when the grant is made. Refusing a new grant to a Bot that- * runs at its own endpoint stops one being created; it does nothing about the ones already- * there, or about a Bot that was built in when it was granted and was pointed at an endpoint- * afterwards. Those rows read as configured and are inert, which is the shape of thing an- * administrator debugs for an afternoon: the grant is right there in the table and no hop ever- * happens.+ * Whatever the grantee's type. A Bot at its own endpoint is offered `message_bot` as a tool it+ * calls back for, and the call reaches the same handoff desk, grant check and caps as a built-in+ * Bot's (see `createCoordinationTools`). This used to keep only built-in grantees, from before+ * remote Bots could call back for coordination, which left every remote Bot's grant reading as+ * configured while no hop ever happened.*- * The asking side is the one that matters here — a Bot at an endpoint runs its own loop and is- * never offered this tool — so it is the grantee, `agent_id`, that is checked.+ * The join keeps a grant held by a Bot that no longer exists from counting.*/async botsReachableFrom(agentId: string): Promise<string[]> {const rows = await database@@ -4436,11 +4433,7 @@ export function createPluginStore(options: PluginStoreOptions) {.from(pluginGrants).innerJoin(agents, eq(agents.id, pluginGrants.agentId)).where(- and(- eq(pluginGrants.kind, "bot"),- eq(pluginGrants.agentId, agentId),- eq(agents.type, "built_in"),- ),+ and(eq(pluginGrants.kind, "bot"), eq(pluginGrants.agentId, agentId)),);return rows.map((row) => row.ref);},diff --git a/server/tests/agent-handoff-endtoend.integration.test.ts b/server/tests/agent-handoff-endtoend.integration.test.tsindex 863ee749..e5fa5207 100644--- a/server/tests/agent-handoff-endtoend.integration.test.ts+++ b/server/tests/agent-handoff-endtoend.integration.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeEach, describe, expect, test } from "bun:test";import { randomUUID } from "node:crypto";-import { and, eq, like } from "drizzle-orm";+import { and, eq, sql } from "drizzle-orm";import { createHandoffDesk } from "../src/agents/handoff";import {createHandoffRunner,@@ -67,7 +67,11 @@ const desk = createHandoffDesk({});async function clean() {- await database.delete(workItems).where(like(workItems.key, `${RUN}%`));+ // By the suite's own actor, which every hop's payload carries. A hop's key is `hop:<hash>:<hash>`,+ // so a key prefix matches nothing, and a hop left queued is claimed by the next suite's sweep.+ await database+ .delete(workItems)+ .where(sql`${workItems.payload}->>'actorId' = ${ACTOR}`);for (const id of [ASKER, TARGET]) {await database.delete(pluginGrants).where(eq(pluginGrants.agentId, id));await database.delete(agentProfiles).where(eq(agentProfiles.agentId, id));diff --git a/server/tests/agent-handoff.integration.test.ts b/server/tests/agent-handoff.integration.test.tsindex 5ec8c5f4..e6eed5a9 100644--- a/server/tests/agent-handoff.integration.test.ts+++ b/server/tests/agent-handoff.integration.test.ts@@ -1,6 +1,6 @@import { afterAll, beforeEach, describe, expect, test } from "bun:test";import { randomUUID } from "node:crypto";-import { and, eq, like } from "drizzle-orm";+import { and, eq, sql } from "drizzle-orm";import { createHandoffDesk, HANDOFF_KIND } from "../src/agents/handoff";import { createAgentProfileStore } from "../src/agents/profile-store";import { createAuditStore } from "../src/audit";@@ -53,7 +53,11 @@ const desk = createHandoffDesk({});async function clean() {- await database.delete(workItems).where(like(workItems.key, `run-${suite}%`));+ // By the suite's own actor, which every hop's payload carries. A hop's key is `hop:<hash>:<hash>`,+ // so a key prefix matches nothing, and a hop left queued is claimed by the next suite's sweep.+ await database+ .delete(workItems)+ .where(sql`${workItems.payload}->>'actorId' = ${ACTOR}`);for (const id of [ASKER, TARGET]) {await database.delete(pluginGrants).where(eq(pluginGrants.agentId, id));await database.delete(agentProfiles).where(eq(agentProfiles.agentId, id));diff --git a/server/tests/agent-routes.test.ts b/server/tests/agent-routes.test.tsindex 86977bbc..46710c67 100644--- a/server/tests/agent-routes.test.ts+++ b/server/tests/agent-routes.test.ts@@ -698,7 +698,7 @@ describe("which Bots a Bot may hand work to", () => {enabled: true,canGrant: true,reachable: ["knowledge"],- // No runsHere reader was wired, and a Bot nothing can vouch for is not offered grants.+ // No canHandOn reader was wired, and a Bot nothing can vouch for is not offered grants.grantable: false,});});diff --git a/server/tests/plugin-routes.test.ts b/server/tests/plugin-routes.test.tsindex 1e3c4a27..ffe3eaca 100644--- a/server/tests/plugin-routes.test.ts+++ b/server/tests/plugin-routes.test.ts@@ -377,10 +377,10 @@ describe("refreshing a server that cannot be resolved", () => {*/function grantsApp(role: "admin" | "user" = "admin",- runsHere: (agentId: string) => boolean | undefined = (agentId) => {+ canHandOn: (agentId: string) => boolean | undefined = (agentId) => {// Undefined is "no such Bot", which is what the store answers for one nobody registered.if (agentId === "never-registered") return undefined;- return agentId !== "at-an-endpoint";+ return true;},) {/**@@ -416,7 +416,7 @@ function grantsApp(},skillOwner: async () => null,agentOwner: async () => null,- agentRunsHere: async (agentId: string) => runsHere(agentId),+ agentCanHandOn: async (agentId: string) => canHandOn(agentId),agentIsRegistered: async (agentId: string) =>agentId !== "never-registered",});diff --git a/server/tests/remote-bot-handoff.integration.test.ts b/server/tests/remote-bot-handoff.integration.test.tsnew file mode 100644index 00000000..e719af1f--- /dev/null+++ b/server/tests/remote-bot-handoff.integration.test.ts@@ -0,0 +1,206 @@+import { afterAll, beforeEach, describe, expect, test } from "bun:test";+import { randomUUID } from "node:crypto";+import { and, eq, inArray, sql } from "drizzle-orm";+import { createHandoffDesk } from "../src/agents/handoff";+import { createAgentProfileStore } from "../src/agents/profile-store";+import { createAuditStore } from "../src/audit";+import { createDatabase } from "../src/db/client";+import {+ agentProfiles,+ agents,+ auditEvents,+ pluginGrants,+ workItems,+} from "../src/db/schema";+import type { ComposioBroker } from "../src/plugins/broker";+import { createPluginStore } from "../src/plugins/store";+import { createWorkQueue } from "../src/work/queue";+import { TEST_POOL, testDatabaseUrl } from "./support/database";++/**+ * A Bot at its own endpoint hands work on, through the plugin store's own grant read.+ *+ * The desk in `agent-handoff.integration.test.ts` reads grants with its own query, so it could not+ * see the store keeping only built-in grantees. This one is wired the way `index.ts` wires the+ * desk: `mayAddress` is `botsReachableFrom`, failing closed.+ */++const database = createDatabase(testDatabaseUrl(), TEST_POOL);++const suite = randomUUID().slice(0, 8);+const REMOTE = `remote-asker-${suite}`;+const BUILT_IN = `built-in-target-${suite}`;+const OTHER_REMOTE = `remote-target-${suite}`;+const ACTOR = `remote-handoff-actor-${suite}`;+const ALL = [REMOTE, BUILT_IN, OTHER_REMOTE];++const broker: ComposioBroker = {+ listApps: async () => [],+ ensureAuthConfig: async () => undefined,+ deleteAuthConfig: async () => undefined,+ authorize: async () => {+ throw new Error("a handoff grant asked the broker for a connection");+ },+ isConnected: async () => false,+ revoke: async () => true,+};++const auditStore = createAuditStore(database);+const store = createPluginStore({+ database,+ auditStore,+ credentials: {+ readSecret: async () => null,+ create: async () => {+ throw new Error("a handoff grant asked the vault to create a secret");+ },+ updateSecret: async () => {+ throw new Error("a handoff grant asked the vault to write a secret");+ },+ revoke: async () => {+ throw new Error("a handoff grant asked the vault to revoke a secret");+ },+ },+ encryptionKey: "x".repeat(44),+ policy: () => ({ mode: "enforce", deny: [], allow: ["true"] }),+ broker,+});++const desk = createHandoffDesk({+ queue: createWorkQueue(database),+ profiles: createAgentProfileStore(database),+ actorFor: async (id: string) => ({ id, role: "user" as const }),+ mayAddress: async (fromBotId, toBotId) =>+ (+ await store.botsReachableFrom(fromBotId).catch(() => [] as string[])+ ).includes(toBotId),+ auditStore,+ caps: { maxDepth: 2, maxPerRun: 4 },+});++async function clean() {+ // By the suite's own actor, which every hop's payload carries. A hop's key is `hop:<hash>:<hash>`,+ // so a key prefix matches nothing, and a hop left queued is claimed by the next suite's sweep.+ await database+ .delete(workItems)+ .where(sql`${workItems.payload}->>'actorId' = ${ACTOR}`);+ await database.delete(pluginGrants).where(inArray(pluginGrants.agentId, ALL));+ await database+ .delete(agentProfiles)+ .where(inArray(agentProfiles.agentId, ALL));+ await database.delete(agents).where(inArray(agents.id, ALL));+}++beforeEach(async () => {+ await clean();+ const rows = [+ {+ id: REMOTE,+ name: "Remote Asker",+ type: "remote_ag_ui" as const,+ configuration: { endpoint: "http://127.0.0.1:1/agui" },+ },+ {+ id: BUILT_IN,+ name: "Built In Target",+ type: "built_in" as const,+ configuration: { systemPrompt: "Help." },+ },+ {+ id: OTHER_REMOTE,+ name: "Remote Target",+ type: "remote_ag_ui" as const,+ configuration: { endpoint: "http://127.0.0.1:2/agui" },+ },+ ];+ for (const row of rows) {+ await database.insert(agents).values(row);+ await database.insert(agentProfiles).values({+ agentId: row.id,+ name: row.name,+ title: "",+ roleDescription: "",+ avatarSeed: row.id,+ visibility: "public",+ });+ }+});++afterAll(async () => {+ await clean();+ await database.$client.end({ timeout: 5 });+});++const from = (runId = `run-${suite}-1`) => ({+ botId: REMOTE,+ actorId: ACTOR,+ runId,+ threadId: `thread-${suite}`,+ depth: 0,+});++describe("a Bot at its own endpoint, handing work on", () => {+ test("its grant is read back, whatever its type", async () => {+ expect(await store.botsReachableFrom(REMOTE)).toEqual([]);++ await store.grant("bot", BUILT_IN, REMOTE, "test");++ expect(await store.botsReachableFrom(REMOTE)).toEqual([BUILT_IN]);+ });++ test("the screen is told it can hold the grant", async () => {+ expect(await store.agentCanHandOn(REMOTE)).toBe(true);+ expect(await store.agentCanHandOn(BUILT_IN)).toBe(true);+ expect(await store.agentCanHandOn(`nobody-${suite}`)).toBeUndefined();+ });++ test("without a grant the hop is refused and says so", async () => {+ const refused = await desk.send({+ from: from(),+ target: BUILT_IN,+ envelope: { task: "have a look" },+ });+ expect(refused.ok).toBe(false);++ const [row] = await database+ .select({ payload: auditEvents.payload })+ .from(auditEvents)+ .where(+ and(+ eq(auditEvents.eventType, "agent.handoff_refused"),+ eq(auditEvents.targetId, REMOTE),+ ),+ )+ .limit(1);+ expect(row).toBeDefined();+ });++ test("granted, it hands work to a built-in Bot and to another remote Bot", async () => {+ await store.grant("bot", BUILT_IN, REMOTE, "test");+ await store.grant("bot", OTHER_REMOTE, REMOTE, "test");++ const toBuiltIn = await desk.send({+ from: from(`run-${suite}-2`),+ target: BUILT_IN,+ envelope: { task: "have a look" },+ });+ expect(toBuiltIn).toMatchObject({ ok: true, to: BUILT_IN });++ const toRemote = await desk.send({+ from: from(`run-${suite}-3`),+ target: OTHER_REMOTE,+ envelope: { task: "and you" },+ });+ expect(toRemote).toMatchObject({ ok: true, to: OTHER_REMOTE });++ const offered = await database+ .select({ payload: auditEvents.payload })+ .from(auditEvents)+ .where(eq(auditEvents.eventType, "agent.handoff_offered"));+ const targets = offered+ .map((row) => row.payload as Record<string, unknown>)+ .filter((payload) => payload.from === REMOTE)+ .map((payload) => payload.to);+ expect(targets).toEqual(expect.arrayContaining([BUILT_IN, OTHER_REMOTE]));+ });+});