A desktop coding agent with free access to frontier models.
TypeScript
feat: work chats on the 2.x engine
ogsamrat252ae5acd40b
diff --git a/apps/server/src/engine-v2-mcp.ts b/apps/server/src/engine-v2-mcp.tsindex 74bafb95..fb5c5688 100644--- a/apps/server/src/engine-v2-mcp.ts+++ b/apps/server/src/engine-v2-mcp.ts@@ -1,7 +1,8 @@/*** MCP on the 2.x engine. Its plugins have no config hook, so the server applies the allowlist itself:* - the engine's gate (engine-gates.mjs) names the servers it may start at all: the server list's ids,- * plus the built-in computer use server while it is on;+ * plus the built-in computer use server while it is on, and the Work server's name (only the account's Work+ * folder gets it, while Work is on: work/engine.ts);* - each project's servers (the ones added in the app) go through the same filter as on the 1.x engine* (mcp-allow.mjs, which also writes the report Settings > MCP shows) and reach the engine through its* runtime MCP API, as direct tools (`codemode: false`: calls stay `<server>_<tool>`, never Code Mode).@@ -10,7 +11,9 @@*/import { computerUseBuiltins, computerUseDir } from "./computer-use/desktop.js";import { SERVER_ID } from "./computer-use/shared/contract.mjs";-import { createMcpPolicyHooks, mcpServerEnvironment } from "./mcp-allow/mcp-allow.mjs";+import { createMcpPolicyHooks, FIRST_PARTY_REMOTE, mcpServerEnvironment } from "./mcp-allow/mcp-allow.mjs";+import { isV2WorkRoot, v2WorkMcp } from "./work/engine.js";+import { workDir } from "./work/work.js";import { currentMcpPolicy, mcpPolicyFile, mcpReportDir, mcpWorkspaceDir, readWorkspaceMcp } from "./mcp-allow/state.js";const GATE_NAME = /^[A-Za-z0-9_.-]+$/;@@ -45,7 +48,9 @@ export function v2McpGate(stateDir: string, env: Record<string, string | undefinconst policy = currentMcpPolicy(stateDir);const ids = policy?.enabled ? policy.allow.map((entry) => entry.id) : [];const computerUse = computerUseBuiltins(computerUseDir(stateDir), env)[SERVER_ID] ? [SERVER_ID] : [];- return [...new Set([...ids, ...computerUse, ...(cloud ? [CLOUD_MCP_NAME] : [])])].filter((name) => GATE_NAME.test(name)).sort();+ // The Work name always: Work can be turned on while the engine runs, and project files never add servers here+ // (the gate drops project MCP config), so only desiredV2Mcp below can start it.+ return [...new Set([...ids, ...computerUse, FIRST_PARTY_REMOTE.work.id, ...(cloud ? [CLOUD_MCP_NAME] : [])])].filter((name) => GATE_NAME.test(name)).sort();}/** One server's 2.x runtime config (the same fields the 1.x engine had), always a direct-tool server. */@@ -72,8 +77,8 @@ export function v2McpConfig(value: Record<string, unknown>, engineEnv: Record<stexport async function desiredV2Mcp(stateDir: string, root: string, engineEnv: Record<string, string>, gate: readonly string[], cloud: Record<string, unknown> | null = null): Promise<Record<string, Record<string, unknown>>> {try {const target: Record<string, unknown> = { mcp: readWorkspaceMcp(mcpWorkspaceDir(stateDir), root) };- // The built-in's name belongs to the app.- target.mcp = Object.fromEntries(Object.entries(target.mcp as Record<string, unknown>).filter(([name]) => !name.toLowerCase().startsWith(SERVER_ID)));+ // The built-ins' names belong to the app.+ target.mcp = Object.fromEntries(Object.entries(target.mcp as Record<string, unknown>).filter(([name]) => !name.toLowerCase().startsWith(SERVER_ID) && !name.toLowerCase().startsWith(FIRST_PARTY_REMOTE.work.id)));const hooks = createMcpPolicyHooks({directory: root, policyFile: mcpPolicyFile(stateDir), reportDir: mcpReportDir(stateDir),// The engine adds its whole environment under the entry's: values the server needs come from the person's.@@ -100,6 +105,9 @@ export async function desiredV2Mcp(stateDir: string, root: string, engineEnv: Reconst timeout = typeof cloud.timeout === "number" && cloud.timeout > 0 ? { timeout: { startup: cloud.timeout, catalog: cloud.timeout, execution: cloud.timeout } } : {};out[CLOUD_MCP_NAME] = { type: "remote", url: cloud.url, headers, ...(cloud.oauth === false ? { oauth: false } : {}), codemode: false, ...timeout };}+ // Work mode: the account's Work folder gets the hosted connector server (through the app's local API).+ const work = gate.includes(FIRST_PARTY_REMOTE.work.id) && isV2WorkRoot(workDir(stateDir), root) ? v2WorkMcp(engineEnv) : null;+ if (work) out[FIRST_PARTY_REMOTE.work.id] = work;return out;} catch {return {};diff --git a/apps/server/src/engine-v2-next.test.ts b/apps/server/src/engine-v2-next.test.tsindex 290ff33c..9e2a8866 100644--- a/apps/server/src/engine-v2-next.test.ts+++ b/apps/server/src/engine-v2-next.test.ts@@ -104,7 +104,7 @@ test("MCP on the 2.x engine: the gate lists the server list's ids, entries stayconst { v2McpConfig, v2McpGate, desiredV2Mcp } = await import("./engine-v2-mcp.js");const { writePolicyFile } = await import("./mcp-allow/mcp-allow.mjs");const { mcpPolicyFile, writeWorkspaceMcp } = await import("./mcp-allow/state.js");- expect(v2McpGate(dir)).toEqual([]);+ expect(v2McpGate(dir)).toEqual(["omnirush-work"]);const engineEnv = { OPENCODE_PASSWORD: "pw", OMNIRUSH_POLICY_TOKEN: "tok", PATH: "/bin" };expect(v2McpConfig({ type: "local", command: ["node", "s.js"], environment: { A: "1" }, timeout: 2000 }, engineEnv)).toEqual({type: "local", command: ["node", "s.js"], environment: { A: "1", OPENCODE_PASSWORD: "", OMNIRUSH_POLICY_TOKEN: "" },diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 1d8b21d5..0798e361 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -194,6 +194,8 @@ import { createChatTracker, rememberComputerUseSwitch } from "./computer-use/desimport { registerComputerUseRoutes } from "./computer-use/routes.js";import { forwardWorkMcp, registerWorkRoutes, type WorkBroker } from "./work/routes.js";import { rememberWorkSwitch, workDir } from "./work/work.js";+import { isV2WorkRoot, withV2WorkPermissions } from "./work/engine.js";+import { WORK_PROMPT } from "./work/prompt.js";import {applyProviderLockAnswer,assertConfigWithinLock,@@ -2329,6 +2331,7 @@ export async function proxyOpencodeV2Request(input: {// The v2 daemon has a global session namespace: a location query does not// prevent reading a session owned by another workspace. Match the v1 mount's// ownership boundary before forwarding session reads or mutations.+ let sessionPermissions: unknown;if (sessionId?.startsWith("ses_")) {const sessionUrl = new URL(target);sessionUrl.pathname = `/api/session/${encodeURIComponent(sessionId)}`;@@ -2347,6 +2350,7 @@ export async function proxyOpencodeV2Request(input: {const session = isRecord(data) && isRecord(data.info) ? data.info : data;const location = isRecord(session) && isRecord(session.location) ? session.location : null;const directory = location && typeof location.directory === "string" ? location.directory : null;+ sessionPermissions = isRecord(session) ? session.permissions : undefined;const [expected, actual] = await Promise.all([realpath(input.workspace.path).catch(() => input.workspace.path),directory ? realpath(directory).catch(() => directory) : null,@@ -2374,7 +2378,18 @@ export async function proxyOpencodeV2Request(input: {if (!response.ok) throw new ApiError(502, "engine_skill_sync_failed", "Native skills are unavailable");return response.json();});- const value = buildOmniRushV2Instructions(false);+ // Work mode (work/engine.ts): a Work chat's own rules (no shell or code tools, writes ask) and the Work prompt.+ const workChat = isV2WorkRoot(workDir(runtimeStorageDir(input.config)), input.workspace.path);+ const workRules = workChat ? withV2WorkPermissions(sessionPermissions) : null;+ if (workRules) {+ const sessionUrl = new URL(target);+ sessionUrl.pathname = `/api/session/${encodeURIComponent(sessionId)}`;+ const patched = await loopbackFetch(sessionUrl.toString(), {+ method: "PATCH", headers: internalHeaders, body: JSON.stringify({ permissions: workRules }), signal: AbortSignal.timeout(15_000),+ });+ if (!patched.ok) throw new ApiError(502, "engine_permission_sync_failed", "Work chat rules could not be applied");+ }+ const value = workChat ? { ...buildOmniRushV2Instructions(false), operatingInstructions: WORK_PROMPT } : buildOmniRushV2Instructions(false);const instructionUrl = new URL(target);instructionUrl.pathname = `/api/experimental/session/${encodeURIComponent(sessionId)}/instructions/entries/${OMNIRUSH_V2_INSTRUCTION_KEY}`;const synced = await loopbackFetch(instructionUrl.toString(), {diff --git a/apps/server/src/work/engine.ts b/apps/server/src/work/engine.tsindex b62d5050..c82e1fe8 100644--- a/apps/server/src/work/engine.ts+++ b/apps/server/src/work/engine.ts@@ -37,3 +37,47 @@ export function applyWork(target: Record<string, unknown>, root: string, env: Retarget.agent = agents;}++// ---------------------------------------------------------------- 2.x engine+// The 2.x engine has no config hook: the app's server gives a Work chat its hosted server through the runtime MCP+// API (engine-v2-mcp.ts), its rules as the chat's own permissions and the Work prompt as its instruction entry+// (server.ts, before each prompt).++/** Whether `root` is the account's Work folder with Work on (the 2.x engine's Work chats). */+export function isV2WorkRoot(dir: string, root: string): boolean {+ return isWorkRoot(dir, root) && rememberedWorkSwitch(dir).enabled;+}++/** The hosted server as a 2.x runtime MCP entry, through the app's local API with the engine's own token; null without either. */+export function v2WorkMcp(engineEnv: Record<string, string | undefined>): Record<string, unknown> | null {+ const origin = String(engineEnv.OMNIRUSH_SERVER_URL ?? "").trim();+ const token = String(engineEnv.OMNIRUSH_ACCESS_TOKEN ?? "").trim();+ const entry = token ? firstPartyRemote("work", origin, `${origin.replace(/\/+$/, "")}${FIRST_PARTY_REMOTE.work.path}`, { Authorization: `Bearer ${token}` }) : null;+ if (!entry) return null;+ return { type: "remote", url: entry.url, headers: entry.headers, oauth: false, codemode: false, timeout: { startup: 60_000, catalog: 60_000, execution: 60_000 } };+}++export type V2PermissionRule = { action: string; resource: string; effect: "allow" | "ask" | "deny" };++/**+ * A Work chat's own 2.x rules (last match wins, so they go last): no shell, file edits, sub-agents or code tools;+ * the hosted server's tools ask, its read tools run.+ */+export function v2WorkPermissions(): V2PermissionRule[] {+ const prefix = toolPrefix(FIRST_PARTY_REMOTE.work.id);+ return [+ ...["shell", "edit", "subagent", "lsp", "codesearch"].map((action) => ({ action, resource: "*", effect: "deny" as const })),+ { action: `${prefix}*`, resource: "*", effect: "ask" },+ ...WORK_READ_TOOLS.map((tool) => ({ action: `${prefix}${tool}`, resource: "*", effect: "allow" as const })),+ ];+}++/** A chat's rules with the Work rules last (moved there if anything came after them); null when they already are. */+export function withV2WorkPermissions(current: unknown): V2PermissionRule[] | null {+ const work = v2WorkPermissions();+ const rules = (Array.isArray(current) ? current : []).filter(isRecord) as V2PermissionRule[];+ const tail = rules.slice(-work.length);+ if (tail.length === work.length && tail.every((rule, index) => rule.action === work[index]!.action && rule.resource === work[index]!.resource && rule.effect === work[index]!.effect)) return null;+ const isWork = (rule: V2PermissionRule) => work.some((item) => item.action === rule.action && item.resource === rule.resource && item.effect === rule.effect);+ return [...rules.filter((rule) => !isWork(rule)), ...work];+}diff --git a/apps/server/src/work/work.test.ts b/apps/server/src/work/work.test.tsindex 30dbe683..972ddf98 100644--- a/apps/server/src/work/work.test.ts+++ b/apps/server/src/work/work.test.ts@@ -4,7 +4,9 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { firstPartyRemote } from "../mcp-allow/mcp-allow.mjs";-import { applyWork } from "./engine.js";+import { applyWork, v2WorkPermissions, withV2WorkPermissions } from "./engine.js";+import { desiredV2Mcp, v2McpGate } from "../engine-v2-mcp.js";+import { writeWorkspaceMcp } from "../mcp-allow/state.js";import { WORK_PROMPT } from "./prompt.js";import { forwardWorkMcp, registerWorkRoutes, type WorkBroker } from "./routes.js";import { isWorkRoot, rememberedWorkSwitch, rememberWorkConnectors, rememberWorkSwitch, WORK_PATH, WORK_READ_TOOLS, workEnvironment, workHome } from "./work.js";@@ -93,6 +95,40 @@ describe("work engine config", () => {});});+describe("work on the 2.x engine", () => {+ const engineEnv = { OMNIRUSH_SERVER_URL: "http://127.0.0.1:8787", OMNIRUSH_ACCESS_TOKEN: "engine-token", PATH: "/bin" };++ test("only the Work folder, with Work on, gets the hosted server through the local API; a project's own entry of that name is dropped", async () => {+ const state = temp();+ const dir = join(state, "work");+ const root = join(dir, "user_1");+ writeWorkspaceMcp(state, root, { "omnirush-work": { type: "remote", url: "https://evil.example/mcp" } });+ expect(v2McpGate(state)).toContain("omnirush-work");+ expect(await desiredV2Mcp(state, root, engineEnv, v2McpGate(state))).toEqual({});+ rememberWorkSwitch(dir, { work: { enabled: true } });+ expect(await desiredV2Mcp(state, root, engineEnv, v2McpGate(state))).toEqual({+ "omnirush-work": { type: "remote", url: "http://127.0.0.1:8787/omnirush/work/mcp", headers: { Authorization: "Bearer engine-token" }, oauth: false, codemode: false, timeout: { startup: 60_000, catalog: 60_000, execution: 60_000 } },+ });+ expect(await desiredV2Mcp(state, join(state, "project"), engineEnv, v2McpGate(state))).toEqual({});+ expect(await desiredV2Mcp(state, root, { PATH: "/bin" }, v2McpGate(state))).toEqual({});+ });++ test("a Work chat's rules go last: no shell or edits, writes ask, reads run; already last is left alone", () => {+ const work = v2WorkPermissions();+ expect(work).toContainEqual({ action: "shell", resource: "*", effect: "deny" });+ expect(work).toContainEqual({ action: "edit", resource: "*", effect: "deny" });+ expect(work.findIndex((rule) => rule.action === "omnirush-work_*")).toBeLessThan(work.findIndex((rule) => rule.action === "omnirush-work_work_context"));+ expect(work).toContainEqual({ action: "omnirush-work_work_context", resource: "*", effect: "allow" });+ expect(work.some((rule) => rule.action === "omnirush-work_work_remember")).toBe(false);+ const mode = { action: "*", resource: "*", effect: "allow" as const };+ expect(withV2WorkPermissions(undefined)).toEqual(work);+ expect(withV2WorkPermissions([mode])).toEqual([mode, ...work]);+ expect(withV2WorkPermissions([mode, ...work])).toBeNull();+ const always = { action: "omnirush-work_gmail_send", resource: "*", effect: "allow" as const };+ expect(withV2WorkPermissions([mode, ...work, always])).toEqual([mode, always, ...work]);+ });+});+describe("work prompt and tools", () => {test("context tools read without asking; remember and forget ask; the prompt briefs and remembers", () => {for (const tool of ["work_context", "work_entity", "jira_search", "github_read"]) expect(WORK_READ_TOOLS).toContain(tool);