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 message the current thread (#80)
Leo61c2129c4e09
diff --git a/apps/server/src/provider/AkeruDelegationRuntime.test.ts b/apps/server/src/provider/AkeruDelegationRuntime.test.tsindex bb4b2fea5..1fe396f55 100644--- a/apps/server/src/provider/AkeruDelegationRuntime.test.ts+++ b/apps/server/src/provider/AkeruDelegationRuntime.test.ts@@ -37,6 +37,12 @@ const targetBot: OrchestrationBot = {createdAt: now,updatedAt: now,};+const sourceBot: OrchestrationBot = {+ ...targetBot,+ id: sourceBotId,+ name: "Source",+ title: "Source",+};const sourceThread: OrchestrationThread = {id: sourceThreadId,@@ -67,7 +73,7 @@ const sourceThread: OrchestrationThread = {const snapshot: OrchestrationReadModel = {snapshotSequence: 0,projects: [],- bots: [targetBot],+ bots: [sourceBot, targetBot],groups: [],delegations: [],threads: [sourceThread],@@ -77,6 +83,75 @@ const snapshot: OrchestrationReadModel = {const request = { botId: targetBotId, task: "Review the patch", expectedResult: "A verdict" };describe("AkeruDelegationRuntime", () => {+ it("sends a bot message through the current thread assistant-message path", async () => {+ const commands: Array<{ type: string; [key: string]: unknown }> = [];+ const runtime = createAkeruDelegationRuntime({+ readSnapshot: async () => ({+ ...snapshot,+ threads: [+ {+ ...sourceThread,+ latestTurn: {+ turnId: sourceTurnId,+ state: "running",+ requestedAt: now,+ startedAt: now,+ completedAt: null,+ assistantMessageId: null,+ },+ },+ ],+ }),+ dispatch: async (command) => commands.push(command),+ awaitChild: vi.fn(),+ now: () => now,+ id: () => "1",+ });++ await expect(+ runtime.sendToUser(+ { threadId: sourceThreadId, turnId: sourceTurnId, botId: sourceBotId, depth: 0 },+ { message: "The export is ready." },+ ),+ ).resolves.toMatchObject({+ toolId: "SendToUser",+ phase: "success",+ threadId: sourceThreadId,+ botId: sourceBotId,+ fatalToThread: false,+ });+ expect(commands).toMatchObject([+ {+ type: "thread.message.assistant.delta",+ threadId: sourceThreadId,+ turnId: sourceTurnId,+ delta: "The export is ready.",+ },+ {+ type: "thread.message.assistant.complete",+ threadId: sourceThreadId,+ turnId: sourceTurnId,+ },+ ]);+ });++ it("rejects a bot that does not own the active thread", async () => {+ const dispatch = vi.fn();+ const runtime = createAkeruDelegationRuntime({+ readSnapshot: async () => snapshot,+ dispatch,+ awaitChild: vi.fn(),+ });++ await expect(+ runtime.sendToUser(+ { threadId: sourceThreadId, turnId: sourceTurnId, botId: targetBotId, depth: 0 },+ { message: "Wrong thread." },+ ),+ ).rejects.toThrow("not authorized");+ expect(dispatch).not.toHaveBeenCalled();+ });+it("enforces depth from the server-owned parent context", async () => {const dispatch = vi.fn();const runtime = createAkeruDelegationRuntime({diff --git a/apps/server/src/provider/AkeruDelegationRuntime.ts b/apps/server/src/provider/AkeruDelegationRuntime.tsindex b0bc2efaf..a90c636d0 100644--- a/apps/server/src/provider/AkeruDelegationRuntime.ts+++ b/apps/server/src/provider/AkeruDelegationRuntime.ts@@ -46,6 +46,58 @@ export function createAkeruDelegationRuntime(options: AkeruDelegationRuntimeOpticonst id = options.id ?? (() => NodeCrypto.randomUUID());const commandId = (label: string) => CommandId.make(`delegation:${label}:${id()}`);+ const sendToUser = async (+ parent: AkeruDelegationParent,+ request: (typeof AkeruToolInputSchemas.SendToUser)["Type"],+ ): Promise<AkeruToolReceipt> => {+ const snapshot = await options.readSnapshot();+ const sourceThread = snapshot.threads.find((thread) => thread.id === parent.threadId);+ const sourceBot = snapshot.bots.find((bot) => bot.id === parent.botId);+ if (+ !sourceThread ||+ sourceThread.deletedAt !== null ||+ sourceThread.archivedAt !== null ||+ !sourceBot ||+ sourceBot.archivedAt !== null ||+ (sourceThread.respondingBotId ?? sourceThread.botId) !== parent.botId ||+ sourceThread.latestTurn?.turnId !== parent.turnId ||+ sourceThread.latestTurn.state !== "running"+ ) {+ throw new Error("The source bot is not authorized for this active thread.");+ }++ const messageId = MessageId.make(`bot-message-${id()}`);+ const createdAt = now();+ await options.dispatch({+ type: "thread.message.assistant.delta",+ commandId: commandId("message"),+ threadId: parent.threadId,+ messageId,+ delta: request.message,+ turnId: parent.turnId,+ createdAt,+ });+ await options.dispatch({+ type: "thread.message.assistant.complete",+ commandId: commandId("message-complete"),+ threadId: parent.threadId,+ messageId,+ turnId: parent.turnId,+ createdAt,+ });++ return {+ receiptId: `message:${messageId}`,+ toolId: "SendToUser",+ phase: "success",+ threadId: parent.threadId,+ botId: parent.botId,+ summary: "Message sent to the user.",+ fatalToThread: false,+ createdAt,+ };+ };+const send = async (parent: AkeruDelegationParent,request: (typeof AkeruToolInputSchemas.SendToAgent)["Type"],@@ -161,7 +213,7 @@ export function createAkeruDelegationRuntime(options: AkeruDelegationRuntimeOpti};};- return { send, readSnapshot: options.readSnapshot };+ return { send, sendToUser, readSnapshot: options.readSnapshot };}export type AkeruDelegationRuntime = ReturnType<typeof createAkeruDelegationRuntime>;diff --git a/apps/server/src/provider/AkeruToolRuntime.test.ts b/apps/server/src/provider/AkeruToolRuntime.test.tsindex b85fb28cf..fd427e062 100644--- a/apps/server/src/provider/AkeruToolRuntime.test.ts+++ b/apps/server/src/provider/AkeruToolRuntime.test.ts@@ -277,6 +277,35 @@ describe("AkeruToolRuntime", () => {});});+ it("isolates user-message failures from the current thread", async () => {+ const runtime = createAkeruToolRuntime({ now: () => "2026-09-01T00:00:00.000Z" });+ const execution = {+ threadId: "thread-1",+ toolId: "SendToUser" as const,+ toolCallId: "tool-message",+ input: { message: "The export is ready." },+ approvalMode: "require-grant" as const,+ };+ runtime.registerSession("thread-1", {+ botId: BotId.make("parent"),+ runtimeMode: "full-access",+ workspaceType: "local",+ sendToUser: async () => {+ throw new Error("Message dispatch failed");+ },+ });+ runtime.grantApproval(execution);++ await expect(runtime.execute(execution)).resolves.toMatchObject({+ receiptId: "tool-message",+ toolId: "SendToUser",+ phase: "failure",+ failureCode: "internal",+ fatalToThread: false,+ summary: "Message dispatch failed",+ });+ });+it("translates await handles to workspace process ids", async () => {const runtime = createAkeruToolRuntime();runtime.registerSession("thread-1", {diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.tsindex 3fa07edf5..b2efeed8e 100644--- a/apps/server/src/provider/AkeruToolRuntime.ts+++ b/apps/server/src/provider/AkeruToolRuntime.ts@@ -70,6 +70,9 @@ export interface AkeruToolSession {input: (typeof AkeruToolInputSchemas.UpdateChannel)["Type"],) => Promise<string>;};+ readonly sendToUser?: (+ input: (typeof AkeruToolInputSchemas.SendToUser)["Type"],+ ) => Promise<AkeruToolReceipt>;}export interface AkeruToolRuntimeOptions {@@ -108,6 +111,7 @@ const BACKEND_NAMES: Record<| "SendToAgent"| "CreateChannel"| "UpdateChannel"+ | "SendToUser">,ReadonlyArray<string>> = {@@ -206,6 +210,7 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akerutools.add("CreateChannel");tools.add("UpdateChannel");}+ if (session.sendToUser) tools.add("SendToUser");return tools;};@@ -366,6 +371,26 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeru}}+ if (input.toolId === "SendToUser") {+ if (!session.sendToUser)+ throw new Error("User messaging is not available for this session.");+ try {+ return await session.sendToUser(decodeAkeruToolInput("SendToUser", decoded));+ } 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,+ 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 f716fa803..10277fdef 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -922,6 +922,15 @@ const make = (options?: AgentControllerLiveOptions) =>...(registeredMemoryHandlers ? { memoryHandlers: registeredMemoryHandlers } : {}),...(input.botId && delegationRuntime? {+ sendToUser: async (request) => {+ const active = sessions.get(key);+ const turnId = active?.activeTurn?.turnId;+ if (!turnId) throw new Error("User messaging requires an active turn.");+ return delegationRuntime!.sendToUser(+ { threadId, turnId, botId: input.botId!, depth: 0 },+ request,+ );+ },delegation: {send: async (request) => {const active = sessions.get(key);diff --git a/packages/contracts/src/akeruTools.test.ts b/packages/contracts/src/akeruTools.test.tsindex cfddaed01..1fb85301f 100644--- a/packages/contracts/src/akeruTools.test.ts+++ b/packages/contracts/src/akeruTools.test.ts@@ -49,6 +49,14 @@ describe("Akeru tool contracts", () => {expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "SendToAgent")?.approval).toBe("send");});+ it("decodes SendToUser input and keeps it approval-gated", () => {+ expect(decodeAkeruToolInput("SendToUser", { message: "The export is ready." })).toEqual({+ message: "The export is ready.",+ });+ expect(() => decodeAkeruToolInput("SendToUser", { message: "" })).toThrow();+ expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "SendToUser")?.approval).toBe("send");+ });+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 fe5b1cb85..8e758de5d 100644--- a/packages/contracts/src/akeruTools.ts+++ b/packages/contracts/src/akeruTools.ts@@ -56,6 +56,9 @@ export const AkeruToolInputSchemas = {channelId: GroupId,name: TrimmedNonEmptyString,}),+ SendToUser: Schema.Struct({+ message: TrimmedNonEmptyString.check(Schema.isMaxLength(AKERU_COMMAND_MAX_CHARS)),+ }),} as const;export type AkeruToolId = keyof typeof AkeruToolInputSchemas;@@ -189,6 +192,9 @@ export const AKERU_TOOL_CATALOG = [}),define("CreateChannel", "bot-workspace", "Create a bot channel."),define("UpdateChannel", "bot-workspace", "Rename a bot channel."),+ define("SendToUser", "bot-workspace", "Send a message into the current Akeru thread.", {+ approval: "send",+ }),] satisfies ReadonlyArray<AkeruToolDefinition>;export interface AkeruToolAvailabilityContext {