A desktop coding agent with free access to frontier models.
TypeScript
feat: each assistant session keeps its chosen model
ogsamratb7ab71a1f368
diff --git a/apps/server/src/claude-code/access.ts b/apps/server/src/claude-code/access.tsindex e5c96a7e..69903198 100644--- a/apps/server/src/claude-code/access.ts+++ b/apps/server/src/claude-code/access.ts@@ -1,6 +1,6 @@import { createHash } from "node:crypto";import type { ClaudeAccess, ClaudeAuthorization, ClaudeBudgetSnapshot, ClaudeGrant } from "./runtime.js";-import { MODEL } from "./sandbox-assets.js";+import { CLAUDE_MODEL_ID } from "./sandbox-assets.js";import { SDK_INSTALL_PIN } from "./sandbox-lock.js";export type ClaudeDeviceRequest = (route: string, init?: { method: "POST"; body: string }, owner?: string) => Promise<Response>;@@ -8,6 +8,19 @@ const record = (value: unknown): value is Record<string, unknown> => Boolean(valconst tokens = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;const limit = (value: unknown): value is number | null => value === null || tokens(value);const timestamp = (value: unknown): value is string => typeof value === "string" && Number.isFinite(Date.parse(value));+/** A picker entry of the server's `claude_code.catalog`. */+export type ClaudeCatalogEntry = { id: string; name: string };+/** The catalog's valid entries (catalog ids, visible names), first of each id kept. */+export function claudeCatalog(value: unknown): ClaudeCatalogEntry[] {+ if (!Array.isArray(value)) return [];+ const entries: ClaudeCatalogEntry[] = [];+ for (const item of value.slice(0, 16)) {+ if (!record(item) || typeof item.id !== "string" || !CLAUDE_MODEL_ID.test(item.id) || entries.some(entry => entry.id === item.id)) continue;+ const name = typeof item.display_name === "string" ? item.display_name.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim().slice(0, 64) : "";+ entries.push({id: item.id, name: name || item.id});+ }+ return entries;+}/** Neutral quota metadata is useful to the SDK; provider and credential headers stay private. */export function claudeResponseHeaders(headers: Headers): Record<string, string> {const result: Record<string, string> = {};@@ -69,28 +82,34 @@ async function read(response: Response): Promise<unknown> {export class ClaudeDeviceAccess {private readonly grants = new Map<string, { grant: ClaudeGrant; refreshAt: number }>();private readonly pending = new Map<string, Promise<ClaudeGrant>>();- private capability?: {owner: string; expiresAt: number; enabled: boolean};+ private capability?: {owner: string; expiresAt: number; models: string[]; catalog: ClaudeCatalogEntry[]; reason: string | null};constructor(private readonly request: ClaudeDeviceRequest, private readonly client: string) {}async access(): Promise<ClaudeAccess> {const account = await read(await this.request("device/me"));if (!record(account) || typeof account.id !== "string" || !account.id) throw new Error("Sign in to OmniRush to use Claude Code");if (!this.capability || this.capability.owner !== account.id || Date.now() >= this.capability.expiresAt) {- let enabled = false;+ let models: string[] = [], catalog: ClaudeCatalogEntry[] = [], reason: string | null = "unavailable";try {const value = await read(await this.request("collect/capabilities"));const code = record(value) ? value.claude_code : null;- // The pilot supports this exact SDK/Code pair and one fixed model.- // An enabled relay with an empty catalog is not permission to run it.- enabled = record(code) && code.enabled === true && record(code.sdk)- && code.sdk.package === SDK_INSTALL_PIN.package && code.sdk.version === SDK_INSTALL_PIN.version- && code.sdk.integrity === SDK_INSTALL_PIN.integrity- && Array.isArray(code.models) && code.models.includes(MODEL)- && code.models.every(model => typeof model === "string" && model.length > 0);+ if (record(code)) {+ // The catalog is shown to every account; `models` (what may run) only to allowed ones.+ catalog = claudeCatalog(code.catalog);+ const access = record(code.access) ? code.access : {};+ reason = typeof access.reason === "string" ? access.reason : code.enabled === true ? null : "not_allowed";+ // The runtime supports this exact SDK/Code pair. An enabled relay+ // with an empty model list is not permission to run it.+ const pinned = record(code.sdk) && code.sdk.package === SDK_INSTALL_PIN.package && code.sdk.version === SDK_INSTALL_PIN.version+ && code.sdk.integrity === SDK_INSTALL_PIN.integrity;+ if (code.enabled === true && pinned && Array.isArray(code.models)) models = [...new Set(code.models.filter((model): model is string => typeof model === "string" && CLAUDE_MODEL_ID.test(model)))];+ if (code.enabled === true && !models.length) reason = pinned ? "no_models" : "client_outdated";+ }} catch { /* Failed eligibility checks deny new sessions, but never hide saved evidence. */ }- this.capability = {owner: account.id, expiresAt: Date.now() + 30_000, enabled};+ this.capability = {owner: account.id, expiresAt: Date.now() + 30_000, models, catalog, reason: models.length ? null : reason};}- return { owner: account.id, capabilities: this.capability.enabled ? ["claude-code"] : [] };+ const {models, catalog, reason} = this.capability;+ return { owner: account.id, capabilities: models.length ? ["claude-code"] : [], models, catalog, reason };}async authorize(context: ClaudeAuthorization): Promise<ClaudeGrant> {diff --git a/apps/server/src/claude-code/native-capture.test.ts b/apps/server/src/claude-code/native-capture.test.tsindex d3e2b2ab..f9e462e7 100644--- a/apps/server/src/claude-code/native-capture.test.ts+++ b/apps/server/src/claude-code/native-capture.test.ts@@ -7,7 +7,7 @@ import { createHash } from "node:crypto";import { fileURLToPath } from "node:url";import { NativeCapture } from "./native-capture.js";import { ClaudeAccessError, ClaudeDeviceAccess } from "./access.js";-import { CLAUDE_VERSION, MODEL } from "./sandbox-assets.js";+import { CLAUDE_VERSION, MANAGED_SETTINGS, MODEL, managedSettings } from "./sandbox-assets.js";import { SDK_INSTALL_PIN } from "./sandbox-lock.js";import { ClaudeRuntime } from "./runtime.js";import { ApiError } from "../errors.js";@@ -16,10 +16,10 @@ test("managed Claude availability requires an enabled compatible catalog, neverconst valid = {enabled: true, version: CLAUDE_VERSION, sdk: SDK_INSTALL_PIN, models: [MODEL]};for (const [code, allowed] of [[valid, true], [{...valid, enabled: false}, false], [{...valid, models: []}, false],- [{...valid, models: ["claude-haiku-4-5-20251001"]}, false], [{...valid, sdk: {...SDK_INSTALL_PIN, version: "0.0.0"}}, false],+ [{...valid, models: ["claude-haiku-4-5-20251001"]}, true], [{...valid, models: ["gpt-6-astra"]}, false], [{...valid, sdk: {...SDK_INSTALL_PIN, version: "0.0.0"}}, false],[{...valid, sdk: null}, false], [{...valid, sdk: {...SDK_INSTALL_PIN, integrity: "sha512-wrong"}}, false],[{...valid, sdk: {...SDK_INSTALL_PIN, package: "@anthropic-ai/claude-code"}}, false],- [{...valid, models: [MODEL, null]}, false], [{enabled: true}, false], [null, false],+ [{...valid, models: [MODEL, null]}, true], [{enabled: true}, false], [null, false],] as const) {const routes: string[] = [];const access = new ClaudeDeviceAccess(async route => {@@ -31,6 +31,25 @@ test("managed Claude availability requires an enabled compatible catalog, never}});+test("access lists every Claude model the server allows and the catalog for everyone", async () => {+ const sonnet = "claude-sonnet-5-5";+ const catalog = [{id: MODEL, display_name: "Claude Opus 5.5"}, {id: sonnet, display_name: "Claude Sonnet 5.5"}, {id: "gpt-6-astra", display_name: "x"}, {id: sonnet, display_name: "dup"}];+ const read = async (code: unknown) => new ClaudeDeviceAccess(async route => Response.json(route === "device/me" ? {id: "owner"} : {claude_code: code}), "desktop/3.7.6").access();+ const allowed = await read({enabled: true, sdk: SDK_INSTALL_PIN, models: [MODEL, sonnet, sonnet], catalog, access: {mode: "staff", allowed: true, reason: null}});+ expect(allowed).toMatchObject({capabilities: ["claude-code"], models: [MODEL, sonnet], reason: null});+ expect(allowed.catalog).toEqual([{id: MODEL, name: "Claude Opus 5.5"}, {id: sonnet, name: "Claude Sonnet 5.5"}]);+ const denied = await read({enabled: false, sdk: SDK_INSTALL_PIN, models: [], catalog, access: {mode: "staff", allowed: false, reason: "not_allowed"}});+ expect(denied).toMatchObject({capabilities: [], models: [], reason: "not_allowed"});+ expect(denied.catalog?.map(entry => entry.id)).toEqual([MODEL, sonnet]);+ expect((await read({enabled: true, sdk: null, models: [sonnet], catalog})).reason).toBe("client_outdated");+});++test("managed settings pin each session's own model; Opus keeps its original policy", () => {+ expect(managedSettings(MODEL)).toBe(MANAGED_SETTINGS);+ expect(JSON.parse(MANAGED_SETTINGS).deniedModels).toEqual(["sonnet", "haiku"]);+ expect(JSON.parse(managedSettings("claude-sonnet-5-5"))).toMatchObject({availableModels: ["claude-sonnet-5-5"], deniedModels: ["opus", "haiku"]});+});+test("managed grants reject provider keys and zero refresh, refresh from request time, and revoke the root", async () => {const context = {owner: "owner", sessionId: "00000000-0000-4000-8000-000000000001", workspaceId: "project", model: MODEL, contractSha256: "a".repeat(64)};const response = {token: "orc_" + "a".repeat(43), expires_in: 900, refresh_after: 600,@@ -112,7 +131,7 @@ test("session broker re-mints once on rejected authentication and never replaysexpect(init?.redirect).toBe("error");expect(init?.signal?.aborted).toBe(false);return globalThis.fetch(input, init);- }, directory: root, surface: "gui", access: async () => ({owner: "owner", capabilities: ["claude-code"]}),+ }, directory: root, surface: "gui", access: async () => ({owner: "owner", capabilities: ["claude-code"], models: [MODEL]}),authorize: async context => {authorizations++; if (context.refresh) refreshes++;return {owner: "owner", sessionId: id, model: MODEL, upstreamModel: MODEL, client: "desktop/3.7.5",@@ -733,13 +752,13 @@ function gate<T>() {test("shutdown fences startup blocked on access and never mints or starts Docker after access resolves", async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-startup-")); roots.push(root);- const entered = gate<void>(), access = gate<{owner: string; capabilities: string[]}>(); let grants = 0, dockerCalls = 0;+ const entered = gate<void>(), access = gate<{owner: string; capabilities: string[]; models: string[]}>(); let grants = 0, dockerCalls = 0;const runtime = new ClaudeRuntime({fetch: globalThis.fetch, directory: root, surface: "gui", access: () => { entered.resolve(); return access.promise; }, authorize: async () => { grants++; throw new Error("must not mint"); }});Reflect.set(runtime, "docker", async () => { dockerCalls++; throw new Error("must not start Docker"); });const creation = runtime.create(root, "workspace").then(() => "created", () => "cancelled");await entered.promise;const shutdown = runtime.shutdown();- access.resolve({owner: "local-owner", capabilities: ["claude-code"]});+ access.resolve({owner: "local-owner", capabilities: ["claude-code"], models: [MODEL]});expect(await creation).toBe("cancelled"); await shutdown;expect({grants, dockerCalls}).toEqual({grants: 0, dockerCalls: 0});await expect(runtime.prepare()).rejects.toThrow();@@ -785,12 +804,12 @@ async function cancellationResult(work: Promise<string>) {finally { clearTimeout(timer); }}-function startupDockerFixture(stage: "build" | "create" | "cp" | "exec" | "restore") {+function startupDockerFixture(stage: "build" | "create" | "cp" | "exec" | "restore", models: string[] = [MODEL]) {const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-docker-fixture-")); roots.push(root);const workspace = path.join(root, "workspace"); fs.mkdirSync(workspace);const docker = path.join(root, "docker-fixture.mjs"), ready = path.join(root, "ready"), release = path.join(root, "release"), log = path.join(root, "calls.jsonl");const runtime = new ClaudeRuntime({fetch: globalThis.fetch, directory: path.join(root, "state"), surface: "gui", docker,- access: async () => ({owner: "local-owner", capabilities: ["claude-code"]}),+ access: async () => ({owner: "local-owner", capabilities: ["claude-code"], models}),authorize: async () => { grants++; throw new Error("must not authorize after cancellation"); }});let grants = 0;const fingerprint = createHash("sha256").update(JSON.stringify(Reflect.get(runtime, "harnessContract").call(runtime))).digest("hex");@@ -821,6 +840,24 @@ else if(args[0]==='rm'||args[0]==='container'&&args[1]==='rm')fs.rmSync(state,{fcalls: (): string[][] => fs.existsSync(log) ? fs.readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)) : []};}+test("a session pins the model it was created with and refuses one the server does not list", async () => {+ const sonnet = "claude-sonnet-5-5";+ const refused = startupDockerFixture("restore");+ await expect(refused.runtime.create(refused.workspace, "workspace", undefined, sonnet)).rejects.toThrow("isn't available on your account yet");+ expect(refused.calls()).toEqual([]);+ const f = startupDockerFixture("restore", [MODEL, sonnet]);+ const session = await f.runtime.create(f.workspace, "workspace", undefined, sonnet);+ expect(session.model).toBe(sonnet);+ expect(session.contract?.model).toBe(sonnet);+ expect(session.modelIsolation?.expectedModel).toBe(sonnet);+ expect(session.contract?.harness.managedSettingsSha256).toBe(createHash("sha256").update(managedSettings(sonnet)).digest("hex"));+ expect(f.calls()).toContainEqual(["exec", "-i", "--user", "root", session.container, "sh", "-c", "cat > /etc/claude-code/managed-settings.json"]);+ expect((await f.runtime.get(session.id)).compatibility).toBe("current");+ const opus = startupDockerFixture("restore", [MODEL, sonnet]);+ expect((await opus.runtime.create(opus.workspace, "workspace")).model).toBe(MODEL);+ expect(opus.calls().some(call => call.includes("cat > /etc/claude-code/managed-settings.json"))).toBe(false);+});+for (const stage of ["build", "create", "cp", "exec"] as const) test(`startup request abort kills Docker ${stage}, waits for owned cleanup and never authorizes`, async () => {const f = startupDockerFixture(stage), controller = new AbortController();const result = f.runtime.create(f.workspace, "workspace", controller.signal).then(() => "created", () => "cancelled");diff --git a/apps/server/src/claude-code/routes.ts b/apps/server/src/claude-code/routes.tsindex ea3037a9..584a5050 100644--- a/apps/server/src/claude-code/routes.ts+++ b/apps/server/src/claude-code/routes.ts@@ -1,4 +1,5 @@import { ClaudeRuntime } from "./runtime.js";+import { ClaudeAccessError } from "./access.js";import { createReadStream } from "node:fs";import { Readable } from "node:stream";import { addRoute, type RequestContext, type Route } from "../routes/registry.js";@@ -35,7 +36,9 @@ export function registerClaudeRoutes(input: {register("POST", "/sessions", async (ctx, workspace) => {const body = await ctx.request.json();if (body?.captureConsent !== true) throw new ApiError(400, "capture_consent_required", "Confirm private trace and environment capture");- return Response.json(await runtime.create(workspace.path, workspace.id, ctx.request.signal), {status: 201});+ if (body.model !== undefined && typeof body.model !== "string") throw new ApiError(400, "invalid_model", "Choose a Claude model");+ try { return Response.json(await runtime.create(workspace.path, workspace.id, ctx.request.signal, body.model), {status: 201}); }+ catch (error) { throw error instanceof ClaudeAccessError ? new ApiError(error.status, "claude_unavailable", error.message) : error; }});register("GET", "/sessions/:session", async ctx => Response.json(await runtime.get(ctx.params.session)));register("GET", "/sessions/:session/events", async ctx => Response.json(await runtime.events(ctx.params.session)));diff --git a/apps/server/src/claude-code/runtime.ts b/apps/server/src/claude-code/runtime.tsindex 387ba7dd..c0dc9964 100644--- a/apps/server/src/claude-code/runtime.ts+++ b/apps/server/src/claude-code/runtime.ts@@ -14,7 +14,7 @@ import { once } from "node:events";import { pipeline } from "node:stream/promises";import { createGzip, createGunzip } from "node:zlib";import { NativeCapture } from "./native-capture.js";-import { CAPTURE_POLICY_VERSION, CLAUDE_VERSION, CONTROLLER, DOCKERFILE, IMAGE, MANAGED_SETTINGS, MODEL, SDK_VERSION } from "./sandbox-assets.js";+import { CAPTURE_POLICY_VERSION, CLAUDE_MODEL_ID, CLAUDE_VERSION, CONTROLLER, DOCKERFILE, IMAGE, MANAGED_SETTINGS, MODEL, SDK_VERSION, managedSettings } from "./sandbox-assets.js";import { PACKAGE_JSON, LOCKFILE } from "./sandbox-lock.js";import { zipDirectory } from "./zip.js";import { REPLAY_ADAPTER } from "./replay-adapter.js";@@ -28,7 +28,8 @@ export type ClaudeBudgetSnapshot = {sessionLimitTokens?: number | null; sessionUsedTokens?: number; sessionRemainingTokens?: number | null;accountLimitTokens?: number; accountRemainingTokens?: number; accountScope?: "day" | "week"; accountResetAt?: string;};-export type ClaudeAccess = { owner: string; capabilities?: string[]; budget?: ClaudeBudgetSnapshot };+/** `models`: the Claude ids this account may run (the server's claude_code.models); `catalog`: what the picker shows every account; `reason`: why nothing may run (access.reason). */+export type ClaudeAccess = { owner: string; capabilities?: string[]; budget?: ClaudeBudgetSnapshot; models?: string[]; catalog?: {id: string; name: string}[]; reason?: string | null };export type ClaudeAuthorization = { sessionId: string; owner: string; model: string; workspaceId: string; contractSha256: string; refresh?: boolean };export type ClaudeGrant = {owner: string; baseUrl: string; token: string; sessionId: string; model: string;@@ -267,9 +268,10 @@ export class ClaudeRuntime {}async available() {const access = await this.access();- if (!access.capabilities?.includes("claude-code")) return {allowed: false, sandboxReady: false, model: MODEL, sdkVersion: SDK_VERSION};- try { await this.docker(["info", "--format", "{{.ServerVersion}}"], {timeout: 10_000}); return {allowed: true, sandboxReady: true, model: MODEL, sdkVersion: SDK_VERSION}; }- catch { return {allowed: true, sandboxReady: false, model: MODEL, sdkVersion: SDK_VERSION}; }+ const models = access.models ?? [], listed = {model: models[0] ?? MODEL, models, catalog: access.catalog ?? [], reason: access.reason ?? null, sdkVersion: SDK_VERSION};+ if (!access.capabilities?.includes("claude-code") || !models.length) return {allowed: false, sandboxReady: false, ...listed};+ try { await this.docker(["info", "--format", "{{.ServerVersion}}"], {timeout: 10_000}); return {allowed: true, sandboxReady: true, ...listed}; }+ catch { return {allowed: true, sandboxReady: false, ...listed}; }}async prepare(signal?: AbortSignal) {const job = this.reserve(`prepare:${randomUUID()}`, signal);@@ -350,12 +352,16 @@ export class ClaudeRuntime {try { await this.createContainer(session.container, checkpoint.image, false, signal, ownership); interrupted(signal); }catch (error) { await this.cleanupStartup(ownership); throw error; }}- async create(workspace: string, workspaceId: string, signal?: AbortSignal): Promise<ClaudeSession> {+ /** `model`: a catalog id the server lists for this account (default: its first). The session keeps it for good. */+ async create(workspace: string, workspaceId: string, signal?: AbortSignal, requested?: string): Promise<ClaudeSession> {const id = randomUUID(), job = this.reserve(id, signal), ownership = randomUUID();const container = `omnirush-claude-${id}`;let attempted = false;try {- const {owner} = await this.access(undefined, job.signal); await this.prepare(job.signal);+ const access = await this.access(undefined, job.signal);+ const {owner} = access, model = requested ?? access.models?.[0];+ if (!model || !CLAUDE_MODEL_ID.test(model) || !access.models?.includes(model)) throw new ClaudeAccessError(403, "This Claude model isn't available on your account yet");+ await this.prepare(job.signal);interrupted(job.signal);const root = await fsp.realpath(workspace);if (!(await fsp.stat(root)).isDirectory() || root === path.parse(root).root) throw new Error("Choose a project directory");@@ -371,19 +377,21 @@ export class ClaudeRuntime {await this.docker(["cp", `${root}${path.sep}.`, `${container}:/workspace/`], {signal: job.signal, timeout: 5 * 60_000});await this.docker(["start", container], {signal: job.signal});await this.docker(["exec", "--user", "root", container, "chown", "-R", "node:node", "/workspace"], {signal: job.signal});+ // The session's own model policy, root-owned, in the base checkpoint (the image carries MODEL's).+ if (model !== MODEL) await this.docker(["exec", "-i", "--user", "root", container, "sh", "-c", "cat > /etc/claude-code/managed-settings.json"], {input: managedSettings(model), signal: job.signal});await this.docker(["stop", "--time", "2", container], {signal: job.signal});const base = await this.checkpoint(container, dir, [], job.signal);await this.docker(["rm", container], {signal: job.signal});await this.createContainer(container, base.image, false, job.signal, ownership);interrupted(job.signal);const contract: ClaudeSessionContract = {- schema: 1, sessionId: id, owner, workspaceId, model: MODEL,- harness: this.harnessContract(),+ schema: 1, sessionId: id, owner, workspaceId, model,+ harness: this.harnessContract(model),execution: {kind: "docker", os: "linux", architecture: image.Architecture, workingDirectory: "/workspace", shell: "/bin/bash", runtimeImage: image.Id, baseImage: base.image, workspace: "session-copy"},capture: {policyVersion: CAPTURE_POLICY_VERSION, originals: "private", modelIsolation: "exact", scope: "managed-inference", network: "development-network-enabled", initialWorkspaceProvenance: "user-supplied-unattested"},};const contractSha256 = digest(JSON.stringify(contract));- const session: ClaudeSession = {schema: 1, id, owner, workspaceId, surface: this.options.surface, model: MODEL, sdkVersion: SDK_VERSION, claudeVersion: CLAUDE_VERSION, createdAt: new Date().toISOString(), container, base, turns: [], capture: "capturing", replay: "unverified", issues: [], contract, contractSha256, compatibility: "current", modelIsolation: initialModelIsolation(MODEL)};+ const session: ClaudeSession = {schema: 1, id, owner, workspaceId, surface: this.options.surface, model, sdkVersion: SDK_VERSION, claudeVersion: CLAUDE_VERSION, createdAt: new Date().toISOString(), container, base, turns: [], capture: "capturing", replay: "unverified", issues: [], contract, contractSha256, compatibility: "current", modelIsolation: initialModelIsolation(model)};save(path.join(dir, "policy", "contract.json"), {contract, sha256: contractSha256});save(path.join(dir, "session.json"), session); return session;} catch (e) {@@ -449,8 +457,8 @@ export class ClaudeRuntime {found.modelIsolation ??= initialModelIsolation(found.model, true);return found;}- private harnessContract(): ClaudeSessionContract["harness"] {- return {name: "claude-code", sdkVersion: SDK_VERSION, claudeVersion: CLAUDE_VERSION, controllerSha256: digest(CONTROLLER), lockSha256: digest(PACKAGE_JSON + "\n" + LOCKFILE), managedSettingsSha256: digest(MANAGED_SETTINGS), dockerfileSha256: digest(DOCKERFILE)};+ private harnessContract(model = MODEL): ClaudeSessionContract["harness"] {+ return {name: "claude-code", sdkVersion: SDK_VERSION, claudeVersion: CLAUDE_VERSION, controllerSha256: digest(CONTROLLER), lockSha256: digest(PACKAGE_JSON + "\n" + LOCKFILE), managedSettingsSha256: digest(managedSettings(model)), dockerfileSha256: digest(DOCKERFILE)};}private compatibility(session: ClaudeSession): NonNullable<ClaudeSession["compatibility"]> {if (!session.contract || !session.contractSha256) return "legacy_unverified";@@ -458,8 +466,8 @@ export class ClaudeRuntime {let saved: unknown;try { saved = JSON.parse(fs.readFileSync(path.join(this.dir(session.owner, session.id), "policy", "contract.json"), "utf8")); } catch { return "contract_invalid"; }if (!isRecord(saved) || !isRecord(saved.contract) || saved.sha256 !== session.contractSha256 || digest(JSON.stringify(saved.contract)) !== session.contractSha256 || digest(JSON.stringify(c)) !== session.contractSha256 ||- c.schema !== 1 || c.sessionId !== session.id || c.owner !== session.owner || c.workspaceId !== session.workspaceId || c.model !== session.model || c.model !== MODEL || c.execution?.baseImage !== session.base.image || c.execution?.kind !== "docker" || c.execution.os !== "linux" || c.execution.shell !== "/bin/bash" || c.execution.workingDirectory !== "/workspace") return "contract_invalid";- if (session.sdkVersion !== SDK_VERSION || session.claudeVersion !== CLAUDE_VERSION || JSON.stringify(c.harness) !== JSON.stringify(this.harnessContract()) || c.capture?.policyVersion !== CAPTURE_POLICY_VERSION) return "runtime_upgrade_required";+ c.schema !== 1 || c.sessionId !== session.id || c.owner !== session.owner || c.workspaceId !== session.workspaceId || c.model !== session.model || !CLAUDE_MODEL_ID.test(c.model) || c.execution?.baseImage !== session.base.image || c.execution?.kind !== "docker" || c.execution.os !== "linux" || c.execution.shell !== "/bin/bash" || c.execution.workingDirectory !== "/workspace") return "contract_invalid";+ if (session.sdkVersion !== SDK_VERSION || session.claudeVersion !== CLAUDE_VERSION || JSON.stringify(c.harness) !== JSON.stringify(this.harnessContract(session.model)) || c.capture?.policyVersion !== CAPTURE_POLICY_VERSION) return "runtime_upgrade_required";return "current";}private assertResumable(session: ClaudeSession) {@@ -711,7 +719,7 @@ export class ClaudeRuntime {broker = await this.broker(session, () => isolationStop.abort(), executionSignal);interrupted(executionSignal);const actual = await this.docker(["exec", session.container, "sha256sum", "/opt/claude/controller.mjs", "/etc/claude-code/managed-settings.json"], {signal: executionSignal});- if (actual.split("\n").map(line => line.split(/\s+/)[0]).join(":") !== `${digest(CONTROLLER)}:${digest(MANAGED_SETTINGS)}`) throw new Error("The sandbox controller or managed model policy changed");+ if (actual.split("\n").map(line => line.split(/\s+/)[0]).join(":") !== `${digest(CONTROLLER)}:${digest(managedSettings(session.model))}`) throw new Error("The sandbox controller or managed model policy changed");await this.docker(["exec", "-i", session.container, "node", "/opt/claude/controller.mjs"], {input: JSON.stringify({sessionId: session.id, resume: turn.number > 1, turn: turn.number, prompt, model: session.model, baseUrl: broker.baseUrl, token: broker.token}), signal: executionSignal, timeout: 60 * 60_000,stdout: bytes => { collector.recordStream("sdk", bytes, offset); offset += bytes.length; },diff --git a/apps/server/src/claude-code/sandbox-assets.ts b/apps/server/src/claude-code/sandbox-assets.tsindex fba8899e..3f0153b3 100644--- a/apps/server/src/claude-code/sandbox-assets.ts+++ b/apps/server/src/claude-code/sandbox-assets.ts@@ -2,11 +2,17 @@export const SDK_VERSION = "0.3.306";export const CLAUDE_VERSION = "2.1.306";export const IMAGE = `omnirush-claude-sdk:${SDK_VERSION}-3`;+/** The model baked into the runtime image's policy file; a session on another model replaces that file before its base checkpoint. */export const MODEL = "claude-opus-5-5";+/** A Claude catalog id (claude-<name>), the only shape a session may pin. */+export const CLAUDE_MODEL_ID = /^claude-[a-z0-9][a-z0-9.-]{0,62}$/;export const CAPTURE_POLICY_VERSION = "claude-native-2";+/** The family aliases denied for a session: every family but its own (Opus keeps its original ["sonnet", "haiku"]). */+export const deniedFamilies = (model: string) => ["opus", "sonnet", "haiku"].filter(family => !model.includes(family));// This is also passed as SDK managed policy. The on-disk copy is root-owned// so a project setting or tool cannot widen it for a nested Claude process.-export const MANAGED_SETTINGS = JSON.stringify({availableModels: [MODEL], availableModelsMatch: "exact", enforceAvailableModels: true, deniedModels: ["sonnet", "haiku"], allowManagedHooksOnly: true});+export const managedSettings = (model: string) => JSON.stringify({availableModels: [model], availableModelsMatch: "exact", enforceAvailableModels: true, deniedModels: deniedFamilies(model), allowManagedHooksOnly: true});+export const MANAGED_SETTINGS = managedSettings(MODEL);export const DOCKERFILE = `FROM node:22.21.1-bookworm-slimRUN apt-get update && apt-get install -y --no-install-recommends git ripgrep python3 python3-venv ca-certificates zip unzip procps && rm -rf /var/lib/apt/lists/*RUN corepack enable && corepack prepare [email protected] --activate@@ -82,7 +88,7 @@ try {...(request.resume ? {resume: request.sessionId} : {sessionId: request.sessionId}),persistSession: true, includePartialMessages: true, forwardSubagentText: true,includeHookEvents: true, settingSources: [],- managedSettings: {availableModels: [request.model], availableModelsMatch: 'exact', enforceAvailableModels: true, deniedModels: ['sonnet', 'haiku'], allowManagedHooksOnly: true},+ managedSettings: {availableModels: [request.model], availableModelsMatch: 'exact', enforceAvailableModels: true, deniedModels: ['opus', 'sonnet', 'haiku'].filter(family => !request.model.includes(family)), allowManagedHooksOnly: true},settings: {model: request.model, fallbackModel: []},systemPrompt: {type: 'preset', preset: 'claude_code'},permissionMode: 'bypassPermissions', allowDangerouslySkipPermissions: true,