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 bot bosses manage channels (#74)
Leo66c2e24c4f60
diff --git a/apps/server/src/provider/AkeruChannelRuntime.test.ts b/apps/server/src/provider/AkeruChannelRuntime.test.tsnew file mode 100644index 000000000..14a1bf727--- /dev/null+++ b/apps/server/src/provider/AkeruChannelRuntime.test.ts@@ -0,0 +1,102 @@+import { BotId, GroupId, type OrchestrationReadModel } from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";++import { createAkeruChannelRuntime } from "./AkeruChannelRuntime.ts";++const now = "2026-09-01T00:00:00.000Z";+const bossBotId = BotId.make("boss");+const specialistBotId = BotId.make("specialist");+const channelId = GroupId.make("channel-1");++const bot = (id: BotId, groupId: GroupId | null) => ({+ id,+ name: id,+ title: id,+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "dither" as const, seed: id },+ engine: null,+ sandbox: "local" as const,+ runtimeMode: "approval-required" as const,+ usageCap: null,+ voiceEnabled: false,+ groupId,+ archivedAt: null,+ createdAt: now,+ updatedAt: now,+});++const snapshot: OrchestrationReadModel = {+ snapshotSequence: 0,+ projects: [],+ bots: [bot(bossBotId, channelId), bot(specialistBotId, channelId)],+ groups: [+ {+ id: channelId,+ name: "Launch",+ bossBotId,+ members: [+ { botId: bossBotId, role: "boss" },+ { botId: specialistBotId, role: "specialist" },+ ],+ createdAt: now,+ updatedAt: now,+ },+ ],+ delegations: [],+ threads: [],+ updatedAt: now,+};++describe("AkeruChannelRuntime", () => {+ it("creates a persisted group with the calling bot as boss", async () => {+ const dispatch = vi.fn();+ const runtime = createAkeruChannelRuntime({+ readSnapshot: async () => ({ ...snapshot, groups: [], bots: [bot(bossBotId, null)] }),+ dispatch,+ now: () => now,+ id: () => "1",+ });++ await expect(runtime.create(bossBotId, { name: "Research" })).resolves.toBe("channel-1");+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "group.create",+ groupId: "channel-1",+ name: "Research",+ bossBotId,+ }),+ );+ });++ it("lets the existing boss rename a channel", async () => {+ const dispatch = vi.fn();+ const runtime = createAkeruChannelRuntime({+ readSnapshot: async () => snapshot,+ dispatch,+ id: () => "1",+ });++ await runtime.update(bossBotId, { channelId, name: "Launch room" });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ type: "group.rename", groupId: channelId, name: "Launch room" }),+ );+ });++ it("rejects updates from specialists and missing channels", async () => {+ const dispatch = vi.fn();+ const runtime = createAkeruChannelRuntime({+ readSnapshot: async () => snapshot,+ dispatch,+ });++ await expect(runtime.update(specialistBotId, { channelId, name: "Hijacked" })).rejects.toThrow(+ "Only the channel boss",+ );+ await expect(+ runtime.update(bossBotId, { channelId: GroupId.make("missing"), name: "Missing" }),+ ).rejects.toThrow("does not exist");+ expect(dispatch).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/provider/AkeruChannelRuntime.ts b/apps/server/src/provider/AkeruChannelRuntime.tsnew file mode 100644index 000000000..90b1ed2f2--- /dev/null+++ b/apps/server/src/provider/AkeruChannelRuntime.ts@@ -0,0 +1,67 @@+// @effect-diagnostics globalDate:off globalRandom:off nodeBuiltinImport:off+import * as NodeCrypto from "node:crypto";++import {+ BotId,+ CommandId,+ GroupId,+ type AkeruToolInputSchemas,+ type OrchestrationCommand,+ type OrchestrationReadModel,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";++export interface AkeruChannelRuntimeOptions {+ readonly readSnapshot: () => Promise<OrchestrationReadModel>;+ readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;+ readonly now?: () => string;+ readonly id?: () => string;+}++export function createAkeruChannelRuntime(options: AkeruChannelRuntimeOptions) {+ const now = options.now ?? (() => DateTime.formatIso(DateTime.nowUnsafe()));+ const id = options.id ?? (() => NodeCrypto.randomUUID());++ const create = async (+ bossBotId: BotId,+ input: (typeof AkeruToolInputSchemas.CreateChannel)["Type"],+ ) => {+ const snapshot = await options.readSnapshot();+ const boss = snapshot.bots.find((bot) => bot.id === bossBotId && bot.archivedAt === null);+ if (!boss) throw new Error("The channel boss bot is not available.");++ const channelId = GroupId.make(`channel-${id()}`);+ await options.dispatch({+ type: "group.create",+ commandId: CommandId.make(`channel:create:${id()}`),+ groupId: channelId,+ name: input.name,+ bossBotId,+ specialistBotIds: input.specialistBotIds,+ createdAt: now(),+ });+ return channelId;+ };++ const update = async (+ botId: BotId,+ input: (typeof AkeruToolInputSchemas.UpdateChannel)["Type"],+ ) => {+ const snapshot = await options.readSnapshot();+ const channel = snapshot.groups.find((group) => group.id === input.channelId);+ if (!channel) throw new Error("The channel does not exist.");+ if (channel.bossBotId !== botId) throw new Error("Only the channel boss can update it.");++ await options.dispatch({+ type: "group.rename",+ commandId: CommandId.make(`channel:update:${id()}`),+ groupId: input.channelId,+ name: input.name,+ });+ return input.channelId;+ };++ return { create, update };+}++export type AkeruChannelRuntime = ReturnType<typeof createAkeruChannelRuntime>;diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.tsindex f469faa76..3fa07edf5 100644--- a/apps/server/src/provider/AkeruToolRuntime.ts+++ b/apps/server/src/provider/AkeruToolRuntime.ts@@ -62,6 +62,14 @@ export interface AkeruToolSession {input: (typeof AkeruToolInputSchemas.SendToAgent)["Type"],) => Promise<AkeruToolReceipt>;};+ readonly channels?: {+ readonly create: (+ input: (typeof AkeruToolInputSchemas.CreateChannel)["Type"],+ ) => Promise<string>;+ readonly update: (+ input: (typeof AkeruToolInputSchemas.UpdateChannel)["Type"],+ ) => Promise<string>;+ };}export interface AkeruToolRuntimeOptions {@@ -92,7 +100,15 @@ export interface AkeruToolRuntime {}const BACKEND_NAMES: Record<- Exclude<AkeruToolId, "CopyToBox" | "CopyFromBox" | "request_box_help" | "SendToAgent">,+ Exclude<+ AkeruToolId,+ | "CopyToBox"+ | "CopyFromBox"+ | "request_box_help"+ | "SendToAgent"+ | "CreateChannel"+ | "UpdateChannel"+ >,ReadonlyArray<string>> = {Shell: ["execute_command", "mastra_workspace_execute_command"],@@ -186,6 +202,10 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akerutools.add("request_box_help");}if (session.delegation) tools.add("SendToAgent");+ if (session.channels) {+ tools.add("CreateChannel");+ tools.add("UpdateChannel");+ }return tools;};@@ -310,6 +330,42 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeru}}+ if (input.toolId === "CreateChannel" || input.toolId === "UpdateChannel") {+ if (!session.channels || !session.botId) {+ throw new Error("Channel management is not available for this session.");+ }+ try {+ const channelId =+ input.toolId === "CreateChannel"+ ? await session.channels.create(decodeAkeruToolInput("CreateChannel", decoded))+ : await session.channels.update(decodeAkeruToolInput("UpdateChannel", decoded));+ return {+ receiptId: input.toolCallId,+ toolId: input.toolId,+ phase: "success",+ threadId: ThreadId.make(input.threadId),+ botId: session.botId,+ summary: `Channel '${channelId}' saved.`,+ fatalToThread: false,+ billedBotId: session.botId,+ createdAt: options?.now?.() ?? DateTime.formatIso(DateTime.nowUnsafe()),+ } satisfies AkeruToolReceipt;+ } catch (cause) {+ return {+ receiptId: input.toolCallId,+ toolId: input.toolId,+ phase: "failure",+ threadId: ThreadId.make(input.threadId),+ botId: session.botId,+ summary: cause instanceof Error ? cause.message : String(cause),+ failureCode: "internal",+ fatalToThread: false,+ billedBotId: session.botId,+ createdAt: options?.now?.() ?? DateTime.formatIso(DateTime.nowUnsafe()),+ } satisfies AkeruToolReceipt;+ }+ }+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 de9abf749..f716fa803 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -62,6 +62,7 @@ import {type AkeruMastraSession,} from "../AkeruMastraHarness.ts";import { AKERU_BOT_TURN_INSTRUCTIONS } from "../AkeruAgentInstructions.ts";+import { createAkeruChannelRuntime, type AkeruChannelRuntime } from "../AkeruChannelRuntime.ts";import {createAkeruDelegationRuntime,type AkeruDelegationChildOutcome,@@ -315,6 +316,7 @@ const make = (options?: AgentControllerLiveOptions) =>const resolvedByThread = new Map<string, ResolvedEngine>();const sessions = new Map<string, ActiveSession>();let delegationRuntime: AkeruDelegationRuntime | undefined;+ let channelRuntime: AkeruChannelRuntime | undefined;const childWaiters = new Map<string,{ readonly resolve: (outcome: AkeruDelegationChildOutcome) => void }@@ -943,6 +945,14 @@ const make = (options?: AgentControllerLiveOptions) =>},}: {}),+ ...(input.botId && channelRuntime+ ? {+ channels: {+ create: (request) => channelRuntime!.create(input.botId!, request),+ update: (request) => channelRuntime!.update(input.botId!, request),+ },+ }+ : {}),};toolRuntime.registerSession(key, toolSession);const session = yield* runMastra("createSession", () =>@@ -1320,6 +1330,7 @@ const make = (options?: AgentControllerLiveOptions) =>return AgentController.of({configureDelegation: (input) =>Effect.sync(() => {+ channelRuntime = createAkeruChannelRuntime(input);delegationRuntime = createAkeruDelegationRuntime({...input,failChild: (threadId, error) => resolveChildWaiter(threadId, { turnId: null, error }),diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.tsindex b15db64cf..fe5b1cb85 100644--- a/packages/contracts/src/akeruTools.ts+++ b/packages/contracts/src/akeruTools.ts@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";import {BotId,+ GroupId,IsoDateTime,NonNegativeInt,ThreadId,@@ -47,6 +48,14 @@ export const AkeruToolInputSchemas = {task: TrimmedNonEmptyString,expectedResult: TrimmedNonEmptyString,}),+ CreateChannel: Schema.Struct({+ name: TrimmedNonEmptyString,+ specialistBotIds: Schema.optional(Schema.Array(BotId)),+ }),+ UpdateChannel: Schema.Struct({+ channelId: GroupId,+ name: TrimmedNonEmptyString,+ }),} as const;export type AkeruToolId = keyof typeof AkeruToolInputSchemas;@@ -178,6 +187,8 @@ export const AKERU_TOOL_CATALOG = [define("SendToAgent", "bot-workspace", "Delegate a task to another bot.", {approval: "send",}),+ define("CreateChannel", "bot-workspace", "Create a bot channel."),+ define("UpdateChannel", "bot-workspace", "Rename a bot channel."),] satisfies ReadonlyArray<AkeruToolDefinition>;export interface AkeruToolAvailabilityContext {