Skip to content

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): run approved Akeru tools (#39)

Leoca16a27bc027
diff --git a/apps/server/src/provider/AkeruMastraHarness.test.ts b/apps/server/src/provider/AkeruMastraHarness.test.ts
index 4f9a3c54f..89b85cff8 100644
--- a/apps/server/src/provider/AkeruMastraHarness.test.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.test.ts
@@ -1,14 +1,21 @@
import { AuthStorage } from "@mastra/code-sdk/auth/storage";
-import type { ToolsInput } from "@mastra/core/agent";
-import { TOOL_NAME_OVERRIDES } from "@mastra/code-sdk/tool-names";
import { RequestContext } from "@mastra/core/request-context";
-import { LocalFilesystem, LocalSandbox, Workspace } from "@mastra/core/workspace";
-import { AKERU_PRODUCT_FEEDBACK_TOOL_NAME, ProviderDriverKind } from "@t3tools/contracts";
+import {
+ AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
+ AKERU_TOOL_CATALOG,
+ ProviderDriverKind,
+} from "@t3tools/contracts";
import { assert, describe, it } from "vite-plus/test";
import { AKERU_AGENT_INSTRUCTIONS } from "./AkeruAgentInstructions.ts";
-import { mastraModelId, resolveAkeruMastraModel, resolveAkeruTools } from "./AkeruMastraHarness.ts";
+import {
+ criticalAkeruAction,
+ mastraModelId,
+ resolveAkeruMastraModel,
+ resolveAkeruTools,
+} from "./AkeruMastraHarness.ts";
import { productFeedbackToolInputSchema } from "./AkeruMastraHarness.ts";
+import type { AkeruToolRuntime } from "./AkeruToolRuntime.ts";
describe("AkeruMastraHarness", () => {
it("keeps Kimi model names on the Kimi subscription transport", () => {
@@ -37,28 +44,53 @@ describe("AkeruMastraHarness", () => {
assert.notInclude(AKERU_AGENT_INSTRUCTIONS, "coding agent");
});
- it("builds workspace and selected MCP tools from the controller resource", async () => {
- const workspace = new Workspace({
- filesystem: new LocalFilesystem({ basePath: process.cwd() }),
- sandbox: new LocalSandbox({ workingDirectory: process.cwd() }),
- tools: TOOL_NAME_OVERRIDES,
- });
+ it("selects implemented runtime tools without dropping approval-aware plugins", async () => {
const requestContext = new RequestContext();
requestContext.setRaw("controller", {
resourceId: "thread-1",
session: { modelId: "openai/gpt-5.6-sol" },
});
+ const runtime = {
+ toolsForThread: () => AKERU_TOOL_CATALOG.filter((tool) => tool.id === "Shell"),
+ requiresApproval: async () => true,
+ execute: async () => undefined,
+ } as unknown as AkeruToolRuntime;
+ const pluginTool = { id: "plugin", execute: async () => undefined, requireApproval: false };
+ const approvalPolicies: boolean[] = [];
const tools = await resolveAkeruTools(requestContext, {
authStorage: new AuthStorage("/tmp/akeru-unused-auth.json"),
- getThreadWorkspace: (threadId) => (threadId === "thread-1" ? workspace : undefined),
- getThreadTools: (threadId) =>
- (threadId === "thread-1" ? { exa_search: {} } : {}) as ToolsInput,
+ getThreadTools: () => ({
+ exa_search: pluginTool,
+ RestartMcpServers: pluginTool,
+ }),
+ syncThreadToolApproval: async (_threadId, _toolName, protectedAction) => {
+ approvalPolicies.push(protectedAction);
+ },
+ toolRuntime: runtime,
});
- assert.containsAllKeys(tools, ["view", "write_file", "execute_command", "exa_search"]);
- assert.containsAllKeys(tools, [AKERU_PRODUCT_FEEDBACK_TOOL_NAME]);
- await workspace.destroy();
+ assert.containsAllKeys(tools, [
+ "Shell",
+ "exa_search",
+ "RestartMcpServers",
+ AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
+ ]);
+ assert.notProperty(tools, "Read");
+ assert.notProperty(tools, "execute_command");
+ const restart = tools.RestartMcpServers as unknown as {
+ readonly needsApprovalFn: (input: unknown) => Promise<boolean>;
+ };
+ const search = tools.exa_search as unknown as {
+ readonly needsApprovalFn: (input: unknown) => Promise<boolean>;
+ };
+ assert.isTrue(await restart.needsApprovalFn({}));
+ assert.isTrue(await search.needsApprovalFn({ operation: "send" }));
+ assert.isTrue(await search.needsApprovalFn({ command: "git push origin main" }));
+ assert.isTrue(await search.needsApprovalFn({ path: ".env" }));
+ assert.isFalse(await search.needsApprovalFn({ operation: "read" }));
+ assert.deepEqual(approvalPolicies, [true, true, true, true, false]);
+ assert.equal(criticalAkeruAction("RestartMcpServers"), "production");
});
it("keeps product feedback draft-only and approval-gated", async () => {
@@ -76,8 +108,8 @@ describe("AkeruMastraHarness", () => {
requestContext.setRaw("controller", { resourceId: "thread-1" });
const tools = await resolveAkeruTools(requestContext, {
authStorage: new AuthStorage("/tmp/akeru-unused-auth.json"),
- getThreadWorkspace: () => undefined,
getThreadTools: () => ({}),
+ toolRuntime: { toolsForThread: () => [] } as unknown as AkeruToolRuntime,
});
const tool = tools[AKERU_PRODUCT_FEEDBACK_TOOL_NAME] as {
requireApproval?: boolean;
diff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.ts
index 355703133..f8235609b 100644
--- a/apps/server/src/provider/AkeruMastraHarness.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.ts
@@ -8,11 +8,12 @@ import {
import { createCodingAgent } from "@mastra/core/coding-agent";
import type { RequestContext } from "@mastra/core/request-context";
import type { StandardSchemaWithJSON } from "@mastra/core/schema";
-import { createTool } from "@mastra/core/tools";
-import { createWorkspaceTools, type Workspace } from "@mastra/core/workspace";
+import { createTool, type NeedsApprovalFn } from "@mastra/core/tools";
import {
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
ProductFeedbackToolDraft,
+ classifyAkeruExternalCommand,
+ classifyAkeruSensitivePath,
type ProviderDriverKind,
type ProductFeedbackToolDraft as ProductFeedbackToolDraftValue,
} from "@t3tools/contracts";
@@ -21,6 +22,8 @@ import * as Schema from "effect/Schema";
import { AKERU_AGENT_INSTRUCTIONS } from "./AkeruAgentInstructions.ts";
import { akeruKimiProvider, type AkeruKimiAccess } from "./AkeruKimiProvider.ts";
+import { createAkeruMastraTools } from "./AkeruMastraTools.ts";
+import type { AkeruToolRuntime } from "./AkeruToolRuntime.ts";
const DEFAULT_MODEL_ID = "openai/gpt-5.6-sol";
const decodeProductFeedbackToolDraft = Schema.decodeUnknownExit(ProductFeedbackToolDraft, {
@@ -73,7 +76,12 @@ export interface AkeruMastraHarnessOptions {
readonly authStorage: AuthStorage;
readonly getKimiAccess?: () => Promise<AkeruKimiAccess | undefined>;
readonly getThreadTools: (threadId: string) => ToolsInput;
- readonly getThreadWorkspace: (threadId: string) => Workspace | undefined;
+ readonly syncThreadToolApproval?: (
+ threadId: string,
+ toolName: string,
+ protectedAction: boolean,
+ ) => Promise<void>;
+ readonly toolRuntime: AkeruToolRuntime;
}
export interface AkeruMastraHarness {
@@ -141,20 +149,38 @@ export async function resolveAkeruTools(
): Promise<ToolsInput> {
const threadId = controllerResourceId(requestContext);
if (!threadId) return {};
- const workspace = options.getThreadWorkspace(threadId);
- const workspaceTools = workspace
- ? await createWorkspaceTools(workspace, {
- requestContext: Object.fromEntries(requestContext.entries()),
- workspace,
- })
- : {};
return {
- ...workspaceTools,
- ...options.getThreadTools(threadId),
+ ...approvalAwareTools(threadId, options.getThreadTools(threadId), options),
+ ...createAkeruMastraTools(threadId, options.toolRuntime),
[AKERU_PRODUCT_FEEDBACK_TOOL_NAME]: productFeedbackTool,
};
}
+function approvalAwareTools(
+ threadId: string,
+ tools: ToolsInput,
+ options: AkeruMastraHarnessOptions,
+): ToolsInput {
+ return Object.fromEntries(
+ Object.entries(tools).map(([name, tool]) => {
+ const configured = tool as unknown as {
+ readonly requireApproval?: boolean | NeedsApprovalFn;
+ readonly needsApprovalFn?: NeedsApprovalFn;
+ };
+ const existing = configured.needsApprovalFn ?? configured.requireApproval;
+ const needsApproval: NeedsApprovalFn = async (input, context) => {
+ const protectedAction = akeruActionNeedsApproval(name, input);
+ await options.syncThreadToolApproval?.(threadId, name, protectedAction);
+ return (
+ protectedAction ||
+ (typeof existing === "function" ? await existing(input, context) : existing === true)
+ );
+ };
+ return [name, { ...tool, requireApproval: needsApproval, needsApprovalFn: needsApproval }];
+ }),
+ );
+}
+
export type AkeruToolCategory = "read" | "edit" | "execute" | "mcp" | "other";
export type AkeruCriticalAction =
| "send"
@@ -224,6 +250,7 @@ function textTokens(value: string): ReadonlySet<string> {
function criticalActionFromText(value: string): AkeruCriticalAction | null {
const tokens = textTokens(value);
+ if (tokens.has("restart") && tokens.has("mcp")) return "production";
for (const [action, actionTokens] of CRITICAL_ACTION_TOKENS) {
if ([...actionTokens].some((token) => tokens.has(token))) return action;
}
@@ -261,6 +288,10 @@ function inspectAkeruAction(toolName: string, args?: unknown): AkeruActionInspec
const keyedAction = criticalActionFromText(key);
if (keyedAction) return { action: keyedAction, hasUnclassifiedIntent: false };
if (ACTION_TEXT_KEYS.has(normalizedKey) && typeof entry === "string") {
+ if (normalizedKey === "command") {
+ const action = classifyAkeruExternalCommand(entry);
+ if (action) return { action, hasUnclassifiedIntent: false };
+ }
const action = criticalActionFromText(entry);
if (action) return { action, hasUnclassifiedIntent: false };
if (MUTATING_INTENT_KEYS.has(normalizedKey)) {
@@ -270,6 +301,13 @@ function inspectAkeruAction(toolName: string, args?: unknown): AkeruActionInspec
}
}
}
+ if (
+ typeof entry === "string" &&
+ (normalizedKey === "path" || normalizedKey.endsWith("path")) &&
+ classifyAkeruSensitivePath(entry)
+ ) {
+ return { action: "secrets", hasUnclassifiedIntent: false };
+ }
if (typeof entry === "object" && entry !== null) pending.push(entry);
}
}
diff --git a/apps/server/src/provider/AkeruMastraTools.test.ts b/apps/server/src/provider/AkeruMastraTools.test.ts
new file mode 100644
index 000000000..940117e3d
--- /dev/null
+++ b/apps/server/src/provider/AkeruMastraTools.test.ts
@@ -0,0 +1,34 @@
+import { AKERU_TOOL_CATALOG } from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import type { AkeruToolRuntime } from "./AkeruToolRuntime.ts";
+import { createAkeruMastraTools } from "./AkeruMastraTools.ts";
+
+describe("createAkeruMastraTools", () => {
+ it("passes an exact call identity and approval mode to the runtime", async () => {
+ const execute = vi.fn(async () => ({ ok: true }));
+ const runtime = {
+ toolsForThread: () => [AKERU_TOOL_CATALOG[0]!],
+ requiresApproval: vi.fn(async () => true),
+ execute,
+ } as unknown as AkeruToolRuntime;
+ const shell = createAkeruMastraTools("thread-1", runtime).Shell as {
+ readonly execute?: (input: unknown, context: unknown) => Promise<unknown>;
+ };
+ if (!shell?.execute) throw new Error("Shell tool is unavailable.");
+
+ await expect(
+ shell.execute({ command: "pwd" }, { agent: { toolCallId: "tool-1" } } as never),
+ ).resolves.toEqual({ ok: true });
+ expect(execute).toHaveBeenCalledWith({
+ threadId: "thread-1",
+ toolId: "Shell",
+ toolCallId: "tool-1",
+ input: { command: "pwd" },
+ approvalMode: "require-grant",
+ });
+ await expect(shell.execute({ command: "pwd" }, {} as never)).rejects.toThrow(
+ "has no call identity",
+ );
+ });
+});
diff --git a/apps/server/src/provider/AkeruMastraTools.ts b/apps/server/src/provider/AkeruMastraTools.ts
new file mode 100644
index 000000000..907ba4994
--- /dev/null
+++ b/apps/server/src/provider/AkeruMastraTools.ts
@@ -0,0 +1,40 @@
+import type { ToolsInput } from "@mastra/core/agent";
+import { createTool } from "@mastra/core/tools";
+import { AkeruToolInputSchemas } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { z } from "zod";
+
+import type { AkeruToolRuntime } from "./AkeruToolRuntime.ts";
+
+export function createAkeruMastraTools(threadId: string, runtime: AkeruToolRuntime): ToolsInput {
+ return Object.fromEntries(
+ runtime.toolsForThread(threadId).map((definition) => {
+ const schema = AkeruToolInputSchemas[definition.id];
+ const standardSchema = Schema.toStandardJSONSchemaV1(schema);
+ const approval = (input: unknown) => runtime.requiresApproval(threadId, definition.id, input);
+ const tool = createTool({
+ id: definition.id,
+ description: definition.description,
+ inputSchema: z.fromJSONSchema(
+ standardSchema["~standard"].jsonSchema.input({ target: "draft-07" }),
+ ),
+ requireApproval: approval,
+ execute: (input, context) => {
+ const toolCallId = context.agent?.toolCallId;
+ if (!toolCallId) {
+ throw new Error(`Tool '${definition.id}' has no call identity.`);
+ }
+ return runtime.execute({
+ threadId,
+ toolId: definition.id,
+ toolCallId,
+ input,
+ approvalMode: "require-grant",
+ });
+ },
+ });
+ tool.needsApprovalFn = approval;
+ return [definition.id, tool] as const;
+ }),
+ );
+}
diff --git a/apps/server/src/provider/AkeruToolRuntime.test.ts b/apps/server/src/provider/AkeruToolRuntime.test.ts
new file mode 100644
index 000000000..689944d1c
--- /dev/null
+++ b/apps/server/src/provider/AkeruToolRuntime.test.ts
@@ -0,0 +1,148 @@
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeFS from "node:fs";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+
+import { LocalFilesystem, LocalSandbox, Workspace } from "@mastra/core/workspace";
+import { afterEach, describe, expect, it } from "vite-plus/test";
+
+import { createAkeruToolRuntime } from "./AkeruToolRuntime.ts";
+
+const directories = new Set<string>();
+
+function workspace(name: string) {
+ const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), `akeru-tool-${name}-`));
+ directories.add(root);
+ return new Workspace({
+ filesystem: new LocalFilesystem({ basePath: root }),
+ sandbox: new LocalSandbox({ workingDirectory: root }),
+ });
+}
+
+describe("AkeruToolRuntime", () => {
+ afterEach(() => {
+ for (const directory of directories) {
+ NodeFS.rmSync(directory, { force: true, recursive: true });
+ }
+ directories.clear();
+ });
+
+ it("only exposes tools backed by the registered computer boundaries", () => {
+ const runtime = createAkeruToolRuntime();
+ runtime.registerSession("thread-1", {
+ runtimeMode: "approval-required",
+ workspaceType: "local",
+ workspace: workspace("bot"),
+ });
+ expect(runtime.toolsForThread("thread-1").map((tool) => tool.id)).toEqual([
+ "Shell",
+ "Read",
+ "AwaitShell",
+ ]);
+ });
+
+ it("requires an exact one-shot grant for local shell commands", async () => {
+ const runtime = createAkeruToolRuntime();
+ runtime.registerSession("thread-1", {
+ runtimeMode: "full-access",
+ workspaceType: "local",
+ workspace: workspace("shell"),
+ });
+ const execution = {
+ threadId: "thread-1",
+ toolId: "Shell" as const,
+ toolCallId: "tool-1",
+ input: { command: "pwd" },
+ approvalMode: "require-grant" as const,
+ };
+ await expect(runtime.execute(execution)).rejects.toThrow("requires approval");
+ runtime.grantApproval({ ...execution, input: { command: "echo wrong" } });
+ await expect(runtime.execute(execution)).rejects.toThrow("requires approval");
+ runtime.grantApproval({ ...execution, input: { command: " pwd " } });
+ await expect(runtime.execute(execution)).resolves.toBeDefined();
+ await expect(runtime.execute(execution)).rejects.toThrow("requires approval");
+ });
+
+ it("copies files only when both boundaries are registered", async () => {
+ const runtime = createAkeruToolRuntime();
+ const bot = workspace("copy-bot");
+ const user = workspace("copy-user");
+ await user.filesystem?.writeFile("report.txt", "report");
+ runtime.registerSession("thread-1", {
+ runtimeMode: "full-access",
+ workspaceType: "local",
+ workspace: bot,
+ userComputerWorkspace: user,
+ });
+ const execution = {
+ threadId: "thread-1",
+ toolId: "CopyToBox" as const,
+ toolCallId: "tool-copy",
+ input: { sourcePath: "report.txt", destinationPath: "inbox/report.txt" },
+ approvalMode: "require-grant" as const,
+ };
+ runtime.grantApproval(execution);
+ await runtime.execute(execution);
+ expect(await bot.filesystem?.readFile("inbox/report.txt", { encoding: "utf-8" })).toBe(
+ "report",
+ );
+ });
+
+ it("invalidates approvals when the thread workspace changes", async () => {
+ const runtime = createAkeruToolRuntime();
+ const original = workspace("original");
+ const replacement = workspace("replacement");
+ const user = workspace("user");
+ await user.filesystem?.writeFile(".env", "SECRET=value");
+ runtime.registerSession("thread-1", {
+ runtimeMode: "full-access",
+ workspaceType: "local",
+ workspace: original,
+ userComputerWorkspace: user,
+ });
+ const execution = {
+ threadId: "thread-1",
+ toolId: "CopyToBox" as const,
+ toolCallId: "tool-copy",
+ input: { sourcePath: ".env", destinationPath: ".env" },
+ approvalMode: "require-grant" as const,
+ };
+ runtime.grantApproval(execution);
+ runtime.registerSession("thread-1", {
+ runtimeMode: "full-access",
+ workspaceType: "local",
+ workspace: replacement,
+ userComputerWorkspace: user,
+ });
+
+ await expect(runtime.execute(execution)).rejects.toThrow("requires approval");
+ await expect(replacement.filesystem?.readFile(".env")).rejects.toThrow();
+ });
+
+ it("translates await handles to workspace process ids", async () => {
+ const runtime = createAkeruToolRuntime();
+ runtime.registerSession("thread-1", {
+ runtimeMode: "full-access",
+ workspaceType: "cloud",
+ workspace: workspace("await"),
+ });
+ const started = await runtime.execute({
+ threadId: "thread-1",
+ toolId: "Shell",
+ toolCallId: "tool-start",
+ input: { command: "printf done", background: true },
+ approvalMode: "require-grant",
+ });
+ const handleId = String(started).match(/PID: ([^)]+)/)?.[1];
+ if (!handleId) throw new Error("Background command did not return a process id.");
+ await expect(
+ runtime.execute({
+ threadId: "thread-1",
+ toolId: "AwaitShell",
+ toolCallId: "tool-await",
+ input: { handleId },
+ approvalMode: "require-grant",
+ }),
+ ).resolves.toContain("done");
+ });
+});
diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.ts
new file mode 100644
index 000000000..a3e154077
--- /dev/null
+++ b/apps/server/src/provider/AkeruToolRuntime.ts
@@ -0,0 +1,258 @@
+import { RequestContext } from "@mastra/core/request-context";
+import { createWorkspaceTools, type Workspace } from "@mastra/core/workspace";
+import {
+ AkeruToolInputSchemas,
+ type AkeruToolDefinition,
+ type AkeruToolId,
+ type AkeruToolWorkspaceType,
+ type RuntimeMode,
+ akeruToolRequiresApproval,
+ decodeAkeruToolInput,
+ filterAkeruTools,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+
+export interface AkeruToolSession {
+ readonly runtimeMode: RuntimeMode;
+ readonly workspaceType: AkeruToolWorkspaceType;
+ readonly workspace?: Workspace;
+ readonly userComputerWorkspace?: Workspace;
+}
+
+export interface AkeruToolExecution {
+ readonly threadId: string;
+ readonly toolId: AkeruToolId;
+ readonly toolCallId: string;
+ readonly input: unknown;
+ readonly approvalMode: "require-grant";
+}
+
+export interface AkeruToolRuntime {
+ readonly registerSession: (threadId: string, session: AkeruToolSession) => void;
+ readonly unregisterSession: (threadId: string) => void;
+ readonly clearApprovals: (threadId: string) => void;
+ readonly toolsForThread: (threadId: string) => ReadonlyArray<AkeruToolDefinition>;
+ readonly requiresApproval: (
+ threadId: string,
+ toolId: AkeruToolId,
+ input: unknown,
+ ) => Promise<boolean>;
+ readonly grantApproval: (input: Omit<AkeruToolExecution, "approvalMode">) => void;
+ readonly execute: (input: AkeruToolExecution) => Promise<unknown>;
+}
+
+const BACKEND_NAMES: Record<
+ Exclude<AkeruToolId, "CopyToBox" | "CopyFromBox" | "request_box_help">,
+ ReadonlyArray<string>
+> = {
+ Shell: ["execute_command", "mastra_workspace_execute_command"],
+ Read: ["view", "mastra_workspace_read_file"],
+ Screenshot: ["mastra_workspace_computer_screenshot"],
+ ExternalShell: ["execute_command", "mastra_workspace_execute_command"],
+ ExternalRead: ["view", "mastra_workspace_read_file"],
+ AwaitShell: ["get_process_output", "mastra_workspace_get_process_output"],
+ AwaitExternalShell: ["get_process_output", "mastra_workspace_get_process_output"],
+};
+
+function field(value: unknown, key: string): unknown {
+ if (typeof value !== "object" || value === null) return undefined;
+ return Object.getOwnPropertyDescriptor(value, key)?.value;
+}
+
+function requiredString(value: unknown, key: string): string {
+ const candidate = field(value, key);
+ if (typeof candidate !== "string" || candidate.length === 0) {
+ throw new Error(`Tool input field '${key}' is required.`);
+ }
+ return candidate;
+}
+
+function canonicalInput(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(canonicalInput).join(",")}]`;
+ if (typeof value === "object" && value !== null) {
+ return `{${Object.keys(value)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${canonicalInput(field(value, key))}`)
+ .join(",")}}`;
+ }
+ return JSON.stringify(value) ?? "undefined";
+}
+
+function workspaceForTool(toolId: AkeruToolId, session: AkeruToolSession) {
+ return toolId === "ExternalShell" || toolId === "ExternalRead" || toolId === "AwaitExternalShell"
+ ? session.userComputerWorkspace
+ : session.workspace;
+}
+
+async function toolsForWorkspace(workspace: Workspace | undefined) {
+ if (!workspace) return {};
+ return createWorkspaceTools(workspace, {
+ requestContext: {},
+ workspace,
+ });
+}
+
+function executable(value: unknown): value is {
+ readonly execute: (input: unknown, context: Record<string, unknown>) => Promise<unknown>;
+} {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "execute" in value &&
+ typeof value.execute === "function"
+ );
+}
+
+export function createAkeruToolRuntime(): AkeruToolRuntime {
+ const sessions = new Map<string, AkeruToolSession>();
+ const grants = new Map<string, { readonly toolId: AkeruToolId; readonly input: string }>();
+ const key = (threadId: string, toolCallId: string) => `${threadId}\u0000${toolCallId}`;
+ const clearGrants = (threadId: string) => {
+ for (const grantKey of grants.keys()) {
+ if (grantKey.startsWith(`${threadId}\u0000`)) grants.delete(grantKey);
+ }
+ };
+
+ const implementedTools = (session: AkeruToolSession) => {
+ const tools = new Set<AkeruToolId>();
+ if (session.workspace?.sandbox?.executeCommand) tools.add("Shell");
+ if (session.workspace?.filesystem) tools.add("Read");
+ if (session.workspace?.sandbox?.processes) tools.add("AwaitShell");
+ if (session.workspace?.sandbox?.computer) tools.add("Screenshot");
+ if (session.userComputerWorkspace?.sandbox?.executeCommand) {
+ tools.add("ExternalShell");
+ }
+ if (session.userComputerWorkspace?.filesystem) {
+ tools.add("ExternalRead");
+ }
+ if (session.userComputerWorkspace?.sandbox?.processes) {
+ tools.add("AwaitExternalShell");
+ }
+ if (session.workspace?.filesystem && session.userComputerWorkspace?.filesystem) {
+ tools.add("CopyToBox");
+ tools.add("CopyFromBox");
+ }
+ return tools;
+ };
+
+ const toolsForThread = (threadId: string) => {
+ const session = sessions.get(threadId);
+ if (!session) throw new Error(`Tool session '${threadId}' is not registered.`);
+ const implemented = implementedTools(session);
+ return filterAkeruTools({
+ capabilities: new Set(["bot-workspace", "user-computer"]),
+ workspaceType: session.workspaceType,
+ hasUserComputer: Boolean(session.userComputerWorkspace),
+ localFullAccess: session.runtimeMode === "full-access",
+ implementedTools: implemented,
+ });
+ };
+
+ const validatedInput = (toolId: AkeruToolId, input: unknown) =>
+ Schema.decodeUnknownPromise(AkeruToolInputSchemas[toolId])(input, {
+ onExcessProperty: "error",
+ });
+
+ return {
+ registerSession: (threadId, session) => {
+ clearGrants(threadId);
+ sessions.set(threadId, session);
+ },
+ unregisterSession: (threadId) => {
+ sessions.delete(threadId);
+ clearGrants(threadId);
+ },
+ clearApprovals: clearGrants,
+ toolsForThread,
+ requiresApproval: async (threadId, toolId, input) => {
+ const session = sessions.get(threadId);
+ if (!session) throw new Error(`Tool session '${threadId}' is not registered.`);
+ const tool = toolsForThread(threadId).find((candidate) => candidate.id === toolId);
+ if (!tool) throw new Error(`Tool '${toolId}' is not available for this turn.`);
+ return akeruToolRequiresApproval(
+ tool,
+ {
+ localFullAccess: session.runtimeMode === "full-access",
+ workspaceType: session.workspaceType,
+ },
+ await validatedInput(toolId, input),
+ );
+ },
+ grantApproval: (input) => {
+ grants.set(key(input.threadId, input.toolCallId), {
+ toolId: input.toolId,
+ input: canonicalInput(decodeAkeruToolInput(input.toolId, input.input)),
+ });
+ },
+ execute: async (input) => {
+ const session = sessions.get(input.threadId);
+ if (!session) throw new Error(`Tool session '${input.threadId}' is not registered.`);
+ const tool = toolsForThread(input.threadId).find(
+ (candidate) => candidate.id === input.toolId,
+ );
+ if (!tool) throw new Error(`Tool '${input.toolId}' is not available for this turn.`);
+ const decoded = await validatedInput(input.toolId, input.input);
+ if (
+ akeruToolRequiresApproval(
+ tool,
+ {
+ localFullAccess: session.runtimeMode === "full-access",
+ workspaceType: session.workspaceType,
+ },
+ decoded,
+ )
+ ) {
+ const grantKey = key(input.threadId, input.toolCallId);
+ const grant = grants.get(grantKey);
+ if (
+ !grant ||
+ input.approvalMode !== "require-grant" ||
+ grant?.toolId !== input.toolId ||
+ grant.input !== canonicalInput(decoded)
+ ) {
+ throw new Error(`Tool '${input.toolId}' requires approval.`);
+ }
+ grants.delete(grantKey);
+ }
+
+ if (input.toolId === "CopyToBox" || input.toolId === "CopyFromBox") {
+ const source =
+ input.toolId === "CopyToBox" ? session.userComputerWorkspace : session.workspace;
+ const destination =
+ input.toolId === "CopyToBox" ? session.workspace : session.userComputerWorkspace;
+ if (!source?.filesystem || !destination?.filesystem) {
+ throw new Error("Both computer boundaries are required for file copy.");
+ }
+ const sourcePath = requiredString(decoded, "sourcePath");
+ const destinationPath = requiredString(decoded, "destinationPath");
+ await destination.filesystem.writeFile(
+ destinationPath,
+ await source.filesystem.readFile(sourcePath),
+ { recursive: true },
+ );
+ return { sourcePath, destinationPath };
+ }
+ if (input.toolId === "request_box_help") {
+ throw new Error("Human handoff is not available for this session.");
+ }
+
+ const workspace = workspaceForTool(input.toolId, session);
+ const backends = await toolsForWorkspace(workspace);
+ const backendName = BACKEND_NAMES[input.toolId].find((name) => executable(backends[name]));
+ const backend = backendName ? backends[backendName] : undefined;
+ if (!executable(backend)) throw new Error(`Tool '${input.toolId}' has no backend.`);
+ const backendInput =
+ input.toolId === "AwaitShell" || input.toolId === "AwaitExternalShell"
+ ? { pid: requiredString(decoded, "handleId"), wait: true }
+ : decoded;
+ return backend.execute(backendInput, {
+ workspace,
+ requestContext: new RequestContext(),
+ observe: {
+ span: async <A>(_name: string, run: () => A | Promise<A>) => run(),
+ log: () => undefined,
+ },
+ });
+ },
+ };
+}
diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.ts
index a9a402171..a4a720070 100644
--- a/apps/server/src/provider/Layers/AgentController.test.ts
+++ b/apps/server/src/provider/Layers/AgentController.test.ts
@@ -152,6 +152,7 @@ function makeMastraHarness() {
setForCategory: vi.fn(async () => undefined),
setForTool: vi.fn(async () => undefined),
},
+ grantTool: vi.fn(),
subscribe: vi.fn((listener: (event: AgentControllerEvent) => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
@@ -590,6 +591,10 @@ describe("AgentControllerLive", () => {
toolName: AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
policy: "ask",
});
+ expect(mastra.session.permissions.setForTool).toHaveBeenCalledWith({
+ toolName: "RestartMcpServers",
+ policy: "ask",
+ });
yield* controller.sendTurn({ threadId: codexThreadId, input: "Prepare feedback." });
mastra.emit({
@@ -616,6 +621,79 @@ describe("AgentControllerLive", () => {
);
});
+ it.effect("grants one exact Akeru tool call without persisting acceptAlways", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* resolveCodex(controller);
+ yield* controller.startSession(codexThreadId, {
+ threadId: codexThreadId,
+ provider: ProviderDriverKind.make("codex"),
+ providerInstanceId: codexInstanceId,
+ cwd: process.cwd(),
+ modelSelection: codexSelection,
+ runtimeMode: "full-access",
+ });
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Run pwd." });
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "shell-tool-1",
+ toolName: "Shell",
+ args: { command: "pwd" },
+ } as AgentControllerEvent);
+ yield* controller.respondToRequest({
+ threadId: codexThreadId,
+ requestId: ApprovalRequestId.make("shell-tool-1"),
+ decision: "acceptAlways",
+ });
+
+ const runtime = mastra.harnessOptions[0]?.toolRuntime;
+ assert.isDefined(runtime);
+ const execution = {
+ threadId: String(codexThreadId),
+ toolId: "Shell" as const,
+ toolCallId: "shell-tool-1",
+ input: { command: "pwd" },
+ approvalMode: "require-grant" as const,
+ };
+ yield* Effect.promise(() => runtime.execute(execution));
+ yield* Effect.promise(() =>
+ expect(runtime.execute(execution)).rejects.toThrow("Tool 'Shell' requires approval."),
+ );
+ expect(mastra.session.permissions.setForTool).not.toHaveBeenCalledWith({
+ toolName: "Shell",
+ policy: "allow",
+ });
+ expect(mastra.session.respondToToolApproval).toHaveBeenCalledWith({
+ toolCallId: "shell-tool-1",
+ decision: "approve",
+ });
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "shell-tool-stale",
+ toolName: "Shell",
+ args: { command: "pwd" },
+ } as AgentControllerEvent);
+ yield* controller.respondToRequest({
+ threadId: codexThreadId,
+ requestId: ApprovalRequestId.make("shell-tool-stale"),
+ decision: "accept",
+ });
+ yield* controller.interruptTurn({ threadId: codexThreadId });
+ yield* Effect.promise(() =>
+ expect(runtime.execute({ ...execution, toolCallId: "shell-tool-stale" })).rejects.toThrow(
+ "Tool 'Shell' requires approval.",
+ ),
+ );
+ mastra.finishSend();
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
it.effect("keeps a suspended Mastra turn active until tool input resumes", () => {
const bridge = makeBridge();
const mastra = makeMastraHarness();
@@ -762,6 +840,40 @@ describe("AgentControllerLive", () => {
"builtin-exa": { url: "https://mcp.exa.ai/mcp" },
});
expect(mcpManager.init).toHaveBeenCalledOnce();
+ assert.property(
+ mastra.harnessOptions[0]?.getThreadTools(String(codexThreadId)),
+ "exa_search",
+ );
+ expect(mastra.session.permissions.setForTool).toHaveBeenCalledWith({
+ toolName: "exa_search",
+ policy: "ask",
+ });
+
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Search." });
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "exa-tool-1",
+ toolName: "exa_search",
+ args: { operation: "read" },
+ } as AgentControllerEvent);
+ yield* controller.respondToRequest({
+ threadId: codexThreadId,
+ requestId: ApprovalRequestId.make("exa-tool-1"),
+ decision: "acceptForSession",
+ });
+ const syncApproval = mastra.harnessOptions[0]?.syncThreadToolApproval;
+ assert.isDefined(syncApproval);
+ yield* Effect.promise(() => syncApproval(String(codexThreadId), "exa_search", true));
+ expect(mastra.session.permissions.setForTool).toHaveBeenLastCalledWith({
+ toolName: "exa_search",
+ policy: "ask",
+ });
+ yield* Effect.promise(() => syncApproval(String(codexThreadId), "exa_search", false));
+ expect(mastra.session.permissions.setForTool).toHaveBeenLastCalledWith({
+ toolName: "exa_search",
+ policy: "allow",
+ });
+ mastra.finishSend();
yield* controller.stopSession({ threadId: codexThreadId });
expect(mcpManager.disconnect).toHaveBeenCalledOnce();
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index d71e537f1..804d9d3b4 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -18,6 +18,7 @@ import {
RuntimeItemId,
RuntimeRequestId,
TurnId,
+ AKERU_TOOL_CATALOG,
DEFAULT_BOT_SANDBOX_BROWSER_SHARING,
type McpServer,
type ModelSelection,
@@ -41,12 +42,14 @@ import {
type SubscriptionProviderId,
} from "../../subscription-auth/service.ts";
import {
+ akeruActionNeedsApproval,
createAkeruMastraHarness,
mastraModelId,
type AkeruMastraHarness,
type AkeruMastraHarnessOptions,
type AkeruMastraSession,
} from "../AkeruMastraHarness.ts";
+import { createAkeruToolRuntime, type AkeruToolSession } from "../AkeruToolRuntime.ts";
import type { BotBrowser, BotBrowserAttachment, CreateBotBrowserInput } from "../botBrowser.ts";
import { AkeruSessionResources } from "../AkeruSessionResources.ts";
import type { CreateRemoteBotWorkspaceInput } from "../botWorkspace.ts";
@@ -93,6 +96,9 @@ interface ActiveSession {
status: ProviderSession["status"];
activeTurn: ActiveTurn | null;
readonly toolNames: Map<string, string>;
+ readonly approvalRequests: Map<string, { readonly name: string; readonly input: unknown }>;
+ readonly connectorSessionApprovals: Set<string>;
+ toolSession: AkeruToolSession;
readonly workspaceResourceKey: string;
readonly unsubscribe: () => void;
}
@@ -289,6 +295,7 @@ const make = (options?: AgentControllerLiveOptions) =>
...(options?.makeRemoteWorkspace ? { makeRemoteWorkspace: options.makeRemoteWorkspace } : {}),
...(options?.makeBotBrowser ? { makeBotBrowser: options.makeBotBrowser } : {}),
});
+ const toolRuntime = createAkeruToolRuntime();
const legacyResourceIdentity = new Map<
string,
{
@@ -303,8 +310,18 @@ const make = (options?: AgentControllerLiveOptions) =>
makeMastraHarness({
authStorage,
getKimiAccess: () => subscriptionAuth.getKimiForCodingAccess(),
+ syncThreadToolApproval: async (threadId, toolName, protectedAction) => {
+ const active = sessions.get(threadId);
+ if (!active || (!protectedAction && !active.connectorSessionApprovals.has(toolName))) {
+ return;
+ }
+ await active.session.permissions.setForTool({
+ toolName,
+ policy: protectedAction ? "ask" : "allow",
+ });
+ },
getThreadTools: (threadId) => sessionResources.getConnectorTools(threadId),
- getThreadWorkspace: (threadId) => sessionResources.getWorkspace(threadId),
+ toolRuntime,
}),
);
yield* runMastra("init", () => bundle.controller.init());
@@ -373,6 +390,8 @@ const make = (options?: AgentControllerLiveOptions) =>
...(errorMessage ? { errorMessage } : {}),
},
});
+ active.approvalRequests.clear();
+ toolRuntime.clearApprovals(String(threadId));
active.activeTurn = null;
publishSessionState(threadId, active, "ready");
};
@@ -462,6 +481,7 @@ const make = (options?: AgentControllerLiveOptions) =>
case "tool_end": {
if (!turn) return;
const toolName = active.toolNames.get(event.toolCallId) ?? "tool";
+ active.approvalRequests.delete(event.toolCallId);
publish({
...baseEvent(threadId, active, turn.turnId),
itemId: RuntimeItemId.make(event.toolCallId),
@@ -478,6 +498,10 @@ const make = (options?: AgentControllerLiveOptions) =>
case "tool_approval_required":
if (!turn) return;
active.toolNames.set(event.toolCallId, event.toolName);
+ active.approvalRequests.set(event.toolCallId, {
+ name: event.toolName,
+ input: event.args,
+ });
turn.waiting = true;
publishSessionState(threadId, active, "waiting");
publish({
@@ -498,11 +522,17 @@ const make = (options?: AgentControllerLiveOptions) =>
{ decision: "accept", label: "Add to feedback draft" },
{ decision: "decline", label: "Cancel" },
]
- : [
- { decision: "accept", label: "Allow" },
- { decision: "acceptForSession", label: "Allow for session" },
- { decision: "decline", label: "Decline" },
- ],
+ : AKERU_TOOL_CATALOG.some((tool) => tool.id === event.toolName) ||
+ akeruActionNeedsApproval(event.toolName, event.args)
+ ? [
+ { decision: "accept", label: "Allow" },
+ { decision: "decline", label: "Decline" },
+ ]
+ : [
+ { decision: "accept", label: "Allow" },
+ { decision: "acceptForSession", label: "Allow for session" },
+ { decision: "decline", label: "Decline" },
+ ],
},
});
return;
@@ -656,6 +686,8 @@ const make = (options?: AgentControllerLiveOptions) =>
existing.providerInstanceId === resolved.providerInstanceId
) {
existing.runtimeMode = input.runtimeMode;
+ existing.toolSession = { ...existing.toolSession, runtimeMode: input.runtimeMode };
+ toolRuntime.registerSession(key, existing.toolSession);
return toProviderSession(threadId, existing);
}
const existingLegacy = legacyResourceIdentity.get(key);
@@ -722,6 +754,15 @@ const make = (options?: AgentControllerLiveOptions) =>
),
);
}
+ const toolSession: AkeruToolSession = {
+ runtimeMode: input.runtimeMode,
+ workspaceType: resources.workspaceType,
+ workspace: resources.workspace,
+ ...(resources.userComputerWorkspace
+ ? { userComputerWorkspace: resources.userComputerWorkspace }
+ : {}),
+ };
+ toolRuntime.registerSession(key, toolSession);
const session = yield* runMastra("createSession", () =>
bundle.controller.createSession({
id: key,
@@ -733,9 +774,15 @@ const make = (options?: AgentControllerLiveOptions) =>
}),
).pipe(
Effect.tapError(() =>
- runMastra("resources.release", () =>
- sessionResources.release(key, { destroy: true }),
- ).pipe(Effect.ignoreCause({ log: true })),
+ Effect.all(
+ [
+ runMastra("resources.release", () =>
+ sessionResources.release(key, { destroy: true }),
+ ).pipe(Effect.ignoreCause({ log: true })),
+ Effect.sync(() => toolRuntime.unregisterSession(key)),
+ ],
+ { discard: true },
+ ),
),
);
yield* runMastra("state.set", () =>
@@ -762,11 +809,18 @@ const make = (options?: AgentControllerLiveOptions) =>
),
{ discard: true },
);
- yield* runMastra("permissions.setForTool", () =>
- session.permissions.setForTool({
- toolName: AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
- policy: "ask",
- }),
+ yield* Effect.forEach(
+ new Set([
+ ...toolRuntime.toolsForThread(key).map((tool) => tool.id),
+ ...Object.keys(sessionResources.getConnectorTools(key)),
+ AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
+ "RestartMcpServers",
+ ]),
+ (toolName) =>
+ runMastra("permissions.setForTool", () =>
+ session.permissions.setForTool({ toolName, policy: "ask" }),
+ ),
+ { discard: true },
);
const createdAt = nowIso();
const activeWithoutUnsubscribe = {
@@ -781,6 +835,9 @@ const make = (options?: AgentControllerLiveOptions) =>
status: "ready" as const,
activeTurn: null,
toolNames: new Map<string, string>(),
+ approvalRequests: new Map(),
+ connectorSessionApprovals: new Set<string>(),
+ toolSession,
workspaceResourceKey,
};
const unsubscribe = session.subscribe((event) => {
@@ -918,13 +975,28 @@ const make = (options?: AgentControllerLiveOptions) =>
}
return yield* legacyProviderBridge.respondToRequest(input);
}
+ if (!active.activeTurn) return;
const toolCallId = String(input.requestId);
- const toolName = active.toolNames.get(toolCallId);
+ const toolRequest = active.approvalRequests.get(toolCallId);
+ if (!toolRequest) return;
+ active.approvalRequests.delete(toolCallId);
+ const { name: toolName, input: toolInput } = toolRequest;
+ const akeruTool = AKERU_TOOL_CATALOG.find((tool) => tool.id === toolName);
+ if (akeruTool && input.decision !== "decline" && input.decision !== "cancel") {
+ toolRuntime.grantApproval({
+ threadId: key,
+ toolCallId,
+ toolId: akeruTool.id,
+ input: toolInput,
+ });
+ }
if (
input.decision === "acceptForSession" &&
- toolName &&
+ !akeruTool &&
+ !akeruActionNeedsApproval(toolName, toolInput) &&
toolName !== AKERU_PRODUCT_FEEDBACK_TOOL_NAME
) {
+ active.connectorSessionApprovals.add(toolName);
yield* runMastra("permissions.setForTool", () =>
active.session.permissions.setForTool({ toolName, policy: "allow" }),
);
@@ -932,7 +1004,10 @@ const make = (options?: AgentControllerLiveOptions) =>
if (active.activeTurn) active.activeTurn.waiting = false;
active.session.respondToToolApproval({
toolCallId,
- decision: approvalDecision(input.decision),
+ decision:
+ akeruTool && input.decision !== "decline" && input.decision !== "cancel"
+ ? "approve"
+ : approvalDecision(input.decision),
});
publish({
...baseEvent(input.threadId, active, active.activeTurn?.turnId),
@@ -1000,6 +1075,7 @@ const make = (options?: AgentControllerLiveOptions) =>
yield* runMastra("resources.release", () =>
sessionResources.release(key, { destroy: destroyResources }),
).pipe(Effect.ignoreCause({ log: true }));
+ toolRuntime.unregisterSession(key);
sessions.delete(key);
});
@@ -1030,6 +1106,7 @@ const make = (options?: AgentControllerLiveOptions) =>
yield* runMastra("deleteSession", () =>
bundle.controller.deleteSession({ resourceId: threadId }),
).pipe(Effect.ignoreCause({ log: true }));
+ toolRuntime.unregisterSession(threadId);
}
legacyResourceIdentity.clear();
sessions.clear();
@@ -1080,11 +1157,8 @@ function ThreadIdBrand(value: string): ThreadId {
return value as ThreadId;
}
-function approvalDecision(
- decision: ProviderApprovalDecision,
-): "approve" | "decline" | "always_allow_category" {
+function approvalDecision(decision: ProviderApprovalDecision): "approve" | "decline" {
if (decision === "decline" || decision === "cancel") return "decline";
- if (decision === "acceptAlways") return "always_allow_category";
return "approve";
}