Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Let a bot the first room answer @mentions change its own skills
AdityaUmaleca790a6ae4be
diff --git a/docs/runtime-contract.md b/docs/runtime-contract.mdindex e9be9f5307..51991f1d4f 100644--- a/docs/runtime-contract.md+++ b/docs/runtime-contract.md@@ -126,7 +126,7 @@ Every turn that may hand work on, whatever started it, gets the same tools:- `start_thread` (on yourself) takes an optional `model_selection` (ids from the read-only `list_models`) and `report_back`: with it the thread is an assignment of the bot's own, and its result resumes the opener like a teammate's.- `list_bots`, `list_threads`, `close_thread`, `post_to_room`, `list_rooms`, the Chief tools and `retry_thread` are unchanged.-Every turn of one conversation is listed the same tools, byte for byte, so the provider's cached prompt carries over from turn to turn; what a turn may not do it is told when it calls the tool. Only what is fixed for the conversation shapes the list: `select_computer` in a direct chat whose bot may pick where it works (`OMB_COMPUTER_SELECTION`: Works on is not Off and no team computer is its own), refused with the reason on any turn but a person's own message; no `show_widget`, `show_html` or wait tools in a room (`OMB_ROOM`), since a room refuses the first two and holds no wait; `wait_until`, `list_waits` and `cancel_wait` in every direct chat, with or without a wait (with none, the last two say there is nothing to list or cancel); the skill tools wherever skill authoring is on, refused in a room to every turn but the first answer to a person's message.+Every turn of one conversation is listed the same tools, byte for byte, so the provider's cached prompt carries over from turn to turn; what a turn may not do it is told when it calls the tool. Only what is fixed for the conversation shapes the list: `select_computer` in a direct chat whose bot may pick where it works (`OMB_COMPUTER_SELECTION`: Works on is not Off and no team computer is its own), refused with the reason on any turn but a person's own message; no `show_widget`, `show_html` or wait tools in a room (`OMB_ROOM`), since a room refuses the first two and holds no wait; `wait_until`, `list_waits` and `cancel_wait` in every direct chat, with or without a wait (with none, the last two say there is nothing to list or cancel); the skill tools wherever skill authoring is on, refused in a room to every turn but the first answer to a person's message and, once each, the bots that answer @mentions.The old names (`delegate_bot`, `ask_bot`, `send_to_bot`, `check_delegation`, `wait_delegation`) stayed for one release as aliases with a deprecation line in their result and were removed in PR 5; `start_thread` opens a job on the bot itself.diff --git a/server/agents-turn.test.ts b/server/agents-turn.test.tsindex 3181530350..a97c73691b 100644--- a/server/agents-turn.test.ts+++ b/server/agents-turn.test.ts@@ -4,7 +4,7 @@ import { createHash } from "node:crypto";import { describe, expect, it } from "vitest";import { TOOL_BRIDGE_ENV } from "./drivers/agents-bridge.ts";import { agentsMcp } from "./drivers/agents-mcp.ts";-import { agentsServerEnv, botDrivenConversation, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, roomSkillsRefusal, type AgentsConversation, type AgentsTurn } from "./agents-turn.ts";+import { agentsServerEnv, botDrivenConversation, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, handRoomSkills, roomSkillsRefusal, roomTurnMayWriteSkills, takeRoomSkills, type AgentsConversation, type AgentsTurn, type RoomSkillsClaim } from "./agents-turn.ts";const HOST: AgentsConversation["host"] = { skillAuthoring: true, sharedComputers: true, cloudHome: false, team: false, voiceNotes: true, x: true, research: true, imageGeneration: false, localVm: true };const CHAT: AgentsConversation = { threadId: "thread-1", bot: { id: "bot-1", chiefOfStaff: true }, room: false, teamComputer: false, host: HOST };@@ -20,9 +20,10 @@ const CHAT_TURNS: Record<string, AgentsTurn> = {"the continuation on a newly picked computer": { generation: "picked", depth: 0, skillAuthoring: true },"a turn that delivers files saved outside its folders": { generation: "files", depth: 0, skillAuthoring: true, deliversSavedFiles: true },};-/** And a room: only the first answer to a person's message may list or write skills. */+/** And a room: only the first answer to a person's message, and the bots it @mentions, may list or write skills. */const ROOM_TURNS: Record<string, AgentsTurn> = {"the first answer to a person, holding the skill claim": { generation: "first", depth: 0, skillAuthoring: true },+ "a bot that first answer @mentioned": { generation: "mentioned", depth: 1, skillAuthoring: true },"a follow-up once the claim is spent": { generation: "follow-up", depth: 1, skillAuthoring: false },"a hand-off into the room": { generation: "room-handoff", depth: 1, skillAuthoring: false, roomHandoffId: "node-2" },"a goal step": { generation: "goal", depth: 0, skillAuthoring: false },@@ -134,7 +135,47 @@ describe("what a turn that may not use a listed tool is told", () => {});it("says which room turn may change skills", () => {- expect(roomSkillsRefusal(false)).toBe("In a room, only the first bot answering a person's message can list or write skills. This turn is a follow-up, so carry on without changing skills.");+ expect(roomSkillsRefusal(false)).toBe("In a room, only the first bot answering a person's message, and a bot it @mentions in that answer, can list or write skills. This turn is a follow-up, so carry on without changing skills.");expect(roomSkillsRefusal(true)).toMatch(/This turn is a teammate's hand-off, so carry on without changing skills\.$/);});++ describe("on one person's message in a room", () => {+ it("lets the first bot answering change skills once, and no other first answer", () => {+ const claim: RoomSkillsClaim = { claimed: false };+ expect(roomTurnMayWriteSkills(claim, 0, "writer")).toBe(true);+ takeRoomSkills(claim, 0, "writer", true);+ expect(roomTurnMayWriteSkills(claim, 0, "writer")).toBe(false);+ expect(roomTurnMayWriteSkills(claim, 0, "editor")).toBe(false);+ });++ it("lets a bot that first answer @mentions change its own skills once, and only that bot", () => {+ const claim: RoomSkillsClaim = { claimed: false };+ takeRoomSkills(claim, 0, "writer", true);+ expect(roomTurnMayWriteSkills(claim, 1, "video")).toBe(false);+ handRoomSkills(claim, "video");+ expect(roomTurnMayWriteSkills(claim, 1, "video")).toBe(true);+ expect(roomTurnMayWriteSkills(claim, 1, "editor")).toBe(false);+ takeRoomSkills(claim, 1, "video", true);+ expect(roomTurnMayWriteSkills(claim, 1, "video")).toBe(false);+ });++ it("never lets a bot mentioned further down the chain change skills", () => {+ const claim: RoomSkillsClaim = { claimed: false };+ takeRoomSkills(claim, 0, "writer", true);+ handRoomSkills(claim, "video");+ expect(roomTurnMayWriteSkills(claim, 2, "video")).toBe(false);+ expect(roomTurnMayWriteSkills(claim, 2, "editor")).toBe(false);+ });++ it("gives the share back to a turn that never ran", () => {+ const claim: RoomSkillsClaim = { claimed: false };+ takeRoomSkills(claim, 0, "writer", true);+ handRoomSkills(claim, "video");+ takeRoomSkills(claim, 1, "video", true);+ takeRoomSkills(claim, 1, "video", false);+ expect(roomTurnMayWriteSkills(claim, 1, "video")).toBe(true);+ takeRoomSkills(claim, 0, "writer", false);+ expect(roomTurnMayWriteSkills(claim, 0, "editor")).toBe(true);+ });+ });});diff --git a/server/agents-turn.ts b/server/agents-turn.tsindex f21862ae82..47610fcb87 100644--- a/server/agents-turn.ts+++ b/server/agents-turn.ts@@ -25,7 +25,7 @@ export interface AgentsConversation {export interface AgentsTurn {generation: string;depth: number;- /** In a room only the first answer to a person's message may list or write skills. */+ /** In a room only the first answer to a person's message, and each bot that answer @mentions, may list or write skills. */skillAuthoring: boolean;roomHandoffId?: string;deliversSavedFiles?: boolean;@@ -95,7 +95,30 @@ export function computerPickRefusal(kind: TurnKind | undefined): string {return `Picking a computer works only on a person's own message. ${THIS_TURN[kind]}, so carry on with the computer already in use.`;}-/** skills_list or skill_manage on a room turn that is not the first answer to a person's message. */+/** skills_list or skill_manage on a room turn that is neither the first answer to a person's message nor a bot it @mentioned. */export function roomSkillsRefusal(handoff: boolean): string {- return `In a room, only the first bot answering a person's message can list or write skills. ${handoff ? THIS_TURN.handoff : "This turn is a follow-up"}, so carry on without changing skills.`;+ return `In a room, only the first bot answering a person's message, and a bot it @mentions in that answer, can list or write skills. ${handoff ? THIS_TURN.handoff : "This turn is a follow-up"}, so carry on without changing skills.`;+}++/** Who may still list and write skills on one person's message in a room: the first bot answering it (hop 0), once, and each+ * bot that answer @mentions (hop 1), once each. A bot those mention (hop 2 and on) never may. */+export interface RoomSkillsClaim {+ claimed: boolean;+ mentioned?: Set<string>;+}++export function roomTurnMayWriteSkills(claim: RoomSkillsClaim, hop: number, botId: string): boolean {+ return hop === 0 ? !claim.claimed : hop === 1 && claim.mentioned?.has(botId) === true;+}++/** The first answer, holding the claim, @mentions `botId`: that bot may change its own skills once on this message. */+export function handRoomSkills(claim: RoomSkillsClaim, botId: string): void {+ (claim.mentioned ??= new Set()).add(botId);+}++/** A turn that may write skills takes its share once its setup succeeded (`taken`), or gives it back when it never ran. */+export function takeRoomSkills(claim: RoomSkillsClaim, hop: number, botId: string, taken: boolean): void {+ if (hop === 0) claim.claimed = taken;+ else if (taken) claim.mentioned?.delete(botId);+ else handRoomSkills(claim, botId);}diff --git a/server/index.ts b/server/index.tsindex f862ba22a0..f6712e9c69 100644--- a/server/index.ts+++ b/server/index.ts@@ -487,7 +487,7 @@ import { WebhookManager } from "./webhooks.ts";import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitContinuationCheck, waitLineFields, waitRunChat, waitTurnRunId } from "./wait-host.ts"; import { continuedConversation } from "./routine-same-conversation.ts"; import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";import type { WebhookTrigger } from "../shared/webhooks.ts";import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";-import { agentsProxyLaunch, agentsToolBridgeEnv, applyAgentsBridge, bridgedToolTitle, turnEngine } from "./agents-bridge-switch.ts"; import { serverTurnedOff } from "./drivers/agents-tool-groups.ts"; import { availableToolGroups, toolsOffPart } from "./tool-groups.ts"; import { agentsServerEnv, botDrivenConversation, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, roomSkillsRefusal, type TurnKind } from "./agents-turn.ts";+import { agentsProxyLaunch, agentsToolBridgeEnv, applyAgentsBridge, bridgedToolTitle, turnEngine } from "./agents-bridge-switch.ts"; import { serverTurnedOff } from "./drivers/agents-tool-groups.ts"; import { availableToolGroups, toolsOffPart } from "./tool-groups.ts"; import { agentsServerEnv, botDrivenConversation, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, handRoomSkills, roomSkillsRefusal, roomTurnMayWriteSkills, takeRoomSkills, type RoomSkillsClaim, type TurnKind } from "./agents-turn.ts";import { harnessMcpTokenEnv } from "./harness-mcp-token.ts";import { loadBundledSkills, loadUserSkills, mergeSkills, renderSkillInstructions, selectBundledSkills, skillsLibraryEnabled, readSkillLibraryIndex } from "./skill-library.ts";import { runSkillsLibraryBootSweep } from "./skills-library-migration.ts";@@ -9476,7 +9476,7 @@ async function runClaimedGroupMemberTurn(isCancelled?: () => boolean,onProviderHandshakeStarted?: () => void,onProviderHandshakeSettled?: () => void,- skillAuthoringClaim: { claimed: boolean } = { claimed: false },+ skillAuthoringClaim: RoomSkillsClaim = { claimed: false },orchestration?: GroupTurnOrchestration,operation?: GroupTurnOperation,// Rebuild the turn once from the fresh bot rather than mix a stale adapter with fresh permissions.@@ -9593,8 +9593,7 @@ async function runClaimedGroupMemberTurn(const integrations: NonNullable<Parameters<typeof instance.adapter.sendTurn>[0]["integrations"]> = {};const skillAuthoring =skillAuthoringEnabled(cfg) &&- hop === 0 &&- !skillAuthoringClaim.claimed &&+ roomTurnMayWriteSkills(skillAuthoringClaim, hop, bot.id) &&!cardContinuation &&instance.adapter.capabilities.agentsMcp === true;if (instance.adapter.capabilities.agentsMcp === true) {@@ -10039,7 +10038,7 @@ async function runClaimedGroupMemberTurn(], integrations.agents, { rules: cfg.everyBotRules, pagesOff: (store.bot(bot.id) ?? bot).toolsOff?.includes("pages") });// Claim /learn only after setup succeeded, so a failed first responder does not consume it.- if (skillAuthoring) skillAuthoringClaim.claimed = true;+ if (skillAuthoring) takeRoomSkills(skillAuthoringClaim, hop, bot.id, true);// Never launch a replacement into a stopped handshake's pre-id window.await pendingCancelledProviderHandshakes.waitForClear(threadId);const heldBeforeDispatch = roomHeld(store.group(group.id), bot.id);@@ -10289,7 +10288,7 @@ async function runClaimedGroupMemberTurn(store.setActivity(bot.id, "idle");}if (outcome === "dispatch_failed") {- if (skillAuthoring) skillAuthoringClaim.claimed = false;+ if (skillAuthoring) takeRoomSkills(skillAuthoringClaim, hop, bot.id, false);// No turn.completed follows a rejected room dispatch: retry what queued meanwhile.drainQueuedSends();}@@ -10301,7 +10300,7 @@ async function runClaimedGroupMemberTurn(return true;}if (outcome === "provider_failed" || outcome === "parked") {- if (skillAuthoring) skillAuthoringClaim.claimed = false;+ if (skillAuthoring) takeRoomSkills(skillAuthoringClaim, hop, bot.id, false);return false;}const resent = orchestration || cardContinuation || oneTimeInputTaken || outcome !== "settled" || isCancelled?.() ? undefined : await roomLimits.resendOnce(threadId, bot, preparedApprovalMode, turnCompleted, roomSpeaker?.since ?? 0,@@ -10385,6 +10384,7 @@ async function runClaimedGroupMemberTurn(if (verdict === "skip") { noteGroupTurn(spoken, next.id); continue; }}if (providerTurnId) usageTrace.expect(threadId, { parent: { threadId, turnId: providerTurnId } });+ if (skillAuthoring && hop === 0) handRoomSkills(skillAuthoringClaim, next.id);if (!(await runGroupMemberTurn(groupId,threadId,@@ -10456,7 +10456,7 @@ async function runGroupGoalStep(args: {threadId: string;bot: BotRecord;operation: GroupTurnOperation;- skillAuthoringClaim: { claimed: boolean };+ skillAuthoringClaim: RoomSkillsClaim;coordinator: boolean;instructions: string;}): Promise<{ ran: boolean; replyText: string; outcome?: GroupMemberTurnOutcome; stopReason?: string | null }> {