Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Every thread of a bot runs with the bot's Claude settings and follows it to its working folder (#4014)

Milind Soni541a8a151a0e
diff --git a/apps/docs/content/docs/features/bots-and-tasks.mdx b/apps/docs/content/docs/features/bots-and-tasks.mdx
index 9c57b35a23..6211f49221 100644
--- a/apps/docs/content/docs/features/bots-and-tasks.mdx
+++ b/apps/docs/content/docs/features/bots-and-tasks.mdx
@@ -39,7 +39,11 @@ A thread can choose its own model in the chat header and its Ask/Auto setting in
All the bot's threads share its saved memory and skills; they do not automatically receive every sibling transcript. Folders are not separate accounts or privacy boundaries. Bot profiles can carry different access preferences, but app organization is not an operating-system sandbox.
-Threads can converse independently, but a physical computer, browser session, or shared project folder cannot safely have two agents changing it at once. OpenMausBot reports contention instead of allowing overlapping managed actions. New local-agent threads use separate working folders by default; existing pinned folders are retained.
+Threads can converse independently, but a physical computer, browser session, or shared project folder cannot safely have two agents changing it at once. OpenMausBot reports contention instead of allowing overlapping managed actions.
+
+A bot without a working folder gives each local-agent thread a folder of its own. Give the bot a working folder and its threads move there with their next message: each starts a new engine session that rereads the conversation, and files it already made stay in its old folder. A thread started in a folder you chose keeps that folder.
+
+A Claude bot has one settings file for all its threads: `.claude/settings.json` in its working folder, or in its own folder (`~/.openmausbot/workspaces/<bot id>/`) when it has none. Its hooks, plugins, permission rules and `env` apply in every thread, whatever folder the thread runs in; Claude Code reads the rest of the file only where the thread runs in that folder. A link in place of the file is not followed.
## Groups and teams
diff --git a/docs/verification/provider-recovery.md b/docs/verification/provider-recovery.md
index 20f6b09fa7..aae2746e59 100644
--- a/docs/verification/provider-recovery.md
+++ b/docs/verification/provider-recovery.md
@@ -23,7 +23,11 @@ node --experimental-strip-types scripts/verify-opencode-permissions.ts /absolute
- Claude must complete **two** turns using the selected account's personal
`apiKeyHelper`, and again with `settings.json`'s API key. All authenticated
model requests go to the fake local Anthropic endpoint. An unrelated
- personal SessionStart hook must not run. OMB retains project settings but
+ personal SessionStart hook must not run. The bot's own settings file, kept
+ outside the turn's folder, must run its Stop hook in that folder, and a field
+ in it Claude Code would refuse must not cost the turn its authentication
+ (Claude Code drops a whole settings file over one such field, and the bot's
+ settings ride in OMB's own `--settings` file). OMB retains project settings but
projects only account authentication from personal settings. Explicit OMB
credentials/endpoints take precedence as a pair.
- OpenCode must actually read a synthetic file **outside** its workspace in
diff --git a/scripts/verify-claude-auth-settings.ts b/scripts/verify-claude-auth-settings.ts
index e1b0bb2eda..7c6c3f0e75 100644
--- a/scripts/verify-claude-auth-settings.ts
+++ b/scripts/verify-claude-auth-settings.ts
@@ -11,8 +11,10 @@ assert.ok(process.argv[2], "Pass the absolute Claude CLI path");
const home = mkdtempSync(join(tmpdir(), "omb-claude-auth-fixture-"));
const account = join(home, ".claude");
const workspace = join(home, "workspace");
+const botSettings = join(home, "bot", ".claude", "settings.json");
mkdirSync(account);
mkdirSync(workspace);
+mkdirSync(join(home, "bot", ".claude"), { recursive: true });
process.env = {
HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: join(home, ".config"),
PATH: process.env.PATH, OMB_DATA_DIR: join(home, "omb"),
@@ -51,6 +53,11 @@ writeFileSync(join(account, "settings.json"), JSON.stringify({
env: { ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`, ...(apiKey ? { ANTHROPIC_API_KEY: "fixture-only-key" } : {}) },
hooks: { SessionStart: [{ hooks: [{ type: "command", command: `${JSON.stringify(process.execPath)} -e "require('fs').writeFileSync('hook-ran', 'unexpected')"` }] }] },
}), { mode: 0o600 });
+// The bot's own settings, with a field Claude Code would refuse: it must not take OMB's own settings down with it.
+writeFileSync(botSettings, JSON.stringify({
+ model: 123,
+ hooks: { Stop: [{ hooks: [{ type: "command", command: `${JSON.stringify(process.execPath)} -e "require('fs').writeFileSync('bot-hook-ran', 'ran')"` }] }] },
+}));
const { ensureDirs } = await import("../server/config.ts");
ensureDirs();
const { ClaudeDriver } = await import("../server/drivers/claude.ts");
@@ -59,14 +66,15 @@ const provider = await ClaudeDriver.create({ instanceId: "fixture", displayName:
const recorder = recordEvents(provider.adapter);
try {
for (let i = 0; i < 2; i++) {
- const { turnId } = await provider.adapter.sendTurn({ threadId: "fixture-thread", text: "Reply briefly. No tools.", cwd: workspace, model: "claude-sonnet-4-6", approvalMode: "ask" });
+ const { turnId } = await provider.adapter.sendTurn({ threadId: "fixture-thread", text: "Reply briefly. No tools.", cwd: workspace, botSettingsFile: botSettings, model: "claude-sonnet-4-6", approvalMode: "ask" });
const done = await recorder.until(event => event.type === "turn.completed" && event.turnId === turnId, 40_000);
assert.equal((done as { ok: boolean }).ok, true, JSON.stringify(recorder.events.filter(event => event.type === "runtime.error")));
}
assert.ok(requests.length >= 2);
assert.ok(requests.every(request => request.authenticated));
assert.equal(existsSync(join(workspace, "hook-ran")), false, "Personal hooks must stay isolated");
- console.log(JSON.stringify({ ok: true, turns: 2, authentication: apiKey ? "settings env key" : "apiKeyHelper", authenticated: true, settingsIsolated: true, endpoint: "loopback only" }));
+ assert.equal(existsSync(join(workspace, "bot-hook-ran")), true, "The bot's own hooks must run in a folder that has none");
+ console.log(JSON.stringify({ ok: true, turns: 2, authentication: apiKey ? "settings env key" : "apiKeyHelper", authenticated: true, settingsIsolated: true, botHooksRan: true, endpoint: "loopback only" }));
} finally {
recorder.stop();
await provider.dispose();
diff --git a/server/bot-cwd.test.ts b/server/bot-cwd.test.ts
index 3f30475ce2..515fee01e3 100644
--- a/server/bot-cwd.test.ts
+++ b/server/bot-cwd.test.ts
@@ -3,7 +3,7 @@ import { homedir, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
-import { inMyFolderCwd, sharedProjectFolder, validateBotCwd } from "./bot-cwd.ts";
+import { folderToFollow, inMyFolderCwd, sharedProjectFolder, validateBotCwd } from "./bot-cwd.ts";
const dir = mkdtempSync(join(tmpdir(), "omb-cwd-"));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
@@ -72,3 +72,27 @@ describe("inMyFolderCwd", () => {
expect(inMyFolderCwd(true, true, privateFolder, data)).toEqual({ error: expect.stringMatching(/no project folder/) });
});
});
+
+describe("folderToFollow", () => {
+ const own = join(dir, "omb-data", "task-workspaces", "bot", "thread");
+ const bot = { id: "bot", cwd: join(dir, "omb-data-site") };
+ const folders = { worksInFolders: true, keepsPrivateFolder: false };
+
+ it("moves a thread from its own folder to the working folder its bot has been given", () => {
+ expect(folderToFollow(bot, "thread", own, folders)).toBe(bot.cwd);
+ });
+
+ it("leaves a thread where it is when the bot has no working folder or the thread is not in its own folder", () => {
+ expect(folderToFollow({ id: "bot" }, "thread", own, folders)).toBeUndefined();
+ expect(folderToFollow(bot, "thread", join(dir, "chosen"), folders)).toBeUndefined();
+ expect(folderToFollow(bot, "thread", bot.cwd, folders)).toBeUndefined();
+ expect(folderToFollow(bot, "thread", join(dir, "omb-data", "task-workspaces", "bot", "other-thread"), folders)).toBeUndefined();
+ expect(folderToFollow(bot, "thread", null, folders)).toBeUndefined();
+ expect(folderToFollow(bot, "thread", undefined, folders)).toBeUndefined();
+ });
+
+ it("never moves a conversation that keeps a private folder, or one on an engine that works in no folder", () => {
+ expect(folderToFollow(bot, "thread", own, { ...folders, keepsPrivateFolder: true })).toBeUndefined();
+ expect(folderToFollow(bot, "thread", own, { ...folders, worksInFolders: false })).toBeUndefined();
+ });
+});
diff --git a/server/bot-cwd.ts b/server/bot-cwd.ts
index a4688cc1e4..13e629ae87 100644
--- a/server/bot-cwd.ts
+++ b/server/bot-cwd.ts
@@ -2,6 +2,8 @@ import { statSync } from "node:fs";
import { homedir } from "node:os";
import { isAbsolute, relative, resolve } from "node:path";
+import { isOwnThreadFolder } from "../shared/thread-folder.ts";
+
export type CwdValidation = { ok: true; cwd: string | null } | { ok: false; error: string };
export function validateBotCwd(input: unknown): CwdValidation {
@@ -22,6 +24,14 @@ export function validateBotCwd(input: unknown): CwdValidation {
return { ok: true, cwd };
}
+/** The working folder a thread moves to on this turn: its bot's, while the thread is still in its own folder. Never for a
+ * conversation that keeps a private folder (a Cloud guest's), nor for an engine that works in no folder. */
+export function folderToFollow(bot: { id: string; cwd?: string }, threadId: string, threadCwd: string | null | undefined,
+ opts: { worksInFolders: boolean; keepsPrivateFolder: boolean }): string | undefined {
+ if (!bot.cwd || !opts.worksInFolders || opts.keepsPrivateFolder) return undefined;
+ return isOwnThreadFolder(threadCwd, bot.id, threadId) ? bot.cwd : undefined;
+}
+
/** A conversation's folder a teammate may be sent to: one that still exists, outside OpenMausBot's own data (a bot's private workspace). */
export function sharedProjectFolder(cwd: string | null | undefined, dataDir: string): string | undefined {
const checked = cwd ? validateBotCwd(cwd) : undefined;
diff --git a/server/cloud-lending-memory.e2e.test.ts b/server/cloud-lending-memory.e2e.test.ts
index f034ab0569..5909b06ebf 100644
--- a/server/cloud-lending-memory.e2e.test.ts
+++ b/server/cloud-lending-memory.e2e.test.ts
@@ -863,3 +863,25 @@ it("no command the owner saved answers for a conversation a guest left behind: i
again.close();
await stop(bot, guests);
}, 60_000);
+
+it("a conversation a guest left behind keeps its private folder when the owner gives the bot a working folder; the owner's own moves there", async () => {
+ const bot = await newBot("Working folder", "done");
+ const guests = await guestThread(bot);
+ const mine = await newThread(bot);
+ const idle = (threadId: string) => expect.poll(async () => ((await api("GET", "/api/bots?messages=0", { token: owner })).body.bots as any[])
+ .find((candidate) => candidate.id === bot.id).tasks.find((task: any) => task.threadId === threadId).busy, { timeout: 15_000 }).toBeFalsy();
+ const cwdOf = async (threadId: string, text: string) => {
+ rmSync(dumpOf("done"), { force: true });
+ await say(owner, bot, text, threadId);
+ const { cwd } = await dumped(dumpOf("done"));
+ await idle(threadId);
+ return realpathSync(cwd);
+ };
+ const guestFolder = await cwdOf(guests, "Hello.");
+ expect(guestFolder).toBe(realpathSync(join(home, ".openmausbot", "task-workspaces", bot.id, guests)));
+ expect(await cwdOf(mine, "Hello.")).toBe(realpathSync(join(home, ".openmausbot", "task-workspaces", bot.id, mine)));
+ const project = realpathSync(mkdtempSync(join(home, "project-")));
+ expect((await api("PATCH", `/api/bots/${bot.id}`, { token: owner, body: { cwd: project } })).status).toBe(200);
+ expect(await cwdOf(guests, "Hello again.")).toBe(guestFolder);
+ expect(await cwdOf(mine, "Hello again.")).toBe(project);
+}, 60_000);
diff --git a/server/cloud-team.e2e.test.ts b/server/cloud-team.e2e.test.ts
index e3852b4404..c18390e05a 100644
--- a/server/cloud-team.e2e.test.ts
+++ b/server/cloud-team.e2e.test.ts
@@ -2,7 +2,7 @@
// signed member claims, the audience rule on chats, memory, recall and files, the team's connected apps, and a My Cloud
// that refuses a team claim. The engine is the synthetic Claude CLI, so this proves the plumbing, not a model's judgement.
import { randomBytes } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterAll, beforeAll, expect, it } from "vitest";
import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";
@@ -298,3 +298,22 @@ it("a person's own connected apps cannot be brought into the team, and the team'
const seen = await turn(cleo, await newThread(cleo, "Cleo and Scout"), "Check my mail.");
expect(Object.keys(seen.mcpConfig.mcpServers)).toContain("composio");
}, hostTimeout(120_000));
+
+it("a member's private chat keeps its own folder when the team's bot is given a working folder; the Owner's own thread moves there", async () => {
+ const ownFolder = (threadId: string) => realpathSync(join(team.home, ".openmausbot", "task-workspaces", bot.id, threadId));
+ const cwdOf = async (token: string, threadId: string, text: string) => realpathSync((await turn(token, threadId, text) as unknown as { cwd: string }).cwd);
+ const hers = await newThread(ada, "Ada's own folder");
+ const olives = await newThread(owner, "Olive's own folder");
+ expect(await cwdOf(ada, hers, "Hello.")).toBe(ownFolder(hers));
+ expect(await cwdOf(owner, olives, "Hello.")).toBe(ownFolder(olives));
+ const project = join(team.home, "team-project");
+ mkdirSync(project, { recursive: true });
+ const given = await team.as(owner, "PATCH", `/api/bots/${bot.id}`, { cwd: project });
+ expect(given.status, JSON.stringify(given.body)).toBe(200);
+ try {
+ expect(await cwdOf(ada, hers, "Hello again.")).toBe(ownFolder(hers));
+ expect(await cwdOf(owner, olives, "Hello again.")).toBe(realpathSync(project));
+ } finally {
+ expect((await team.as(owner, "PATCH", `/api/bots/${bot.id}`, { cwd: null })).status).toBe(200);
+ }
+}, hostTimeout(120_000));
diff --git a/server/contracts.ts b/server/contracts.ts
index 36028ef04b..73d583e41f 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -199,6 +199,9 @@ export interface SendTurnInput {
mcpFromUserConfig?: boolean;
/** Claude Code loads the person's own `~/.claude/skills` from this folder's `.claude/skills` (`--add-dir`). */
userSkillsDir?: string;
+ /** The bot's own Claude Code settings: `.claude/settings.json` in its working folder, else in its own folder. A Claude
+ * turn in any other folder takes their hooks, plugins, permission rules and env. */
+ botSettingsFile?: string;
/** Per-call ceiling (ms) for this turn's MCP tools; absent is the driver's default (10 min). */
mcpCallTimeoutMs?: number;
/** Times an API-model turn that answers after a failed tool call is sent back to re-run it (`loopGuard.correctiveRounds`); never after a denial. */
diff --git a/server/drivers/claude-bot-settings.test.ts b/server/drivers/claude-bot-settings.test.ts
new file mode 100644
index 0000000000..5a50a7037f
--- /dev/null
+++ b/server/drivers/claude-bot-settings.test.ts
@@ -0,0 +1,113 @@
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+import { botSettingsFor, withBotSettings } from "./claude-bot-settings.ts";
+
+const root = mkdtempSync(join(tmpdir(), "omb-bot-settings-"));
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+let count = 0;
+/** A bot folder holding `settings` and an empty thread folder beside it. */
+function folders(settings: unknown): { file: string; bot: string; thread: string } {
+ const base = join(root, String(count++)), bot = join(base, "bot"), thread = join(base, "thread");
+ mkdirSync(join(bot, ".claude"), { recursive: true });
+ mkdirSync(thread);
+ const file = join(bot, ".claude", "settings.json");
+ writeFileSync(file, typeof settings === "string" ? settings : JSON.stringify(settings));
+ return { file, bot, thread };
+}
+
+const guard = { matcher: "Bash", hooks: [{ type: "command", command: "/opt/guards/no-force-push.sh", timeout: 10 }] };
+
+describe("botSettingsFor", () => {
+ it("takes the bot's hooks, plugins, permission rules and env", () => {
+ const settings = {
+ hooks: { PreToolUse: [guard] },
+ enabledPlugins: { "guard@team": true, "notes@team": false },
+ extraKnownMarketplaces: { team: { source: { source: "directory", path: "/opt/marketplace" } } },
+ permissions: { allow: ["Bash(npm test)"], ask: ["Bash(git push:*)"], deny: ["Read(./.env)"], additionalDirectories: ["/opt/shared"] },
+ env: { GUARD_LEVEL: "strict" },
+ };
+ const { file, thread } = folders(settings);
+ expect(botSettingsFor(file, thread, {})).toEqual(settings);
+ });
+
+ it("leaves behind every other field, and each entry Claude Code would refuse, so OpenMausBot's own settings still load", () => {
+ const { file, thread } = folders({
+ model: 123, statusLine: "x", outputStyle: 5, apiKeyHelper: "echo key", cleanupPeriodDays: "30", disableAllHooks: true,
+ hooks: { PreToolUse: [guard, { matcher: 5, hooks: "x" }, { hooks: [{ command: "no type" }] }], Stop: "nope" },
+ enabledPlugins: { "guard@team": true, "typo@team": "yes" },
+ extraKnownMarketplaces: { team: { source: { source: "directory", path: "/opt/marketplace" } }, broken: "x" },
+ permissions: { allow: "Bash", deny: ["Read(./.env)", 7], defaultMode: "bypassPermissions", disableBypassPermissionsMode: "disable" },
+ env: { GUARD_LEVEL: "strict", RETRIES: 3, PATH: "/somewhere/else" },
+ });
+ expect(botSettingsFor(file, thread, { PATH: "/usr/bin" })).toEqual({
+ hooks: { PreToolUse: [guard] },
+ enabledPlugins: { "guard@team": true },
+ extraKnownMarketplaces: { team: { source: { source: "directory", path: "/opt/marketplace" } } },
+ permissions: { deny: ["Read(./.env)"] },
+ env: { GUARD_LEVEL: "strict" },
+ });
+ });
+
+ it("takes nothing from a missing file, a file that is not a JSON object, or no file at all", () => {
+ const { thread } = folders({});
+ for (const content of ["{ not json", "[1, 2]", "\"text\"", "null"]) {
+ expect(botSettingsFor(folders(content).file, thread, {})).toEqual({});
+ }
+ expect(botSettingsFor(join(root, "missing", ".claude", "settings.json"), thread, {})).toEqual({});
+ expect(botSettingsFor(undefined, thread, {})).toEqual({});
+ });
+
+ it("leaves the settings of the folder the turn runs in to Claude Code, which reads them itself", () => {
+ const { file, bot } = folders({ hooks: { PreToolUse: [guard] } });
+ expect(botSettingsFor(file, bot, {})).toEqual({});
+ });
+
+ it.skipIf(process.platform === "win32")("never reads through a link the bot could have planted, file or folder", () => {
+ const outside = folders({ env: { SECRET: "from outside the bot's folder" } });
+ const linkedFile = join(root, "linked-file");
+ mkdirSync(join(linkedFile, ".claude"), { recursive: true });
+ symlinkSync(outside.file, join(linkedFile, ".claude", "settings.json"));
+ expect(botSettingsFor(join(linkedFile, ".claude", "settings.json"), outside.thread, {})).toEqual({});
+ const linkedFolder = join(root, "linked-folder");
+ mkdirSync(linkedFolder);
+ symlinkSync(join(outside.bot, ".claude"), join(linkedFolder, ".claude"));
+ expect(botSettingsFor(join(linkedFolder, ".claude", "settings.json"), outside.thread, {})).toEqual({});
+ });
+
+ it.skipIf(process.platform === "win32")("passes over a FIFO in place of the file without waiting on it", () => {
+ const bot = join(root, "fifo");
+ mkdirSync(join(bot, ".claude"), { recursive: true });
+ expect(spawnSync("mkfifo", [join(bot, ".claude", "settings.json")]).status).toBe(0);
+ expect(botSettingsFor(join(bot, ".claude", "settings.json"), folders({}).thread, {})).toEqual({});
+ });
+});
+
+describe("withBotSettings", () => {
+ it("merges as Claude Code merges a project's settings under --settings: lists join, OpenMausBot's own values win", () => {
+ const ombStop = { matcher: "", hooks: [{ type: "command", command: "omb-hook", timeout: 5 }] };
+ const botStop = { hooks: [{ type: "command", command: "/opt/notify.sh" }] };
+ expect(withBotSettings(
+ { hooks: { PreToolUse: [guard], Stop: [botStop] }, env: { GUARD_LEVEL: "strict", ENABLE_TOOL_SEARCH: "false" }, enabledPlugins: { "guard@team": true } },
+ { hooks: { Stop: [ombStop], PostToolUse: [ombStop] }, env: { ENABLE_TOOL_SEARCH: "true" }, claudeMdExcludes: ["/home/ada/.claude/CLAUDE.md"] },
+ )).toEqual({
+ hooks: { PreToolUse: [guard], Stop: [botStop, ombStop], PostToolUse: [ombStop] },
+ env: { GUARD_LEVEL: "strict", ENABLE_TOOL_SEARCH: "true" },
+ enabledPlugins: { "guard@team": true },
+ claudeMdExcludes: ["/home/ada/.claude/CLAUDE.md"],
+ });
+ expect(withBotSettings({ permissions: { deny: ["Read(./.env)", "WebFetch"] } }, { permissions: { deny: ["WebFetch", "Bash"] } }))
+ .toEqual({ permissions: { deny: ["Read(./.env)", "WebFetch", "Bash"] } });
+ expect(withBotSettings({}, { env: { ENABLE_TOOL_SEARCH: "true" } })).toEqual({ env: { ENABLE_TOOL_SEARCH: "true" } });
+ });
+
+ it("keeps a key named __proto__ as data", () => {
+ const merged = withBotSettings(JSON.parse('{"env": {"__proto__": {"polluted": "yes"}}}'), { env: { A: "1" } });
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ expect(Object.getPrototypeOf(merged.env)).toBe(Object.prototype);
+ });
+});
diff --git a/server/drivers/claude-bot-settings.ts b/server/drivers/claude-bot-settings.ts
new file mode 100644
index 0000000000..0730ad0741
--- /dev/null
+++ b/server/drivers/claude-bot-settings.ts
@@ -0,0 +1,76 @@
+// A bot's own Claude Code settings (`.claude/settings.json` in its working folder, else in its own folder) for a turn
+// that runs in another folder: a thread's own folder, a room's, or one chosen for the thread.
+import { closeSync, constants, fstatSync, openSync, readFileSync, realpathSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+type Settings = Record<string, unknown>;
+
+/** Far above any real settings file; only bounds what is read for a turn. */
+const MAX_BYTES = 1024 * 1024;
+
+const isObject = (value: unknown): value is Settings => typeof value === "object" && value !== null && !Array.isArray(value);
+
+/** `value`'s entries that `keep` maps to something, or undefined when none does. */
+function entriesOf(value: unknown, keep: (entry: unknown, name: string) => unknown): Settings | undefined {
+ if (!isObject(value)) return undefined;
+ const entries = Object.entries(value).map(([name, entry]) => [name, keep(entry, name)] as const).filter(([, entry]) => entry !== undefined);
+ return entries.length ? Object.fromEntries(entries) : undefined;
+}
+
+const isMatcher = (entry: unknown) => isObject(entry) && (entry.matcher === undefined || typeof entry.matcher === "string") &&
+ Array.isArray(entry.hooks) && entry.hooks.every((hook) => isObject(hook) && typeof hook.type === "string");
+
+const nonEmpty = <T>(list: T[]): T[] | undefined => list.length ? list : undefined;
+
+/** null when there is nothing to take: no regular file there, not JSON, or the turn's own folder's, which Claude Code reads itself. */
+function readBotSettings(file: string, cwd: string): unknown {
+ try {
+ const real = realpathSync(file);
+ // Never through a link: the bot can write this folder, and the file is read here, outside any box it runs in.
+ if (real !== join(realpathSync(dirname(dirname(file))), ".claude", "settings.json")) return null;
+ try {
+ if (realpathSync(join(cwd, ".claude", "settings.json")) === real) return null;
+ } catch {}
+ // O_NONBLOCK: a planted FIFO must not hang the open.
+ const fd = openSync(real, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK));
+ try {
+ const stat = fstatSync(fd);
+ return stat.isFile() && stat.size <= MAX_BYTES ? JSON.parse(readFileSync(fd, "utf8")) : null;
+ } finally {
+ closeSync(fd);
+ }
+ } catch {
+ return null;
+ }
+}
+
+/** What a turn takes from the bot's settings file: its hooks, plugins, permission rules and env. They ride in
+ * OpenMausBot's own --settings file (Claude Code takes one), and Claude Code 2.1.312 drops a whole settings file when a
+ * field it knows has the wrong type, so only these, each checked, come along. An env name the turn's process already
+ * has keeps OpenMausBot's value. */
+export function botSettingsFor(file: string | undefined, cwd: string, processEnv: Record<string, string | undefined>): Settings {
+ const parsed = file ? readBotSettings(file, cwd) : null;
+ if (!isObject(parsed)) return {};
+ const carried: Settings = {
+ hooks: entriesOf(parsed.hooks, (matchers) => Array.isArray(matchers) ? nonEmpty(matchers.filter(isMatcher)) : undefined),
+ enabledPlugins: entriesOf(parsed.enabledPlugins, (on) =>
+ typeof on === "boolean" || (Array.isArray(on) && on.every((item) => typeof item === "string")) ? on : undefined),
+ extraKnownMarketplaces: entriesOf(parsed.extraKnownMarketplaces, (marketplace) => isObject(marketplace) ? marketplace : undefined),
+ permissions: entriesOf(parsed.permissions, (rules, key) => ["allow", "ask", "deny", "additionalDirectories"].includes(key) && Array.isArray(rules)
+ ? nonEmpty(rules.filter((rule) => typeof rule === "string")) : undefined),
+ env: entriesOf(parsed.env, (value, name) => typeof value === "string" && !Object.hasOwn(processEnv, name) ? value : undefined),
+ };
+ return Object.fromEntries(Object.entries(carried).filter(([, value]) => value !== undefined));
+}
+
+/** Claude Code's rule for two settings sources, `own` the later: objects merge, lists join, a value replaces. */
+export function withBotSettings(bot: Settings, own: Settings): Settings {
+ return merged(bot, own) as Settings;
+}
+
+function merged(base: unknown, over: unknown): unknown {
+ if (Array.isArray(base) && Array.isArray(over)) return [...base, ...over.filter((item) => !base.includes(item))];
+ if (!isObject(base) || !isObject(over)) return over;
+ return Object.fromEntries([...new Set([...Object.keys(base), ...Object.keys(over)])].map((key) => [key,
+ !Object.hasOwn(over, key) ? base[key] : Object.hasOwn(base, key) ? merged(base[key], over[key]) : over[key]]));
+}
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index a167987012..e4c6b8b92a 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -1555,6 +1555,88 @@ describe("ClaudeDriver turns (fake CLI)", () => {
expect(JSON.parse(readFileSync(dump, "utf8")).argv).not.toContain("--autocompact");
});
+ describe("the bot's own settings file", () => {
+ const guard = { matcher: "Bash", hooks: [{ type: "command", command: "/opt/guards/no-force-push.sh" }] };
+ const botFolders = (name: string, settings: unknown) => {
+ const bot = join(scratch, `${name}-bot`), thread = join(scratch, `${name}-thread`);
+ mkdirSync(join(bot, ".claude"), { recursive: true });
+ mkdirSync(thread);
+ const file = join(bot, ".claude", "settings.json");
+ writeFileSync(file, JSON.stringify(settings));
+ return { bot, thread, file };
+ };
+
+ it("reaches a turn in a thread's own folder, beside OpenMausBot's own settings", async () => {
+ const dump = join(scratch, "bot-settings.json");
+ process.env.FAKE_CLAUDE_DUMP = dump;
+ await create();
+ const { thread, file } = botFolders("reach", {
+ hooks: { PreToolUse: [guard], Stop: [{ hooks: [{ type: "command", command: "/opt/guards/notify.sh" }] }] },
+ enabledPlugins: { "guard@team": true },
+ permissions: { deny: ["Read(./.env)"], defaultMode: "bypassPermissions" },
+ env: { GUARD_LEVEL: "strict", ENABLE_TOOL_SEARCH: "false" },
+ model: 123,
+ });
+ await instance.adapter.sendTurn({ threadId: "t-bot-settings", botId: "b-settings", text: "hi", cwd: thread, botSettingsFile: file,
+ integrations: { hooks: { url: "http://127.0.0.1:1/hooks", token: "bearer" } } });
+ await recorder.until((e) => e.type === "turn.completed");
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ expect(realpathSync(seen.cwd)).toBe(realpathSync(thread));
+ expect(seen.settings.hooks.PreToolUse).toEqual([guard]);
+ expect(seen.settings.hooks.Stop).toHaveLength(2);
+ expect(seen.settings.hooks.Stop[0]).toEqual({ hooks: [{ type: "command", command: "/opt/guards/notify.sh" }] });
+ expect(Object.keys(seen.settings.hooks)).toEqual(expect.arrayContaining(Object.keys(claudeHookSettings("/helper.ts"))));
+ expect(seen.settings.enabledPlugins).toEqual({ "guard@team": true });
+ expect(seen.settings.permissions).toEqual({ deny: ["Read(./.env)"] });
+ expect(seen.settings.env).toMatchObject({ GUARD_LEVEL: "strict", ENABLE_TOOL_SEARCH: "true" });
+ expect(seen.settings).not.toHaveProperty("model");
+ expect(seen.settings.claudeMdExcludes).toEqual([join(homedir(), ".claude", "CLAUDE.md")]);
+ });
+
+ it("is left to Claude Code when the turn runs in the folder that holds it", async () => {
+ const dump = join(scratch, "bot-settings-own-folder.json");
+ process.env.FAKE_CLAUDE_DUMP = dump;
+ await create();
+ const { bot, file } = botFolders("own-folder", { hooks: { PreToolUse: [guard] }, enabledPlugins: { "guard@team": true } });
+ await instance.adapter.sendTurn({ threadId: "t-bot-settings-own", text: "hi", cwd: bot, botSettingsFile: file });
+ await recorder.until((e) => e.type === "turn.completed");
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ expect(seen.settings).not.toHaveProperty("enabledPlugins");
+ expect(seen.settings).not.toHaveProperty("hooks");
+ });
+
+ it("never reaches a guest's turn", async () => {
+ const dump = join(scratch, "bot-settings-guest.json");
+ process.env.FAKE_CLAUDE_DUMP = dump;
+ await create("echo", { FAKE_CLAUDE_VERSION: "2.1.284" });
+ const { thread, file } = botFolders("guest", { hooks: { PreToolUse: [guard] }, env: { GUARD_LEVEL: "strict" } });
+ await instance.adapter.sendTurn({ threadId: "t-bot-settings-guest", text: "hi", cwd: thread, botSettingsFile: file, approvalMode: "ask", guestConfined: true });
+ await recorder.until((e) => e.type === "turn.completed");
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ expect(seen.argv).toContain("--restricted");
+ expect(seen.settings).not.toHaveProperty("hooks");
+ expect(seen.settings.env).not.toHaveProperty("GUARD_LEVEL");
+ });
+
+ it("starts a new process on the turn after it changes, and keeps the warm one while it does not", async () => {
+ const dump = join(scratch, "bot-settings-warm.json");
+ process.env.FAKE_CLAUDE_DUMP = dump;
+ await create();
+ const { thread, file } = botFolders("warm", { enabledPlugins: { "guard@team": true } });
+ const turn = async (text: string) => {
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-bot-settings-warm", text, cwd: thread, botSettingsFile: file });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId);
+ return JSON.parse(readFileSync(dump, "utf8"));
+ };
+ const first = await turn("one");
+ expect((await turn("two")).pid).toBe(first.pid);
+ writeFileSync(file, JSON.stringify({ enabledPlugins: { "guard@team": true, "review@team": true } }));
+ const changed = await turn("three");
+ expect(changed.pid).not.toBe(first.pid);
+ expect(changed.settings.enabledPlugins).toEqual({ "guard@team": true, "review@team": true });
+ });
+ });
+
it("launches isolated from the machine's own Claude Code configuration", async () => {
await create();
const dump = join(scratch, "isolation.json");
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index f44d590dd0..ca2ee2e8ee 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -13,6 +13,7 @@ import { augmentedPath } from "../env-path.ts";
import { brokerSocketPath, cliVersionReader, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts";
import { claudeAuthStatus } from "./claude-auth-status.ts";
import { projectMcpServers } from "./claude-project-mcp.ts";
+import { botSettingsFor, withBotSettings } from "./claude-bot-settings.ts";
import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";
import { claudeAuthFailure, claudeAuthRecovery } from "./claude-auth-recovery.ts";
import { claudeModelExtras } from "./claude-model-extras.ts";
@@ -1203,16 +1204,19 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
const cwd = turn.cwd ?? homedir();
// Every MCP server without alwaysLoad loads on demand behind ToolSearch (claude-tool-search.ts).
const toolSearch = claudeToolSearchSetting(cwd, env);
- const settings: Record<string, unknown> = { ...authSettings, env: { ...authSettings.env, ENABLE_TOOL_SEARCH: toolSearch } };
+ const own: Record<string, unknown> = { ...authSettings, env: { ...authSettings.env, ENABLE_TOOL_SEARCH: toolSearch } };
// Project-only settings still find the personal memory via ancestors when the bot lives under HOME.
- if (isolated) settings.claudeMdExcludes = [join(homedir(), ".claude", "CLAUDE.md")];
- if (hooks) settings.hooks = claudeHookSettings(HOOK_HELPER_PATH);
- if (turn.guestConfined) settings.permissions = GUEST_CLAUDE_PERMISSIONS;
+ if (isolated) own.claudeMdExcludes = [join(homedir(), ".claude", "CLAUDE.md")];
+ if (hooks) own.hooks = claudeHookSettings(HOOK_HELPER_PATH);
+ if (turn.guestConfined) own.permissions = GUEST_CLAUDE_PERMISSIONS;
+ // Approvals and browser credentials expire at the turn boundary; native background workers must not outlive it.
+ env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = "1";
+ // Never for a guest: --restricted leaves project settings out, and a hook is a command.
+ const botSettings = turn.guestConfined ? {} : botSettingsFor(turn.botSettingsFile, cwd, env);
+ const settings = withBotSettings(botSettings, own);
const authSettingsPath = mcpConfigPath && Object.keys(settings).length
? join(dirname(mcpConfigPath), "auth-settings.json") : null;
if (authSettingsPath) args.push("--settings", authSettingsPath);
- // Approvals and browser credentials expire at the turn boundary; native background workers must not outlive it.
- env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = "1";
const commandCwd = permissionLaunchCwd(cwd);
const privateFileFlags = new Set(["--mcp-config", "--settings"]);
const keyArgs = args.filter((a, i) => !privateFileFlags.has(a) && !privateFileFlags.has(args[i - 1] ?? ""));
@@ -1226,6 +1230,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
configDir: env.CLAUDE_CONFIG_DIR ?? null,
hooks: Boolean(hooks),
toolSearch,
+ botSettings: createHash("sha256").update(JSON.stringify(botSettings)).digest("hex"),
// Rotating an account's key/helper must not reuse the old process.
auth: createHash("sha256").update(JSON.stringify({
settings: authSettings,
diff --git a/server/index.test.ts b/server/index.test.ts
index 72a65e432c..040e3ba83e 100644
--- a/server/index.test.ts
+++ b/server/index.test.ts
@@ -2788,6 +2788,34 @@ describe("harness HTTP API", () => {
}
});
+ it("takes a created operator's role description up to 4000 characters, and says what to do with a longer one", async () => {
+ const chief = (await api("POST", "/api/bots")).body.bot;
+ let createdId: string | undefined;
+ try {
+ expect((await api("PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: true, approvalMode: "ask" })).status).toBe(200);
+ const token = await mintTestCapability(BASE, chief.id, chief.threadId);
+ const create = async (name: string, instructions: string) => {
+ const response = await fetch(`${BASE}/api/internal/create-bot`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify({ fromBotId: chief.id, fromThreadId: chief.threadId, name, role: "Analyst", instructions }),
+ });
+ return { status: response.status, body: await response.json() as { id?: string; error?: string } };
+ };
+ const role = `You own the weekly numbers.\n${"Check every figure against its source and say where it came from. ".repeat(80)}`.slice(0, 3999) + ".";
+ const made = await create(`Analyst ${chief.id}`, role);
+ expect(made.status, JSON.stringify(made.body)).toBe(201);
+ createdId = made.body.id;
+ const state = (await api("GET", "/api/bots?messages=0")).body;
+ expect(state.bots.find((bot: { id?: string }) => bot.id === createdId)?.soul).toBe(role);
+ const longer = await create(`Longer analyst ${chief.id}`, `${role}x`);
+ expect(longer).toEqual({ status: 400, body: { error: "instructions must be at most 4000 characters; these are 4001. Shorten them to what this bot does and how it works, or create it with propose_team_setup, where soul takes up to 24000 bytes." } });
+ } finally {
+ if (createdId) await api("DELETE", `/api/bots/${createdId}`);
+ await api("DELETE", `/api/bots/${chief.id}`);
+ }
+ });
+
it("tells the Chief, and the bot in its own chat, when a bot it adds takes the person's own name", async () => {
const chief = (await api("POST", "/api/bots")).body.bot;
const profile = (await api("GET", "/api/config")).body.profile as { name?: string } | undefined;
diff --git a/server/index.ts b/server/index.ts
index b0b367d273..4265d76aef 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -61,7 +61,7 @@ import * as checkpoints from "./checkpoints.ts";
import { commandReceipt } from "./commands.ts";
import { buildTurnDigest, coverageForDriver, digestPromptLine, renderDigest, toolEvidence } from "./digest.ts";
import { appendDecision, bindDecisionRetention, decisionRetentionDays, flushDecisionLog, pruneDecisions, withDecisionActor, type DecisionActor, type DecisionVia } from "./decision-log.ts";
-import { inMyFolderCwd, validateBotCwd } from "./bot-cwd.ts";
+import { folderToFollow, inMyFolderCwd, validateBotCwd } from "./bot-cwd.ts";
import {
ATTACHMENTS_DIR,
attachmentExists,
@@ -345,6 +345,7 @@ import {
TASK_WORKSPACES_DIR,
readMemoryOnlyFromRegularFiles,
workspaceDir,
+ botSettingsFile,
} from "./workspace.ts";
import { listMemoryTopics, memoryDate, readMemoryFile, readMemoryTopic, writeMemoryFile, writeMemoryTopic } from "./workspace.ts";
import {
@@ -1660,6 +1661,7 @@ type InternalCapability = {
const MAX_ATTACHED_FILES_PER_TURN = 10;
const MAX_ROOM_POSTS_PER_TURN = 3;
const MAX_CREATED_BOTS_PER_TURN = 4;
+const MAX_CREATED_BOT_INSTRUCTIONS = 4_000;
// Only an orphan backstop: normal terminal paths revoke a capability synchronously.
const INTERNAL_CAPABILITY_ORPHAN_MS = 30 * 24 * 60 * 60_000;
const internalCapabilities = new Map<string, InternalCapability>();
@@ -7951,6 +7953,8 @@ async function startTurn(
const transcript = selection.transcript.map(({ role, text }) => ({ role, text }));
const contextReset = selection.compacted > 0 && record?.id !== task.appliedCompactionId;
if (contextReset) store.patchTask(bot.id, threadId, { resumeCursors: {} });
+ // Engines keep a session in the folder it started in, so a thread that follows its bot to the bot's working folder starts a new one there.
+ const followed = folderToFollow(bot, threadId, task.cwd, { worksInFolders: supportsWorkspaceFiles(instance.driverKind), keepsPrivateFolder: guestConfined || cloudGuestOpened(threadId) }); if (followed) store.patchTask(bot.id, threadId, { cwd: followed, resumeCursors: {} });
// After a rewind the native session still holds the abandoned branch; the flag clears only once dispatched, or a failed dispatch loses the next attempt's history.
const rewound = Boolean(task.rewound);
@@ -8585,6 +8589,7 @@ async function startTurn(
...(integrations.browser && browserIsThePlace(turnSurfacePlan(bot, undefined, threadId, true)) ? { preloadBrowserTools: true } : {}),
...settingsTurnFields(cfg, DATA_DIR, managedPolicy.restrictsMcp()),
cwd,
+ botSettingsFile: botSettingsFile(bot),
}, (input) => quickFallback.sendTurn(instance, input, route.quickModel ? { model, own: bot.modelSelection, onFallback: () => store.patchMessage(threadId, userMessage.id, { quickModel: undefined }) } : undefined))), () => companyShutdown || !directTurnClaimExists(bot.id, dispatchClaimId, threadId), async () => {
await (runningTurnEngines.get(threadId) ?? instance).adapter.interruptTurn(threadId).catch(() => {});
});
@@ -10483,6 +10488,7 @@ async function runClaimedGroupMemberTurn(
integrations,
...(integrations.browser && browserIsThePlace(roomPlan) ? { preloadBrowserTools: true } : {}),
...settingsTurnFields(cfg, DATA_DIR, managedPolicy.restrictsMcp()),
+ botSettingsFile: botSettingsFile(readyBot),
...(instance.instanceId === readyBot.modelSelection.instanceId
? memberTurnSelection(readyBot.modelSelection)
: { model: instance.models.default }),
@@ -14360,8 +14366,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
// Both fields are quoted into every other room member's system prompt, one line each.
if (!fitsOnOneLine(name)) return json(res, 400, { error: "name must fit on one line" });
if (!fitsOnOneLine(role)) return json(res, 400, { error: "role must fit on one line" });
- if (instructions.length > 1_000) {
- return json(res, 400, { error: "instructions must be at most 1000 characters" });
+ if (instructions.length > MAX_CREATED_BOT_INSTRUCTIONS) {
+ return json(res, 400, { error: `instructions must be at most ${MAX_CREATED_BOT_INSTRUCTIONS} characters; these are ${instructions.length}. Shorten them to what this bot does and how it works, or create it with propose_team_setup, where soul takes up to ${BOT_PROFILE_LIMITS.soul} bytes.` });
}
let selection: ModelSelection;
if (body.modelSelection === undefined) {
diff --git a/server/thread-folder-settings.e2e.test.ts b/server/thread-folder-settings.e2e.test.ts
new file mode 100644
index 0000000000..3bd0b631ea
--- /dev/null
+++ b/server/thread-folder-settings.e2e.test.ts
@@ -0,0 +1,83 @@
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+it("runs every thread of a bot with the bot's settings, and moves its threads to the working folder it is given", async () => {
+ // FAKE_CLAUDE_HOOKS: the fake engine runs the Stop hooks of its --settings file, as Claude Code does.
+ const fixture = await launchVerificationServer({ FAKE_CLAUDE_HOOKS: "1" });
+ const project = realpathSync(mkdtempSync(join(tmpdir(), "omb-thread-settings-project-")));
+ const chosen = realpathSync(mkdtempSync(join(tmpdir(), "omb-thread-settings-chosen-")));
+ const control = (args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${fixture.info.url}${path}`, {
+ method, headers: { "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ const result = await response.json() as any;
+ expect(response.ok, JSON.stringify(result)).toBe(true);
+ return result;
+ };
+ const turn = async (botId: string, threadId: string, text: string) => {
+ await control(["send", "--bot", botId, "--task", threadId, "--text", text]);
+ expect((await control(["wait", "--bot", botId, "--task", threadId, "--timeout", "30"])).status).toBe("settled");
+ return JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8"));
+ };
+ const writeSettings = (folder: string, settings: unknown) => {
+ mkdirSync(join(folder, ".claude"), { recursive: true });
+ writeFileSync(join(folder, ".claude", "settings.json"), JSON.stringify(settings));
+ };
+ try {
+ const { bot } = await api("POST", "/api/bots", { name: "Guarded helper" });
+ const guardRan = join(fixture.info.dataDir, "guard-ran.txt");
+ writeSettings(join(fixture.info.dataDir, "workspaces", bot.id), {
+ hooks: { Stop: [{ hooks: [{ type: "command", command: `pwd -P >> ${JSON.stringify(guardRan)}` }] }] },
+ enabledPlugins: { "guard@team": true },
+ });
+ const ownFolder = (threadId: string) => realpathSync(join(fixture.info.dataDir, "task-workspaces", bot.id, threadId));
+
+ const first = await turn(bot.id, bot.threadId, "Remember the fixture code MOSS-42.");
+ expect(realpathSync(first.cwd)).toBe(ownFolder(bot.threadId));
+ expect(first.settings.enabledPlugins).toEqual({ "guard@team": true });
+ expect(readFileSync(guardRan, "utf8").trim().split("\n")).toEqual([ownFolder(bot.threadId)]);
+ const { task: sibling } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Sibling" });
+ const second = await turn(bot.id, sibling.threadId, "Say hello.");
+ expect(realpathSync(second.cwd)).toBe(ownFolder(sibling.threadId));
+ expect(second.settings.enabledPlugins).toEqual({ "guard@team": true });
+ expect(readFileSync(guardRan, "utf8").trim().split("\n")).toEqual([ownFolder(bot.threadId), ownFolder(sibling.threadId)]);
+
+ writeFileSync(join(ownFolder(bot.threadId), "notes.txt"), "made before the move");
+ writeSettings(project, { enabledPlugins: { "project@team": true } });
+ await api("PATCH", `/api/bots/${bot.id}`, { cwd: project });
+ const firstSession = first.argv[first.argv.indexOf("--session-id") + 1];
+ const moved = await turn(bot.id, bot.threadId, "What was the fixture code?");
+ expect(realpathSync(moved.cwd)).toBe(project);
+ expect(moved.argv).not.toContain("--resume");
+ expect(moved.argv[moved.argv.indexOf("--session-id") + 1]).not.toBe(firstSession);
+ expect(JSON.stringify(moved.prompt)).toContain("MOSS-42");
+ // Claude Code reads the working folder's own settings itself there.
+ expect(moved.settings).not.toHaveProperty("enabledPlugins");
+ expect(readFileSync(join(ownFolder(bot.threadId), "notes.txt"), "utf8")).toBe("made before the move");
+ const tasks = (await api("GET", "/api/bots?messages=0")).bots.find((item: any) => item.id === bot.id).tasks;
+ expect(tasks.find((task: any) => task.threadId === bot.threadId).cwd).toBe(project);
+ expect(tasks.find((task: any) => task.threadId === sibling.threadId).cwd).toBe(join(fixture.info.dataDir, "task-workspaces", bot.id, sibling.threadId));
+
+ const { task: picked } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Chosen folder", cwd: chosen });
+ const kept = await turn(bot.id, picked.threadId, "Say hello from the chosen folder.");
+ expect(realpathSync(kept.cwd)).toBe(chosen);
+ expect(kept.settings.enabledPlugins).toEqual({ "project@team": true });
+
+ // A room without a folder of its own runs its members in their own bot folders.
+ const { group } = await api("POST", "/api/groups", { name: "Guarded room", memberIds: [bot.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: bot.id } } });
+ await control(["send-channel", "--channel", group.id, "--text", "Say hello to the room."]);
+ expect((await control(["wait", "--channel", group.id, "--timeout", "30"])).status).toBe("settled");
+ const room = JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8"));
+ expect(realpathSync(room.cwd)).toBe(realpathSync(join(fixture.info.dataDir, "workspaces", bot.id)));
+ expect(room.settings.enabledPlugins).toEqual({ "project@team": true });
+ } finally {
+ await fixture.close();
+ await removeTempDir(project);
+ await removeTempDir(chosen);
+ }
+}, 90_000);
diff --git a/server/workspace.ts b/server/workspace.ts
index 9be19a8d36..7dae64d20b 100644
--- a/server/workspace.ts
+++ b/server/workspace.ts
@@ -87,6 +87,11 @@ export function workspaceDir(botId: string): string {
return join(WORKSPACES_DIR, botId);
}
+/** One per bot, for every thread: its working folder's Claude Code settings, else its own folder's. */
+export function botSettingsFile(bot: { id: string; cwd?: string }): string {
+ return join(bot.cwd ?? workspaceDir(bot.id), ".claude", "settings.json");
+}
+
/** On a Cloud home memory is read only from regular files, never through a link. */
let regularMemoryFilesOnly = false;
export function readMemoryOnlyFromRegularFiles(): void {
diff --git a/shared/thread-folder.test.ts b/shared/thread-folder.test.ts
new file mode 100644
index 0000000000..e0c9cc9d73
--- /dev/null
+++ b/shared/thread-folder.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+
+import { isOwnThreadFolder } from "./thread-folder.ts";
+
+describe("isOwnThreadFolder", () => {
+ it("knows a thread's own folder on every OS, trailing separator or not", () => {
+ expect(isOwnThreadFolder("/home/ada/.openmausbot/task-workspaces/bot-1/thread-1", "bot-1", "thread-1")).toBe(true);
+ expect(isOwnThreadFolder("/home/ada/.openmausbot/task-workspaces/bot-1/thread-1/", "bot-1", "thread-1")).toBe(true);
+ expect(isOwnThreadFolder("C:\\Users\\Ada\\.openmausbot\\task-workspaces\\bot-1\\thread-1", "bot-1", "thread-1")).toBe(true);
+ });
+
+ it("is never another thread's folder, another bot's, a folder inside one, a chosen folder or none", () => {
+ expect(isOwnThreadFolder("/data/task-workspaces/bot-1/thread-2", "bot-1", "thread-1")).toBe(false);
+ expect(isOwnThreadFolder("/data/task-workspaces/bot-2/thread-1", "bot-1", "thread-1")).toBe(false);
+ expect(isOwnThreadFolder("/data/task-workspaces/bot-1/thread-1/src", "bot-1", "thread-1")).toBe(false);
+ expect(isOwnThreadFolder("/data/workspaces/bot-1/thread-1", "bot-1", "thread-1")).toBe(false);
+ expect(isOwnThreadFolder("/Users/ada/Projects/site", "bot-1", "thread-1")).toBe(false);
+ expect(isOwnThreadFolder(null, "bot-1", "thread-1")).toBe(false);
+ expect(isOwnThreadFolder(undefined, "bot-1", "thread-1")).toBe(false);
+ });
+});
diff --git a/shared/thread-folder.ts b/shared/thread-folder.ts
new file mode 100644
index 0000000000..3606521f02
--- /dev/null
+++ b/shared/thread-folder.ts
@@ -0,0 +1,6 @@
+/** A conversation's own folder, `<data>/task-workspaces/<bot>/<thread>`: where a thread of a bot without a working folder
+ * runs, and the one folder a thread leaves for its bot's working folder once the bot has one. */
+export function isOwnThreadFolder(path: string | null | undefined, botId: string, threadId: string): boolean {
+ const parts = (path ?? "").split(/[\\/]+/).filter(Boolean);
+ return parts.at(-3) === "task-workspaces" && parts.at(-2) === botId && parts.at(-1) === threadId;
+}
diff --git a/shared/wire.ts b/shared/wire.ts
index e5bbc2401a..a9e4312163 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -191,7 +191,7 @@ export interface WireTask extends InboxTask {
/** Prompt-cache keep-warm status for this thread, derived at projection;
* absent when no window is open. */
cacheKeepWarm?: CacheKeepWarmStatus;
- /** the folder this task's turns run in, pinned on its first turn. */
+ /** the folder this task's turns run in, pinned on its first turn; one in its own folder moves to its bot's working folder. */
cwd?: string | null;
/** Set me up was pressed here (server/setup-request.ts): the person's next line in this conversation runs as a
* setup request. Server-owned; a client only shows it. `by`: who pressed, where several people share the place (their
@@ -317,7 +317,7 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {
/** This bot's own SSH config alias for its managed VPS computer; absent
* means the default server from Settings → API keys. */
vpsAlias?: string;
- /** where NEW tasks run their shell tools; absent = home folder. */
+ /** where its tasks run their tools; absent = each task's own folder. Its .claude/settings.json (else the bot folder's) applies in all. */
cwd?: string;
/** Auto mode: the bot approves its own tool permissions. */
autoApprove?: boolean;
diff --git a/src/components/bot-settings/AccessSection.test.ts b/src/components/bot-settings/AccessSection.test.ts
index 1d656945df..a1110497df 100644
--- a/src/components/bot-settings/AccessSection.test.ts
+++ b/src/components/bot-settings/AccessSection.test.ts
@@ -372,3 +372,17 @@ describe("AccessSection parts", () => {
expect(folder).not.toContain("Let this bot use notes");
});
});
+
+describe("working folder note", () => {
+ const folderCard = (bot: Bot) => renderToStaticMarkup(createElement(StoreProvider, null, createElement(AccessSection, { bot, derived: makeDerived(), parts: ["folder"] })));
+ const inFolder = (cwd: string | null, botCwd?: string) => makeBot({ ...(botCwd ? { cwd: botCwd } : {}), tasks: [{ threadId: "thread-1", cwd }] as unknown as Bot["tasks"] });
+
+ it("calls a thread pinned only to a folder chosen for it, or to an earlier working folder, never to its own folder", () => {
+ for (const own of ["/data/.openmausbot/task-workspaces/bot-1/thread-1", "C:\\Users\\Ada\\.openmausbot\\task-workspaces\\bot-1\\thread-1"]) {
+ expect(folderCard(inFolder(own, "/projects/site"))).not.toContain("This task is pinned");
+ expect(folderCard(inFolder(own))).not.toContain("This task is pinned");
+ }
+ expect(folderCard(inFolder("/projects/old", "/projects/site"))).toContain("This task is pinned to /projects/old.");
+ expect(folderCard(inFolder("/projects/site", "/projects/site"))).not.toContain("This task is pinned");
+ });
+});
diff --git a/src/components/bot-settings/AccessSection.tsx b/src/components/bot-settings/AccessSection.tsx
index 6695ce886f..3edef77d77 100644
--- a/src/components/bot-settings/AccessSection.tsx
+++ b/src/components/bot-settings/AccessSection.tsx
@@ -10,6 +10,7 @@ import type { LocaleKey } from "@/locales";
import { mcpServersForBot, mcpServersOfBot, useMcpServers } from "@/lib/mcp-servers";
import { placeFacts, placeViewFor, usePlaceSeat } from "@/lib/place-view";
import { shortPath } from "@/lib/short-path";
+import { isOwnThreadFolder } from "../../../shared/thread-folder";
import { useDesktopCapabilities } from "../DesktopCapabilities";
import { CloudBackendPicker } from "../CloudBackendPicker";
import { Switch } from "../SettingsPrimitives";
@@ -68,7 +69,7 @@ export function WorkingFolder({ bot }: { bot: Bot }) {
const { draft, setDraft, error, saving, canPick, save, pick } = useWorkingFolder(bot);
const task = bot.tasks?.find((t) => t.threadId === bot.threadId);
const pinned = task?.cwd;
- const pinnedElsewhere = pinned !== undefined && (pinned ?? undefined) !== bot.cwd;
+ const pinnedElsewhere = pinned !== undefined && (pinned ?? undefined) !== bot.cwd && !isOwnThreadFolder(pinned, bot.id, bot.threadId);
return (
<div className="rounded-xl bg-card p-4">