Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(server): add durable bot management tools (#90)
Leo2de791e93018
diff --git a/apps/server/src/provider/AkeruDelegationRuntime.ts b/apps/server/src/provider/AkeruDelegationRuntime.tsindex c4d1dc5cc..1adf51024 100644--- a/apps/server/src/provider/AkeruDelegationRuntime.ts+++ b/apps/server/src/provider/AkeruDelegationRuntime.ts@@ -209,6 +209,109 @@ export function createAkeruDelegationRuntime(options: AkeruDelegationRuntimeOpti});};+ const availableBot = (+ snapshot: OrchestrationReadModel,+ parent: AkeruDelegationParent,+ botId: BotId,+ ) => {+ const parentThread = snapshot.threads.find((thread) => thread.id === parent.threadId);+ const bot = snapshot.bots.find((candidate) => candidate.id === botId);+ if (!parentThread || !bot || bot.archivedAt !== null) {+ throw new Error("The target bot is not available in this workspace.");+ }+ if (parentThread.groupId !== null && bot.groupId !== parentThread.groupId) {+ throw new Error("The target bot is not available in the current group.");+ }+ return { parentThread, bot };+ };++ const create = async (+ parent: AkeruDelegationParent,+ request: (typeof AkeruToolInputSchemas.CreateAgent)["Type"],+ ) => {+ const snapshot = await options.readSnapshot();+ const { parentThread, bot: parentBot } = availableBot(snapshot, parent, parent.botId);+ if (+ snapshot.bots.some(+ (candidate) =>+ candidate.archivedAt === null &&+ candidate.name.localeCompare(request.name, undefined, { sensitivity: "accent" }) === 0,+ )+ ) {+ throw new Error(`A bot named '${request.name}' already exists.`);+ }+ const botId = BotId.make(`bot-${id()}`);+ await dispatch({+ type: "bot.create",+ commandId: commandId("bot-create"),+ botId,+ name: request.name,+ title: request.title ?? "Assistant",+ label: null,+ description: request.description ?? null,+ disabledMcpServerIds: parentBot.disabledMcpServerIds,+ avatar: { kind: "dither", seed: String(botId) },+ engine: parentBot.engine,+ sandbox: parentBot.sandbox,+ runtimeMode: parent.access.runtimeMode,+ usageCap: null,+ voiceEnabled: false,+ groupId: parentThread.groupId ?? null,+ createdAt: now(),+ });+ return { botId, name: request.name };+ };++ const check = async (+ parent: AkeruDelegationParent,+ request: (typeof AkeruToolInputSchemas.CheckAgent)["Type"],+ ) => {+ const snapshot = await options.readSnapshot();+ const { bot } = availableBot(snapshot, parent, request.botId);+ return {+ botId: bot.id,+ name: bot.name,+ title: bot.title,+ delegations: snapshot.delegations+ .filter(+ (delegation) =>+ delegation.parentThreadId === parent.threadId && delegation.childBotId === bot.id,+ )+ .map((delegation) => ({+ delegationId: delegation.delegationId,+ state: delegation.state,+ childThreadId: delegation.childThreadId,+ result: delegation.result,+ failure: delegation.failure,+ })),+ };+ };++ const stop = async (+ parent: AkeruDelegationParent,+ request: (typeof AkeruToolInputSchemas.StopAgent)["Type"],+ ) => {+ const snapshot = await options.readSnapshot();+ availableBot(snapshot, parent, request.botId);+ const active = snapshot.delegations.filter(+ (delegation) =>+ delegation.parentThreadId === parent.threadId &&+ delegation.childBotId === request.botId &&+ !TERMINAL_STATES.has(delegation.state),+ );+ if (active.length === 0) throw new Error("The target bot has no active delegated work.");+ for (const delegation of active) {+ await dispatch({+ type: "delegation.cancel",+ commandId: commandId("stop"),+ delegationId: delegation.delegationId,+ keep: false,+ createdAt: now(),+ });+ }+ return { botId: request.botId, stopped: active.map((entry) => entry.delegationId) };+ };+const fail = async (delegation: AkeruDelegationRecord,failureCode: AkeruDelegationFailureCode,@@ -479,7 +582,10 @@ export function createAkeruDelegationRuntime(options: AkeruDelegationRuntimeOpti};return {+ create,+ check,send,+ stop,sendToUser,parentFinished,readSnapshot: options.readSnapshot,diff --git a/apps/server/src/provider/AkeruToolRuntime.test.ts b/apps/server/src/provider/AkeruToolRuntime.test.tsindex 148762e53..b43c063eb 100644--- a/apps/server/src/provider/AkeruToolRuntime.test.ts+++ b/apps/server/src/provider/AkeruToolRuntime.test.ts@@ -142,6 +142,147 @@ describe("AkeruToolRuntime", () => {expect(send).toHaveBeenCalledOnce();});+ it("runs typed durable bot controls through the delegation backend", async () => {+ const create = vi.fn(async () => ({ botId: "bot-research" }));+ const check = vi.fn(async () => ({ state: "ready" }));+ const send = vi.fn(async () => ({ delivered: true }));+ const stop = vi.fn(async () => ({ stopped: true }));+ const runtime = createAkeruToolRuntime();+ runtime.registerSession("thread-controls", {+ runtimeMode: "full-access",+ workspaceType: "local",+ delegation: {+ depth: 0,+ activeDelegations: 0,+ access: {+ allowedToolIds: ["CreateAgent", "CheckAgent", "MessageAgent", "StopAgent"],+ memoryScopes: [],+ sandbox: "local",+ runtimeMode: "full-access",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "delete",+ },+ create,+ check,+ send,+ stop,+ },+ });++ const execute = (toolId: "CreateAgent" | "CheckAgent", input: unknown) =>+ runtime.execute({+ threadId: "thread-controls",+ toolId,+ toolCallId: `tool-${toolId}`,+ input,+ approvalMode: "require-grant",+ });+ await expect(execute("CreateAgent", { name: "Research" })).resolves.toEqual({+ botId: "bot-research",+ });+ await expect(execute("CheckAgent", { botId: "bot-research" })).resolves.toEqual({+ state: "ready",+ });++ for (const execution of [+ {+ threadId: "thread-controls",+ toolId: "MessageAgent" as const,+ toolCallId: "tool-message",+ input: {+ botId: BotId.make("bot-research"),+ task: "Compare flights.",+ expectedResult: "Return a short comparison.",+ },+ approvalMode: "require-grant" as const,+ },+ {+ threadId: "thread-controls",+ toolId: "StopAgent" as const,+ toolCallId: "tool-stop",+ input: { botId: BotId.make("bot-research") },+ approvalMode: "require-grant" as const,+ },+ ]) {+ await expect(runtime.execute(execution)).rejects.toThrow("requires approval");+ runtime.grantApproval(execution);+ await expect(runtime.execute(execution)).resolves.toBeDefined();+ }+ expect(send).toHaveBeenCalledOnce();+ expect(stop).toHaveBeenCalledOnce();+ });++ it("returns nonfatal receipts when durable bot controls fail", async () => {+ const fail = vi.fn(async () => {+ throw new Error("Bot backend unavailable.");+ });+ const receipts: AkeruToolReceipt[] = [];+ const runtime = createAkeruToolRuntime({ onReceipt: (receipt) => receipts.push(receipt) });+ runtime.registerSession("thread-control-failures", {+ botId: BotId.make("bot-parent"),+ runtimeMode: "full-access",+ workspaceType: "local",+ delegation: {+ depth: 0,+ activeDelegations: 0,+ access: {+ allowedToolIds: ["CreateAgent", "CheckAgent", "StopAgent"],+ memoryScopes: [],+ sandbox: "local",+ runtimeMode: "full-access",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "delete",+ },+ create: fail,+ check: fail,+ send: vi.fn(),+ stop: fail,+ },+ });++ for (const execution of [+ {+ threadId: "thread-control-failures",+ toolId: "CreateAgent" as const,+ toolCallId: "create-failure",+ input: { name: "Research" },+ approvalMode: "require-grant" as const,+ },+ {+ threadId: "thread-control-failures",+ toolId: "CheckAgent" as const,+ toolCallId: "check-failure",+ input: { botId: BotId.make("bot-research") },+ approvalMode: "require-grant" as const,+ },+ {+ threadId: "thread-control-failures",+ toolId: "StopAgent" as const,+ toolCallId: "stop-failure",+ input: { botId: BotId.make("bot-research") },+ approvalMode: "require-grant" as const,+ },+ ]) {+ if (execution.toolId === "StopAgent") runtime.grantApproval(execution);+ receipts.length = 0;+ await expect(runtime.execute(execution)).resolves.toMatchObject({+ receiptId: execution.toolCallId,+ toolId: execution.toolId,+ phase: "failure",+ threadId: "thread-control-failures",+ botId: "bot-parent",+ summary: "Bot backend unavailable.",+ failureCode: "internal",+ fatalToThread: false,+ });+ expect(receipts.map((receipt) => receipt.phase)).toEqual(["start", "failure"]);+ }+ });+it("exposes registered memory handlers and protects sensitive writes", async () => {const remember = vi.fn(async () => ({ saved: true }));const unavailable = vi.fn(async () => undefined);diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.tsindex ca1a64724..4f3a6edbf 100644--- a/apps/server/src/provider/AkeruToolRuntime.ts+++ b/apps/server/src/provider/AkeruToolRuntime.ts@@ -68,7 +68,12 @@ export interface AkeruToolSession {readonly depth: number;readonly activeDelegations: number;readonly access: AkeruDelegationAccessGrant;+ readonly create?: (+ input: (typeof AkeruToolInputSchemas.CreateAgent)["Type"],+ ) => Promise<unknown>;+ readonly check?: (input: (typeof AkeruToolInputSchemas.CheckAgent)["Type"]) => Promise<unknown>;readonly send: (input: (typeof AkeruToolInputSchemas.SendToAgent)["Type"]) => Promise<unknown>;+ readonly stop?: (input: (typeof AkeruToolInputSchemas.StopAgent)["Type"]) => Promise<unknown>;};readonly channels?: {readonly create: (@@ -125,6 +130,10 @@ const BACKEND_NAMES: Record<| "CopyToBox"| "CopyFromBox"| "request_box_help"+ | "CreateAgent"+ | "CheckAgent"+ | "MessageAgent"+ | "StopAgent"| "SendToAgent"| "CreateChannel"| "UpdateChannel"@@ -346,7 +355,13 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeruif (options?.onUserActionRequired && session.workspace && session.botId && session.botName) {tools.add("request_box_help");}- if (session.delegation) tools.add("SendToAgent");+ if (session.delegation) {+ if (session.delegation.create) tools.add("CreateAgent");+ if (session.delegation.check) tools.add("CheckAgent");+ tools.add("MessageAgent");+ if (session.delegation.stop) tools.add("StopAgent");+ tools.add("SendToAgent");+ }if (session.channels) {tools.add("CreateChannel");tools.add("UpdateChannel");@@ -502,9 +517,12 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akerusummary,}),});- } else if (input.toolId === "SendToAgent") {+ } else if (input.toolId === "SendToAgent" || input.toolId === "MessageAgent") {if (!session.delegation) throw new Error("Delegation is not available for this session.");- const delegationInput = decodeAkeruToolInput("SendToAgent", decoded);+ const delegationInput =+ input.toolId === "MessageAgent"+ ? decodeAkeruToolInput("MessageAgent", decoded)+ : decodeAkeruToolInput("SendToAgent", decoded);failureCode = "internal";try {result = await session.delegation.send(delegationInput);@@ -525,6 +543,50 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): AkeruemitReceipt(input, "failure", { failureCode, summary });return result;}+ } else if (+ input.toolId === "CreateAgent" ||+ input.toolId === "CheckAgent" ||+ input.toolId === "StopAgent"+ ) {+ if (!session.delegation) {+ throw new Error("Bot management is not available for this session.");+ }+ failureCode = "internal";+ let billedBotId = session.botId;+ try {+ if (input.toolId === "CreateAgent") {+ if (!session.delegation.create) throw new Error("Bot creation is not available.");+ result = await session.delegation.create(+ decodeAkeruToolInput("CreateAgent", decoded),+ );+ } else if (input.toolId === "CheckAgent") {+ if (!session.delegation.check) throw new Error("Bot inspection is not available.");+ const checkInput = decodeAkeruToolInput("CheckAgent", decoded);+ billedBotId = checkInput.botId;+ result = await session.delegation.check(checkInput);+ } else {+ if (!session.delegation.stop) throw new Error("Bot cancellation is not available.");+ const stopInput = decodeAkeruToolInput("StopAgent", decoded);+ billedBotId = stopInput.botId;+ result = await session.delegation.stop(stopInput);+ }+ } catch (cause) {+ const summary = cause instanceof Error ? cause.message : String(cause);+ result = {+ receiptId: input.toolCallId,+ toolId: input.toolId,+ phase: "failure",+ threadId: ThreadId.make(input.threadId),+ botId: session.botId,+ summary,+ failureCode,+ fatalToThread: false,+ ...(billedBotId ? { billedBotId } : {}),+ createdAt: options?.now?.() ?? DateTime.formatIso(DateTime.nowUnsafe()),+ } satisfies AkeruToolReceipt;+ emitReceipt(input, "failure", { failureCode, summary });+ return result;+ }} else if (input.toolId === "CreateChannel" || input.toolId === "UpdateChannel") {if (!session.channels || !session.botId) {throw new Error("Channel management is not available for this session.");diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 178e1d935..27f7f7589 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -173,7 +173,8 @@ export interface AgentControllerLiveOptions {readonly delegationRuntime?: Pick<AkeruDelegationRuntime,"send" | "sendToUser" | "parentFinished" | "accessForThread"- >;+ > &+ Partial<Pick<AkeruDelegationRuntime, "create" | "check" | "stop">>;}export function createAkeruMastraAuthStorage(secretsDir: string): AuthStorage {@@ -525,6 +526,9 @@ const make = (options?: AgentControllerLiveOptions) =>access: input.access,};};+ const createAgent = delegationRuntime?.create;+ const checkAgent = delegationRuntime?.check;+ const stopAgent = delegationRuntime?.stop;return {depth: input.parentDelegation?.depth ?? 0,activeDelegations:@@ -536,7 +540,10 @@ const make = (options?: AgentControllerLiveOptions) =>candidate.state !== "canceled",).length ?? 0,access: input.access,+ ...(createAgent ? { create: (request) => createAgent(parent(), request) } : {}),+ ...(checkAgent ? { check: (request) => checkAgent(parent(), request) } : {}),send: (request) => delegationRuntime!.send(parent(), request),+ ...(stopAgent ? { stop: (request) => stopAgent(parent(), request) } : {}),};};const makeMastraHarness = options?.makeMastraHarness ?? createAkeruMastraHarness;diff --git a/packages/contracts/src/akeruTools.test.ts b/packages/contracts/src/akeruTools.test.tsindex 7be4965a0..0377a8221 100644--- a/packages/contracts/src/akeruTools.test.ts+++ b/packages/contracts/src/akeruTools.test.ts@@ -100,6 +100,20 @@ describe("Akeru tool contracts", () => {expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "SendToAgent")?.approval).toBe("send");});+ it("types durable bot management without bypassing send or cancellation approval", () => {+ expect(decodeAkeruToolInput("CreateAgent", { name: "Research" })).toEqual({+ name: "Research",+ });+ expect(decodeAkeruToolInput("CheckAgent", { botId: "bot-research" })).toEqual({+ botId: "bot-research",+ });+ expect(decodeAkeruToolInput("StopAgent", { botId: "bot-research" })).toEqual({+ botId: "bot-research",+ });+ expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "MessageAgent")?.approval).toBe("send");+ expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "StopAgent")?.approval).toBe("delete");+ });+it("decodes SendToUser input and keeps it approval-gated", () => {expect(decodeAkeruToolInput("SendToUser", { message: "The export is ready." })).toEqual({message: "The export is ready.",diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.tsindex 422ca4196..683f5345d 100644--- a/packages/contracts/src/akeruTools.ts+++ b/packages/contracts/src/akeruTools.ts@@ -63,6 +63,10 @@ export const AkeruToolId = Schema.Literals(["ExternalRead","AwaitShell","AwaitExternalShell",+ "CreateAgent",+ "CheckAgent",+ "MessageAgent",+ "StopAgent","SendToAgent","CreateChannel","UpdateChannel",@@ -88,6 +92,21 @@ export const AkeruToolApprovalClass = Schema.Literals([]);export type AkeruToolApprovalClass = typeof AkeruToolApprovalClass.Type;+const AgentMessageInput = Schema.Struct({+ botId: BotId,+ task: TrimmedNonEmptyString,+ expectedResult: TrimmedNonEmptyString,+ deadline: Schema.optional(IsoDateTime),+ allowedToolIds: Schema.optional(Schema.Array(AkeruToolId)),+ memoryScopes: Schema.optional(Schema.Array(AkeruMemoryTargetScope)),+ mcpServerIds: Schema.optional(Schema.Array(McpServerId)),+ sandbox: Schema.optional(+ Schema.NullOr(Schema.suspend((): Schema.Codec<BotSandbox> => BotSandbox)),+ ),+ runtimeMode: Schema.optional(Schema.suspend((): Schema.Codec<RuntimeMode> => RuntimeMode)),+ approvalCeiling: Schema.optional(AkeruToolApprovalClass),+});+export const AkeruToolInputSchemas = {Shell: CommandInput,Read: PathInput,@@ -102,20 +121,15 @@ export const AkeruToolInputSchemas = {ExternalRead: PathInput,AwaitShell: Schema.Struct({ handleId: AkeruAwaitHandleId }),AwaitExternalShell: Schema.Struct({ handleId: AkeruAwaitHandleId }),- SendToAgent: Schema.Struct({- botId: BotId,- task: TrimmedNonEmptyString,- expectedResult: TrimmedNonEmptyString,- deadline: Schema.optional(IsoDateTime),- allowedToolIds: Schema.optional(Schema.Array(AkeruToolId)),- memoryScopes: Schema.optional(Schema.Array(AkeruMemoryTargetScope)),- mcpServerIds: Schema.optional(Schema.Array(McpServerId)),- sandbox: Schema.optional(- Schema.NullOr(Schema.suspend((): Schema.Codec<BotSandbox> => BotSandbox)),- ),- runtimeMode: Schema.optional(Schema.suspend((): Schema.Codec<RuntimeMode> => RuntimeMode)),- approvalCeiling: Schema.optional(AkeruToolApprovalClass),+ CreateAgent: Schema.Struct({+ name: TrimmedNonEmptyString,+ title: Schema.optional(TrimmedNonEmptyString),+ description: Schema.optional(TrimmedNonEmptyString),}),+ CheckAgent: Schema.Struct({ botId: BotId }),+ MessageAgent: AgentMessageInput,+ StopAgent: Schema.Struct({ botId: BotId }),+ SendToAgent: AgentMessageInput,CreateChannel: Schema.Struct({name: TrimmedNonEmptyString,specialistBotIds: Schema.optional(Schema.Array(BotId)),@@ -256,6 +270,14 @@ export const AKERU_TOOL_CATALOG = [workspace: "user-computer",requiresUserComputer: true,}),+ define("CreateAgent", "bot-workspace", "Create a durable named bot."),+ define("CheckAgent", "bot-workspace", "Inspect a durable named bot and its delegated work."),+ define("MessageAgent", "bot-workspace", "Send bounded work to a durable named bot.", {+ approval: "send",+ }),+ define("StopAgent", "bot-workspace", "Cancel a durable bot's delegated work.", {+ approval: "delete",+ }),define("SendToAgent", "bot-workspace", "Delegate a task to another bot.", {approval: "send",}),@@ -302,7 +324,7 @@ export function filterAkeruTools(if (!context.capabilities.has(tool.capability)) return false;if (!context.implementedTools.has(tool.id)) return false;if (- tool.id === "SendToAgent" &&+ (tool.id === "SendToAgent" || tool.id === "MessageAgent") &&((context.delegationDepth ?? 0) >= AKERU_DELEGATION_MAX_DEPTH ||(context.activeDelegations ?? 0) >= AKERU_DELEGATION_MAX_CONCURRENCY))