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): let bots update their own profiles (#87)
Leo8bc2a3604dce
diff --git a/apps/server/src/provider/AkeruBotStateRuntime.test.ts b/apps/server/src/provider/AkeruBotStateRuntime.test.tsnew file mode 100644index 000000000..ca8f97e64--- /dev/null+++ b/apps/server/src/provider/AkeruBotStateRuntime.test.ts@@ -0,0 +1,116 @@+import { BotId, ThreadId, type OrchestrationCommand } from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";++import { createEmptyReadModel } from "../orchestration/projector.ts";+import { createAkeruBotStateRuntime } from "./AkeruBotStateRuntime.ts";++const now = "2026-09-01T02:00:00.000Z";+const botId = BotId.make("bot-self");+const otherBotId = BotId.make("bot-other");++function snapshot(archivedAt: string | null = null) {+ return {+ ...createEmptyReadModel(now),+ bots: [+ {+ id: botId,+ name: "Researcher",+ title: "Research bot",+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "dither" as const, seed: "researcher" },+ engine: null,+ sandbox: "local" as const,+ runtimeMode: "approval-required" as const,+ usageCap: null,+ voiceEnabled: false,+ groupId: null,+ archivedAt,+ createdAt: now,+ updatedAt: now,+ },+ {+ id: otherBotId,+ name: "Other",+ title: "Other bot",+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "dither" as const, seed: "other" },+ engine: null,+ sandbox: "local" as const,+ runtimeMode: "approval-required" as const,+ usageCap: null,+ voiceEnabled: false,+ groupId: null,+ archivedAt: null,+ createdAt: now,+ updatedAt: now,+ },+ ],+ };+}++describe("AkeruBotStateRuntime", () => {+ it("updates only the session bot and returns an event-backed receipt", async () => {+ const commands: OrchestrationCommand[] = [];+ const runtime = createAkeruBotStateRuntime({+ readSnapshot: async () => snapshot(),+ dispatch: async (command) => {+ commands.push(command);+ return { sequence: 42 };+ },+ now: () => now,+ id: () => "command-1",+ });++ await expect(+ runtime.updateProfile(ThreadId.make("thread-1"), botId, "tool-1", {+ name: "Source checker",+ label: null,+ }),+ ).resolves.toEqual({+ receiptId: "tool-1",+ toolId: "UpdateBotProfile",+ phase: "success",+ threadId: "thread-1",+ botId,+ summary: "Bot profile updated at event sequence 42.",+ fatalToThread: false,+ billedBotId: botId,+ createdAt: now,+ });+ expect(commands).toEqual([+ {+ type: "bot.update",+ commandId: "bot-state:profile:command-1",+ botId,+ name: "Source checker",+ label: null,+ },+ ]);+ });++ it("does not dispatch for a missing or archived session bot", async () => {+ const dispatch = vi.fn(async (_command: OrchestrationCommand) => ({ sequence: 1 }));+ const archived = createAkeruBotStateRuntime({+ readSnapshot: async () => snapshot(now),+ dispatch,+ });+ const missing = createAkeruBotStateRuntime({+ readSnapshot: async () => snapshot(),+ dispatch,+ });++ await expect(+ archived.updateProfile(ThreadId.make("thread-1"), botId, "tool-1", { title: "New" }),+ ).rejects.toThrow("not available");+ await expect(+ missing.updateProfile(ThreadId.make("thread-1"), BotId.make("missing"), "tool-2", {+ title: "New",+ }),+ ).rejects.toThrow("not available");+ expect(dispatch).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/provider/AkeruBotStateRuntime.ts b/apps/server/src/provider/AkeruBotStateRuntime.tsnew file mode 100644index 000000000..7902abeba--- /dev/null+++ b/apps/server/src/provider/AkeruBotStateRuntime.ts@@ -0,0 +1,59 @@+// @effect-diagnostics globalDate:off globalRandom:off nodeBuiltinImport:off+import * as NodeCrypto from "node:crypto";++import {+ CommandId,+ ThreadId,+ type AkeruToolInputSchemas,+ type AkeruToolReceipt,+ type BotId,+ type OrchestrationCommand,+ type OrchestrationReadModel,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";++export interface AkeruBotStateRuntimeOptions {+ readonly readSnapshot: () => Promise<OrchestrationReadModel>;+ readonly dispatch: (command: OrchestrationCommand) => Promise<{ readonly sequence: number }>;+ readonly now?: () => string;+ readonly id?: () => string;+}++export function createAkeruBotStateRuntime(options: AkeruBotStateRuntimeOptions) {+ const now = options.now ?? (() => DateTime.formatIso(DateTime.nowUnsafe()));+ const id = options.id ?? (() => NodeCrypto.randomUUID());++ const updateProfile = async (+ threadId: ThreadId,+ botId: BotId,+ toolCallId: string,+ input: (typeof AkeruToolInputSchemas.UpdateBotProfile)["Type"],+ ): Promise<AkeruToolReceipt> => {+ const snapshot = await options.readSnapshot();+ const bot = snapshot.bots.find((candidate) => candidate.id === botId);+ if (!bot || bot.archivedAt !== null) throw new Error("This bot is not available.");++ const createdAt = now();+ const result = await options.dispatch({+ type: "bot.update",+ commandId: CommandId.make(`bot-state:profile:${id()}`),+ botId,+ ...input,+ });+ return {+ receiptId: toolCallId,+ toolId: "UpdateBotProfile",+ phase: "success",+ threadId,+ botId,+ summary: `Bot profile updated at event sequence ${result.sequence}.`,+ fatalToThread: false,+ billedBotId: botId,+ createdAt,+ };+ };++ return { updateProfile };+}++export type AkeruBotStateRuntime = ReturnType<typeof createAkeruBotStateRuntime>;diff --git a/apps/server/src/provider/AkeruToolRuntime.test.ts b/apps/server/src/provider/AkeruToolRuntime.test.tsindex 076d1bc74..b5eb1a30a 100644--- a/apps/server/src/provider/AkeruToolRuntime.test.ts+++ b/apps/server/src/provider/AkeruToolRuntime.test.ts@@ -129,6 +129,60 @@ describe("AkeruToolRuntime", () => {expect(remember).toHaveBeenCalledTimes(2);});+ it("exposes a narrow profile tool only for a bot-owned session", async () => {+ const updateProfile = vi.fn(async () => ({+ receiptId: "profile-1",+ toolId: "UpdateBotProfile",+ phase: "success" as const,+ threadId: ThreadId.make("thread-profile"),+ botId: BotId.make("bot-one"),+ fatalToThread: false as const,+ createdAt: "2026-09-01T02:00:00.000Z",+ }));+ const runtime = createAkeruToolRuntime();+ runtime.registerSession("thread-no-bot", {+ runtimeMode: "full-access",+ workspaceType: "none",+ botState: { updateProfile },+ });+ runtime.registerSession("thread-profile", {+ botId: BotId.make("bot-one"),+ runtimeMode: "full-access",+ workspaceType: "none",+ botState: { updateProfile },+ });++ expect(runtime.toolsForThread("thread-no-bot").map((tool) => tool.id)).not.toContain(+ "UpdateBotProfile",+ );+ expect(runtime.toolsForThread("thread-profile").map((tool) => tool.id)).toEqual([+ "UpdateBotProfile",+ ]);+ await expect(+ runtime.execute({+ threadId: "thread-profile",+ toolId: "UpdateBotProfile",+ toolCallId: "profile-1",+ input: { title: "Principal researcher" },+ approvalMode: "require-grant",+ }),+ ).resolves.toMatchObject({ phase: "success" });+ expect(updateProfile).toHaveBeenCalledWith("thread-profile", "bot-one", "profile-1", {+ title: "Principal researcher",+ });++ await expect(+ runtime.execute({+ threadId: "thread-profile",+ toolId: "UpdateBotProfile",+ toolCallId: "profile-2",+ input: { title: "Principal researcher", botId: "bot-other" },+ approvalMode: "require-grant",+ }),+ ).rejects.toThrow();+ expect(updateProfile).toHaveBeenCalledTimes(1);+ });+it("requires an exact one-shot grant for local shell commands", async () => {const receipts: AkeruToolReceipt[] = [];const runtime = createAkeruToolRuntime({ onReceipt: (receipt) => receipts.push(receipt) });diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.tsindex 2b69a60fd..630d9f311 100644--- a/apps/server/src/provider/AkeruToolRuntime.ts+++ b/apps/server/src/provider/AkeruToolRuntime.ts@@ -25,6 +25,7 @@ import {type AkeruMemoryToolId,} from "../memory/MemoryToolHandlers.ts";import type { AkeruCatalogToolHandler } from "./AkeruCatalogToolHandlers.ts";+import type { AkeruBotStateRuntime } from "./AkeruBotStateRuntime.ts";export type AkeruRuntimeToolId = AkeruToolId | AkeruMemoryToolId;@@ -75,6 +76,7 @@ export interface AkeruToolSession {readonly sendToUser?: (input: (typeof AkeruToolInputSchemas.SendToUser)["Type"],) => Promise<AkeruToolReceipt>;+ readonly botState?: Pick<AkeruBotStateRuntime, "updateProfile">;readonly catalogHandlers?: Partial<Record<AkeruToolId, AkeruCatalogToolHandler>>;}@@ -122,6 +124,7 @@ const BACKEND_NAMES: Record<| "CreateChannel"| "UpdateChannel"| "SendToUser"+ | "UpdateBotProfile"| "InstallPlugin"| "AuthenticateMcpServer"| "RestartMcpServers"@@ -243,6 +246,7 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akerutools.add("UpdateChannel");}if (session.sendToUser) tools.add("SendToUser");+ if (session.botId && session.botState) tools.add("UpdateBotProfile");for (const toolId of Object.keys(session.catalogHandlers ?? {}) as AkeruToolId[]) {tools.add(toolId);}@@ -454,6 +458,35 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): AkeruemitReceipt(input, "failure", { failureCode, summary });return result;}+ } else if (input.toolId === "UpdateBotProfile") {+ if (!session.botId || !session.botState) {+ throw new Error("Bot profile management is not available for this session.");+ }+ failureCode = "internal";+ try {+ result = await session.botState.updateProfile(+ ThreadId.make(input.threadId),+ session.botId,+ input.toolCallId,+ decodeAkeruToolInput("UpdateBotProfile", decoded),+ );+ } 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: session.botId,+ createdAt: options?.now?.() ?? DateTime.formatIso(DateTime.nowUnsafe()),+ } satisfies AkeruToolReceipt;+ emitReceipt(input, "failure", { failureCode, summary });+ return result;+ }} else if (input.toolId === "CopyToBox" || input.toolId === "CopyFromBox") {const source =input.toolId === "CopyToBox" ? session.userComputerWorkspace : session.workspace;diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 8f77d003b..0c3c31cc3 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -67,6 +67,7 @@ import {} from "../AkeruMastraHarness.ts";import { AKERU_BOT_TURN_INSTRUCTIONS } from "../AkeruAgentInstructions.ts";import { createAkeruChannelRuntime, type AkeruChannelRuntime } from "../AkeruChannelRuntime.ts";+import { createAkeruBotStateRuntime, type AkeruBotStateRuntime } from "../AkeruBotStateRuntime.ts";import {createAkeruDelegationRuntime,type AkeruDelegationChildOutcome,@@ -348,6 +349,7 @@ const make = (options?: AgentControllerLiveOptions) =>let delegationRuntime: AkeruDelegationRuntime | undefined;let channelRuntime: AkeruChannelRuntime | undefined;let pluginRuntime: ReturnType<typeof createAkeruPluginRuntime> | undefined;+ let botStateRuntime: AkeruBotStateRuntime | undefined;const childWaiters = new Map<string,{ readonly resolve: (outcome: AkeruDelegationChildOutcome) => void }@@ -1003,6 +1005,7 @@ const make = (options?: AgentControllerLiveOptions) =>delete toolSession.botId;delete toolSession.botName;delete toolSession.memoryHandlers;+ delete toolSession.botState;const nextMemoryHandlers = memoryHandlers(input.memoryAccess);existing.toolSession = {...toolSession,@@ -1010,6 +1013,7 @@ const make = (options?: AgentControllerLiveOptions) =>...(input.botId ? { botId: input.botId } : {}),...(input.botName ? { botName: input.botName } : {}),...(nextMemoryHandlers ? { memoryHandlers: nextMemoryHandlers } : {}),+ ...(input.botId && botStateRuntime ? { botState: botStateRuntime } : {}),};toolRuntime.registerSession(key, existing.toolSession);return toProviderSession(threadId, existing);@@ -1084,6 +1088,7 @@ const make = (options?: AgentControllerLiveOptions) =>workspace: resources.botWorkspace,...(userComputerWorkspace ? { userComputerWorkspace } : {}),...(registeredMemoryHandlers ? { memoryHandlers: registeredMemoryHandlers } : {}),+ ...(input.botId && botStateRuntime ? { botState: botStateRuntime } : {}),catalogHandlers: createAkeruCatalogToolHandlers(sessionResources.getMcpManager(key),pluginRuntime,@@ -1549,6 +1554,7 @@ const make = (options?: AgentControllerLiveOptions) =>}),configureDelegation: (input) =>Effect.sync(() => {+ botStateRuntime = createAkeruBotStateRuntime(input);channelRuntime = createAkeruChannelRuntime(input);delegationRuntime = createAkeruDelegationRuntime({...input,diff --git a/apps/server/src/provider/Services/AgentController.ts b/apps/server/src/provider/Services/AgentController.tsindex 9354ee67d..d701178d8 100644--- a/apps/server/src/provider/Services/AgentController.ts+++ b/apps/server/src/provider/Services/AgentController.ts@@ -52,7 +52,7 @@ export interface AgentControllerShape {}) => Effect.Effect<void>;readonly configureDelegation?: (input: {readonly readSnapshot: () => Promise<OrchestrationReadModel>;- readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;+ readonly dispatch: (command: OrchestrationCommand) => Promise<{ readonly sequence: number }>;}) => Effect.Effect<void>;readonly failDelegation?: (input: {readonly threadId: ThreadId;diff --git a/packages/contracts/src/akeruTools.test.ts b/packages/contracts/src/akeruTools.test.tsindex 15e352276..fa8522775 100644--- a/packages/contracts/src/akeruTools.test.ts+++ b/packages/contracts/src/akeruTools.test.ts@@ -65,6 +65,33 @@ describe("Akeru tool contracts", () => {expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "SendToUser")?.approval).toBe("send");});+ it("decodes only narrow bot profile fields", () => {+ expect(+ decodeAkeruToolInput("UpdateBotProfile", {+ name: "Researcher",+ label: null,+ description: "Checks primary sources.",+ }),+ ).toEqual({+ name: "Researcher",+ label: null,+ description: "Checks primary sources.",+ });+ expect(() => decodeAkeruToolInput("UpdateBotProfile", {})).toThrow();+ expect(() =>+ decodeAkeruToolInput("UpdateBotProfile", {+ name: "Researcher",+ botId: "another-bot",+ }),+ ).toThrow();+ expect(() =>+ decodeAkeruToolInput("UpdateBotProfile", {+ name: "Researcher",+ groupId: "another-group",+ }),+ ).toThrow();+ });+it("never lets full access bypass protected commands or paths", () => {const shell = AKERU_TOOL_CATALOG.find((tool) => tool.id === "ExternalShell")!;const read = AKERU_TOOL_CATALOG.find((tool) => tool.id === "ExternalRead")!;diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.tsindex 5ccff794d..1b2b0f93d 100644--- a/packages/contracts/src/akeruTools.ts+++ b/packages/contracts/src/akeruTools.ts@@ -1,5 +1,6 @@import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";+import * as SchemaIssue from "effect/SchemaIssue";import {BotId,@@ -30,6 +31,22 @@ const CommandInput = Schema.Struct({const PathInput = Schema.Struct({ path: PathText });const CopyInput = Schema.Struct({ sourcePath: PathText, destinationPath: PathText });const McpServerIdInput = Schema.Struct({ serverId: TrimmedNonEmptyString });+const UpdateBotProfileInput = Schema.Struct({+ name: Schema.optional(TrimmedNonEmptyString),+ title: Schema.optional(TrimmedNonEmptyString),+ label: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),+ description: Schema.optional(Schema.NullOr(Schema.String)),+}).check(+ Schema.makeFilter(+ (input) =>+ input.name !== undefined ||+ input.title !== undefined ||+ input.label !== undefined ||+ input.description !== undefined ||+ new SchemaIssue.InvalidValue({ message: "At least one profile field is required." }),+ { identifier: "UpdateBotProfileInput" },+ ),+);export const AkeruToolInputSchemas = {Shell: CommandInput,@@ -67,6 +84,7 @@ export const AkeruToolInputSchemas = {url: McpServerUrl,authentication: Schema.Literals(["none", "oauth", "optional-oauth"]),}),+ UpdateBotProfile: UpdateBotProfileInput,AuthenticateMcpServer: McpServerIdInput,RestartMcpServers: Schema.Struct({serverIds: Schema.optional(Schema.Array(TrimmedNonEmptyString)),@@ -210,6 +228,7 @@ export const AKERU_TOOL_CATALOG = [define("InstallPlugin", "bot-workspace", "Install or update a URL MCP plugin.", {approval: "production",}),+ define("UpdateBotProfile", "bot-workspace", "Update this bot's public profile."),define("AuthenticateMcpServer", "bot-workspace", "Authenticate an MCP server.", {approval: "secrets",}),