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.
fix(server): disable executable tools in Claude metadata generation (#247)
Leo9aa75f5c6d96
diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.tsindex 3193f24cf..ca5a64cc0 100644--- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts+++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts@@ -35,13 +35,41 @@ function makeFakeClaudeBinary(dir: string) {yield* fs.writeFileString(stubPath,[- 'const args = process.argv.slice(2).join(" ");',+ "const argv = process.argv.slice(2);",+ 'const args = argv.join(" ");',+ 'const { realpathSync } = await import("node:fs");',"","function fail(message, code) {",' process.stderr.write(message + "\\n");'," process.exit(code);","}","",+ 'const permissionIndex = argv.indexOf("--permission-mode");',+ 'if (permissionIndex === -1 || argv[permissionIndex + 1] !== "dontAsk") {',+ ' fail("text generation must deny permission prompts", 12);',+ "}",+ 'const toolsIndex = argv.indexOf("--tools");',+ 'if (toolsIndex === -1 || argv[toolsIndex + 1] !== "") {',+ ' fail("text generation must receive an explicit empty tool set", 6);',+ "}",+ 'if (argv.includes("--dangerously-skip-permissions")) {',+ ' fail("text generation must not bypass permissions", 7);',+ "}",+ 'if (!argv.includes("--disable-slash-commands")) {',+ ' fail("text generation must disable skills", 8);',+ "}",+ 'if (!argv.includes("--strict-mcp-config")) {',+ ' fail("text generation must not load configured MCP servers", 9);',+ "}",+ 'const settingsIndex = argv.indexOf("--settings");',+ "if (settingsIndex === -1 || JSON.parse(argv[settingsIndex + 1]).disableAllHooks !== true) {",+ ' fail("text generation must disable hooks", 10);',+ "}",+ "const cwdMustNotBe = process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;",+ "if (cwdMustNotBe && realpathSync(process.cwd()) === realpathSync(cwdMustNotBe)) {",+ ' fail("text generation ran in the project directory", 11);',+ "}",+ "",'let stdinContent = "";',"if (!process.stdin.isTTY) {"," const chunks = [];",@@ -111,6 +139,7 @@ function withFakeClaudeEnv<A, E, R>(argsMustNotContain?: string;stdinMustContain?: string;configDirMustBe?: string;+ cwdMustNotBe?: string;claudeConfig?: Partial<ClaudeSettings>;},effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,@@ -128,6 +157,7 @@ function withFakeClaudeEnv<A, E, R>(const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;+ const previousCwdMustNotBe = process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;yield* Effect.acquireRelease(Effect.sync(() => {@@ -169,6 +199,12 @@ function withFakeClaudeEnv<A, E, R>(} else {delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;}++ if (input.cwdMustNotBe !== undefined) {+ process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = input.cwdMustNotBe;+ } else {+ delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;+ }}),() =>Effect.sync(() => {@@ -215,6 +251,12 @@ function withFakeClaudeEnv<A, E, R>(} else {process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe;}++ if (previousCwdMustNotBe === undefined) {+ delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;+ } else {+ process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = previousCwdMustNotBe;+ }}),);@@ -234,7 +276,7 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {body: "",},}),- argsMustContain: '--settings {"alwaysThinkingEnabled":false}',+ argsMustContain: '--settings {"disableAllHooks":true,"alwaysThinkingEnabled":false}',argsMustNotContain: "--effort",},(textGeneration) =>@@ -266,7 +308,7 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {body: "Body",},}),- argsMustContain: '--effort max --settings {"fastMode":true}',+ argsMustContain: '--effort max --settings {"disableAllHooks":true,"fastMode":true}',},(textGeneration) =>Effect.gen(function* () {@@ -290,33 +332,58 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {),);- it.effect("generates thread titles through the Claude provider", () =>+ it.effect(+ "generates thread titles outside the project with tools, skills, and hooks disabled",+ () =>+ withFakeClaudeEnv(+ {+ output: JSON.stringify({+ structured_output: {+ title:+ ' "Reconnect failures after restart because the session state does not recover" ',+ },+ }),+ cwdMustNotBe: process.cwd(),+ stdinMustContain: "/call-script",+ },+ (textGeneration) =>+ Effect.gen(function* () {+ const generated = yield* textGeneration.generateThreadTitle({+ cwd: process.cwd(),+ message: "/call-script",+ modelSelection: {+ instanceId: ProviderInstanceId.make("claudeAgent"),+ model: "claude-sonnet-4-6",+ },+ });++ expect(generated.title).toBe(+ sanitizeThreadTitle(+ '"Reconnect failures after restart because the session state does not recover"',+ ),+ );+ }),+ ),+ );++ it.effect("generates branch names from skill prompts without executable capabilities", () =>withFakeClaudeEnv({- output: JSON.stringify({- structured_output: {- title:- ' "Reconnect failures after restart because the session state does not recover" ',- },- }),- stdinMustContain: "Please investigate reconnect failures after restarting the session.",+ output: JSON.stringify({ structured_output: { branch: "call-script" } }),+ stdinMustContain: "/call-script",},(textGeneration) =>Effect.gen(function* () {- const generated = yield* textGeneration.generateThreadTitle({+ const generated = yield* textGeneration.generateBranchName({cwd: process.cwd(),- message: "Please investigate reconnect failures after restarting the session.",+ message: "/call-script",modelSelection: {instanceId: ProviderInstanceId.make("claudeAgent"),model: "claude-sonnet-4-6",},});- expect(generated.title).toBe(- sanitizeThreadTitle(- '"Reconnect failures after restart because the session state does not recover"',- ),- );+ expect(generated.branch).toBe("call-script");}),),);@@ -353,6 +420,100 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {}),);+ for (const verbose of [false, true]) {+ it.effect(`unwraps a JSON title in ${verbose ? "verbose" : "normal"} Claude output`, () => {+ const result = {+ type: "result",+ structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },+ };+ return withFakeClaudeEnv(+ { output: JSON.stringify(verbose ? [result] : result) },+ (textGeneration) =>+ Effect.gen(function* () {+ const generated = yield* textGeneration.generateThreadTitle({+ cwd: process.cwd(),+ message: "Refresh ev-stg APP ASG instances",+ modelSelection: {+ instanceId: ProviderInstanceId.make("claudeAgent"),+ model: "claude-sonnet-4-6",+ },+ });++ expect(generated.title).toBe("Refresh ev-stg APP ASG instances");+ }),+ );+ });+ }++ for (const previousTitle of [undefined, "Old thread title"]) {+ it.effect(+ `reads the result from verbose Claude output when ${previousTitle ? "regenerating" : "generating"} a title`,+ () =>+ withFakeClaudeEnv(+ {+ output: JSON.stringify([+ { type: "system", subtype: "init" },+ { type: "assistant", message: { content: [] } },+ { type: "user", message: { content: [] } },+ { type: "rate_limit_event" },+ {+ type: "result",+ subtype: "success",+ result: '{"title":"Refresh ev-stg APP ASG Instances"}',+ structured_output: { title: "Refresh ev-stg APP ASG Instances" },+ },+ ]),+ },+ (textGeneration) =>+ Effect.gen(function* () {+ const generated = yield* textGeneration.generateThreadTitle({+ cwd: process.cwd(),+ message: "Refresh ev-stg APP ASG instances",+ previousTitle,+ modelSelection: {+ instanceId: ProviderInstanceId.make("claudeAgent"),+ model: "claude-sonnet-4-6",+ },+ });++ expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");+ }),+ ),+ );+ }++ for (const [name, output] of [+ ["empty message array", []],+ ["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],+ ["invalid title", [{ type: "result", structured_output: { title: 42 } }]],+ [+ "final result without structured output",+ [+ { type: "result", structured_output: { title: "Earlier result" } },+ { type: "result", subtype: "error_max_structured_output_retries" },+ ],+ ],+ ] as const) {+ it.effect(`rejects verbose Claude output with ${name}`, () =>+ withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>+ Effect.gen(function* () {+ const error = yield* Effect.flip(+ textGeneration.generateThreadTitle({+ cwd: process.cwd(),+ message: "Name this thread",+ modelSelection: {+ instanceId: ProviderInstanceId.make("claudeAgent"),+ model: "claude-sonnet-4-6",+ },+ }),+ );++ expect(error._tag).toBe("TextGenerationError");+ }),+ ),+ );+ }+it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>withFakeClaudeEnv({diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.tsindex eedb0e0fe..5451dc33d 100644--- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts+++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts@@ -8,6 +8,7 @@* @module ClaudeTextGeneration*/import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import * as Option from "effect/Option";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";@@ -50,14 +51,21 @@ const CLAUDE_TIMEOUT_MS = 180_000;/*** Schema for the wrapper JSON returned by `claude -p --output-format json`.- * We only care about `structured_output`.+ * Verbose mode wraps the result in an array of conversation messages.*/const ClaudeOutputEnvelope = Schema.Struct({structured_output: Schema.Unknown,});+const ClaudeOutputMessage = Schema.Struct({+ type: Schema.String,+ structured_output: Schema.optionalKey(Schema.Unknown),+});+const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope);const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));-const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));+const decodeClaudeOutput = Schema.decodeEffect(+ Schema.fromJsonString(Schema.Union([ClaudeOutputEnvelope, Schema.Array(ClaudeOutputMessage)])),+);export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (claudeSettings: ClaudeSettings,@@ -65,6 +73,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fusecretsDir?: string,) {const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const fileSystem = yield* FileSystem.FileSystem;const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);const readStreamAsString = <E>(@@ -145,23 +154,32 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fuconst fastMode =fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;const settings = {+ disableAllHooks: true,...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),...(fastMode ? { fastMode: true } : {}),...(ultracode ? { ultracode: true } : {}),};- const settingsJson =- Object.keys(settings).length > 0- ? yield* encodeJsonForOperation(- operation,- settings,- "Failed to encode Claude CLI settings.",- )- : undefined;+ const settingsJson = yield* encodeJsonForOperation(+ operation,+ settings,+ "Failed to encode Claude CLI settings.",+ );const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {const requestEnvironment = secretsDir? subscriptionRuntimeEnvironment(secretsDir, "anthropic", claudeEnvironment): claudeEnvironment;+ // Titles need only the supplied prompt, not configuration from the checkout.+ const workingDirectory =+ operation === "generateThreadTitle"+ ? yield* fileSystem+ .makeTempDirectoryScoped({ prefix: "akeru-claude-title-" })+ .pipe(+ Effect.mapError((cause) =>+ normalizeCliError("claude", operation, cause, "Failed to create title directory"),+ ),+ )+ : cwd;const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath || "claude",[@@ -173,14 +191,21 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu"--model",resolveClaudeApiModelId(modelSelection),...(cliEffort ? ["--effort", cliEffort] : []),- ...(settingsJson ? ["--settings", settingsJson] : []),- "--dangerously-skip-permissions",+ "--settings",+ settingsJson,+ // Metadata prompts need no executable capabilities, even when they contain a skill name.+ "--tools",+ "",+ "--disable-slash-commands",+ "--strict-mcp-config",+ "--permission-mode",+ "dontAsk",],{ env: requestEnvironment },);const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {env: requestEnvironment,- cwd,+ cwd: workingDirectory,shell: spawnCommand.shell,stdin: {stream: Stream.encodeText(Stream.make(prompt)),@@ -238,7 +263,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu),);- const envelope = yield* decodeClaudeOutputEnvelope(rawStdout).pipe(+ const output = yield* decodeClaudeOutput(rawStdout).pipe(Effect.catchTags({SchemaError: (cause) =>Effect.fail(@@ -250,9 +275,12 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu),}),);+ const envelope = isClaudeOutputEnvelope(output)+ ? output+ : output.findLast((message) => message.type === "result");const decodeOutput = Schema.decodeEffect(outputSchemaJson);- return yield* decodeOutput(envelope.structured_output).pipe(+ return yield* decodeOutput(envelope?.structured_output).pipe(Effect.catchTags({SchemaError: (cause) =>Effect.fail(diff --git a/apps/server/src/textGeneration/TextGenerationPrompts.test.ts b/apps/server/src/textGeneration/TextGenerationPrompts.test.tsindex 47bd53340..ab3784111 100644--- a/apps/server/src/textGeneration/TextGenerationPrompts.test.ts+++ b/apps/server/src/textGeneration/TextGenerationPrompts.test.ts@@ -237,6 +237,35 @@ describe("buildThreadTitlePrompt", () => {});describe("sanitizeThreadTitle", () => {+ it.each([+ '{"title": "Refresh ev-stg APP ASG instances"}',+ '{\n "title": "Refresh ev-stg APP ASG instances"\n}',+ ])("unwraps a JSON title before normalizing: %s", (raw) => {+ expect(sanitizeThreadTitle(raw)).toBe("Refresh ev-stg APP ASG instances");+ });++ it.each([+ "Rolling ES Refresh ev-stg",+ "Fix {title} interpolation",+ '{"title": 42}',+ '{"subject": "Fix parsing"}',+ '{"title": "unfinished}',+ ])("preserves text that is not a JSON title: %s", (raw) => {+ expect(sanitizeThreadTitle(raw)).toBe(raw);+ });++ it("normalizes the extracted title", () => {+ expect(sanitizeThreadTitle('{"title": " Fix reconnect failures "}')).toBe(+ "Fix reconnect failures",+ );+ expect(sanitizeThreadTitle('{"title": " "}')).toBe("New chat");+ expect(+ sanitizeThreadTitle(+ '{"title": "Reconnect failures after restart because the session state does not recover"}',+ ),+ ).toBe("Reconnect failures after restart because the se...");+ });+it("truncates long titles with the shared sidebar-safe limit", () => {expect(sanitizeThreadTitle(diff --git a/apps/server/src/textGeneration/TextGenerationUtils.ts b/apps/server/src/textGeneration/TextGenerationUtils.tsindex 6a153c167..e0fbaac0d 100644--- a/apps/server/src/textGeneration/TextGenerationUtils.ts+++ b/apps/server/src/textGeneration/TextGenerationUtils.ts@@ -1,7 +1,11 @@import { TextGenerationError } from "@t3tools/contracts";+import * as Option from "effect/Option";import * as Schema from "effect/Schema";const isTextGenerationError = Schema.is(TextGenerationError);+const decodeJsonThreadTitle = Schema.decodeOption(+ Schema.fromJsonString(Schema.Struct({ title: Schema.String })),+);/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */export function toJsonSchemaObject(schema: Schema.Top): unknown {@@ -44,7 +48,10 @@ export function sanitizePrTitle(raw: string): string {/** Normalise a raw thread title to a compact single-line sidebar-safe label. */export function sanitizeThreadTitle(raw: string): string {- const normalized = raw+ // Unwrap a JSON-formatted title before truncation can cut off the closing brace.+ const decoded = decodeJsonThreadTitle(raw);+ const title = Option.isSome(decoded) ? decoded.value.title : raw;+ const normalized = title.trim().split(/\r?\n/g)[0]?.trim()diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.mdindex 7b44a96a4..7e6087158 100644--- a/docs/user/providers-claude.md+++ b/docs/user/providers-claude.md@@ -29,6 +29,10 @@ If a Claude chat fails because the login expired, Akeru names that cause insteadSign-in state belongs to one environment. Connect Claude again on each separate Akeru server thatshould use the account.+Claude Code's verbose mode can stay enabled when you use Claude for text generation, including+thread titles, branch names, commit messages, and pull request descriptions. On a remote connection,+Akeru uses the Claude configuration on the connected server.+## Continue a Claude chatAkeru keeps Claude's provider-specific session identity when a chat continues. Changing to an