Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(codex): support larger bounded images and isolated desktop trials
Alfredo Lopezdee3ec903900
diff --git a/codex-llm-proxy/src/config.ts b/codex-llm-proxy/src/config.tsindex ebe1ade2b..9f96bca4d 100644--- a/codex-llm-proxy/src/config.ts+++ b/codex-llm-proxy/src/config.ts@@ -5,6 +5,7 @@ export type CodexLlmProxyConfig = {adminPort: numberprobePort: numbermaxBodyBytes: number+ maxVisualBodyBytes: numbermaxStreamDurationMs: numbermaxDeadlineMs: numberjwtIssuer: string@@ -45,7 +46,12 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): CodexLlmProxyCenv.CODEX_LLM_PROXY_MAX_BODY_BYTES,LIMITS.maxRequestBodyBytes)- if (imageInputModels.length > 0 && maxBodyBytes < LIMITS.maxRequestBodyBytes) {+ const maxVisualBodyBytes = requiredPositiveInt(+ 'CODEX_LLM_PROXY_MAX_VISUAL_BODY_BYTES',+ env.CODEX_LLM_PROXY_MAX_VISUAL_BODY_BYTES,+ LIMITS.maxVisualRequestBodyBytes+ )+ if (imageInputModels.length > 0 && maxVisualBodyBytes < LIMITS.maxVisualRequestBodyBytes) {throw new Error('Visual Codex requests require the full shared envelope byte budget')}return {@@ -65,6 +71,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): CodexLlmProxyC9090),maxBodyBytes,+ maxVisualBodyBytes,maxStreamDurationMs: requiredPositiveInt('CODEX_LLM_PROXY_MAX_STREAM_DURATION_MS',env.CODEX_LLM_PROXY_MAX_STREAM_DURATION_MS,diff --git a/codex-llm-proxy/src/server.ts b/codex-llm-proxy/src/server.tsindex 9f03c1b25..8ae78fd32 100644--- a/codex-llm-proxy/src/server.ts+++ b/codex-llm-proxy/src/server.ts@@ -114,7 +114,23 @@ export function createProxyApps(})const runtimeApp = express()- runtimeApp.use(express.json({ limit: config.maxBodyBytes }))+ const ordinaryJson = express.json({ limit: config.maxBodyBytes })+ const visualJson = express.json({ limit: config.maxVisualBodyBytes })+ runtimeApp.use((req, res, next) => {+ // Only the image-capable completion endpoint with an already valid platform+ // identity may use the larger transport budget. V1 is still bounded by its+ // contract parser; admin and unauthenticated requests keep their old cap.+ if (+ req.method === 'POST' &&+ req.path === '/internal/runtime/v1/codex/completions' &&+ config.imageInputModels.length > 0 &&+ verifyPlatformJwt(bearer(req), config)+ ) {+ visualJson(req, res, next)+ return+ }+ ordinaryJson(req, res, next)+ })runtimeApp.post('/internal/runtime/v1/codex/completions', runtimeRateLimit, (req, res) => {if (!req.is('application/json')) {reject(res, 415, 'unsupported_media_type')@@ -129,6 +145,14 @@ export function createProxyApps(reject(res, 401, 'Unauthorized')return}+ const bodyLimit =+ req.body?.request?.schemaVersion === 'codex-completion-request.v2'+ ? config.maxVisualBodyBytes+ : config.maxBodyBytes+ if (Buffer.byteLength(JSON.stringify(req.body ?? {}), 'utf8') > bodyLimit) {+ reject(res, 413, 'payload_too_large')+ return+ }const extra = Object.keys(req.body ?? {}).find(key => !COMPLETION_KEYS.has(key))if (extra) {reject(res, 400, 'unknown_field')diff --git a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.tsindex 902d8e253..e17cfd5fd 100644--- a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts+++ b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts@@ -80,6 +80,7 @@ function config(): CodexLlmProxyConfig {adminPort: 0,probePort: 0,maxBodyBytes: 1_048_576,+ maxVisualBodyBytes: 24 * 1024 * 1024,maxStreamDurationMs: 30_000,maxDeadlineMs: 30_000,jwtIssuer: 'control-api',diff --git a/codex-llm-proxy/test/server.security.test.ts b/codex-llm-proxy/test/server.security.test.tsindex fd2ab6f55..d53dfc697 100644--- a/codex-llm-proxy/test/server.security.test.ts+++ b/codex-llm-proxy/test/server.security.test.ts@@ -19,6 +19,7 @@ function config(overrides: Partial<CodexLlmProxyConfig> = {}): CodexLlmProxyConfadminPort: 8081,probePort: 9090,maxBodyBytes: 1024,+ maxVisualBodyBytes: 24 * 1024 * 1024,maxStreamDurationMs: 300_000,maxDeadlineMs: 300_000,jwtIssuer: 'control-api',@@ -151,6 +152,48 @@ describe('codex-llm-proxy security surface', () => {expect(res.status).toBe(413)})+ it('reserves the larger transport budget for authenticated visual requests', async () => {+ const { runtimeApp, adminApp } = createProxyApps(+ config({ maxBodyBytes: 1_048_576, imageInputModels: ['gpt-5.1'] })+ )+ // Deliberately invalid ticket: this test checks parser admission and the+ // unchanged ticket gate, without redeeming or contacting any model.+ const payload = {+ executionTicket: 'invalid-ticket',+ requestHash: 'a'.repeat(64),+ request: { schemaVersion: 'codex-completion-request.v2', pad: 'x'.repeat(10 * 1024 * 1024) },+ }+ const admitted = await request(runtimeApp)+ .post('/internal/runtime/v1/codex/completions')+ .set('Authorization', `Bearer ${platformToken()}`)+ .send(payload)+ expect(admitted.status).toBe(403)+ expect(admitted.body.error).toBe('ticket_invalid')++ const anonymous = await request(runtimeApp)+ .post('/internal/runtime/v1/codex/completions')+ .send(payload)+ expect(anonymous.status).toBe(413)+ const noScope = await request(runtimeApp)+ .post('/internal/runtime/v1/codex/completions')+ .set('Authorization', `Bearer ${platformToken({ workflowControlScopes: [] })}`)+ .send(payload)+ expect(noScope.status).toBe(413)+ const v1 = await request(runtimeApp)+ .post('/internal/runtime/v1/codex/completions')+ .set('Authorization', `Bearer ${platformToken()}`)+ .send({+ ...payload,+ request: { ...payload.request, schemaVersion: 'codex-completion-request.v1' },+ })+ expect(v1.status).toBe(413)+ const admin = await request(adminApp)+ .post('/internal/admin/v1/codex/models')+ .set('Authorization', `Bearer ${adminPermit()}`)+ .send(payload)+ expect(admin.status).toBe(413)+ })+it('rejects a platform JWT whose hostRefs do not bind the ticket hostRef', async () => {const { runtimeApp } = createProxyApps(config())const foreign = sign(@@ -291,7 +334,7 @@ describe('codex-llm-proxy security surface', () => {loadConfig({CODEX_LLM_PROXY_JWT_PUBLIC_KEY: publicKey,CODEX_IMAGE_INPUT_MODELS: 'gpt-5.1',- CODEX_LLM_PROXY_MAX_BODY_BYTES: '1024',+ CODEX_LLM_PROXY_MAX_VISUAL_BODY_BYTES: '1024',})).toThrow(/shared envelope byte budget/)expect(diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex fa7611520..94148d62e 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.552",+ "version": "0.1.553","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.552",+ "version": "0.1.553","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --git a/control-api/package.json b/control-api/package.jsonindex 8211afaca..989dbe548 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.552",+ "version": "0.1.553","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.tsindex de09b46ba..c9bcdb223 100644--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts@@ -1,9 +1,9 @@import {- LIMITS,buildCodexProxyEnvelope,computeCodexPolicyHash,hashCodexCompletionRequest,parseCodexCompletionRequest,+ requestBodyLimitBytes,} from '@clerum/llm-provider-attempt-contract'import { config } from '../config.js'import { type DbClient, pool, withTransaction } from '../db.js'@@ -195,7 +195,7 @@ export async function authorizeLlmProviderAttempt(throw new LlmProviderAttemptAuthorizeError('invalid_request', 'body must be an object')}const serialized = JSON.stringify(body)- if (Buffer.byteLength(serialized, 'utf8') > LIMITS.maxRequestBodyBytes) {+ if (Buffer.byteLength(serialized, 'utf8') > requestBodyLimitBytes(body.request)) {throw new LlmProviderAttemptAuthorizeError('invalid_request', 'request body exceeds the limit')}const unknown = firstUnknownKey(body)diff --git a/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts b/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.tsindex ae69b7ef4..cf4566c99 100644--- a/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts@@ -304,7 +304,15 @@ describeRealPostgres('Codex provider-attempt authorization on real PostgreSQL',)expect(registered.rows).toHaveLength(1)signed = true- return issued+ // The request's text budget stays at 1 MiB. Inject an oversized+ // return value only after a real ticket/reservation exists in+ // this transaction, to prove the final envelope guard rolls+ // back database writes. This value never leaves the test.+ return {+ ...issued,+ executionTicket:+ issued.executionTicket + 'x'.repeat(LIMITS.maxVisualRequestBodyBytes),+ }},}))diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.tsindex 6ccf08fe2..271599ab3 100644--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import { readFileSync } from 'node:fs'+import { crc32 } from 'node:zlib'import { LIMITS, hashCodexCompletionRequestV1 } from '@clerum/llm-provider-attempt-contract'import { streamCodexCompletion } from '../../codex-llm-proxy/src/codexTransport'import {@@ -160,9 +161,11 @@ describe('authorizeLlmProviderAttempt', () => {['jpeg', 'attachment', true],['png', 'tool', true],['jpeg', 'tool', false],+ ['png', 'attachment', false, 10 * 1024 * 1024],+ ['png', 'tool', true, 5 * 1024 * 1024],] as const)('carries %s from %s (tools=%s) through Host authorization and proxy projection',- async (format, origin, withTools) => {+ async (format, origin, withTools, imageBytes = 0) => {const fixtures = JSON.parse(readFileSync(new URL(@@ -253,6 +256,22 @@ describe('authorizeLlmProviderAttempt', () => {const image = fixtures[format].messages[0].contentParts.find((part: { type: string }) => part.type === 'image')+ if (imageBytes > 0) {+ // Preserve the real PNG pixels and add a standards-compliant ancillary+ // text chunk to exercise actual byte transport, not a forged header.+ const png = Buffer.from(image.data, 'base64')+ const payload = Buffer.alloc(imageBytes - png.length - 12, 65)+ Buffer.from('Comment\0').copy(payload)+ const chunk = Buffer.alloc(payload.length + 12)+ chunk.writeUInt32BE(payload.length)+ chunk.write('tEXt', 4)+ payload.copy(chunk, 8)+ chunk.writeUInt32BE(crc32(chunk.subarray(4, -4)) >>> 0, chunk.length - 4)+ image.data = Buffer.concat([png.subarray(0, -12), chunk, png.subarray(-12)]).toString(+ 'base64'+ )+ expect(Buffer.from(image.data, 'base64')).toHaveLength(imageBytes)+ }let messages = fixtures[format].messagesif (origin === 'tool') {image.source = { kind: 'tool', attachmentId: 'fixture-image', toolCallId: 'fixture-call' }@@ -324,9 +343,10 @@ describe('authorizeLlmProviderAttempt', () => {throw error}},- // A bounded synthetic signed envelope contribution; no live account material.+ // Fault injection at the signing seam: exercise the post-signing envelope+ // guard without exceeding the unchanged 1 MiB non-image request budget.issueTicket: vi.fn().mockResolvedValue({- executionTicket: 't'.repeat(4096),+ executionTicket: 't'.repeat(LIMITS.maxVisualRequestBodyBytes),expiresAt: new Date('2026-09-16T23:00:00Z'),}),})diff --git a/desktop-app/scripts/start-isolated-app.mjs b/desktop-app/scripts/start-isolated-app.mjsnew file mode 100644index 000000000..fcf0bad3e--- /dev/null+++ b/desktop-app/scripts/start-isolated-app.mjs@@ -0,0 +1,348 @@+/**+ * Run one ISOLATED dev instance of the Evenfire desktop app.+ *+ * Purpose: three PRs (and three minikube targets) have to run the desktop app at+ * the same time on one machine. A normal launch cannot do that because three+ * pieces of state are machine-wide: the `evenfire:`/`clerum:` OS protocol+ * handler, the application name `Evenfire`, and the user-data directory holding+ * the Chromium profile and the stored runtime-config profiles.+ *+ * This launcher therefore gives each run:+ *+ * - its own per-run directory under the platform application-support+ * directory (never inside the repository, so profile material cannot end up+ * in the worktree, in commits or in notes);+ * - a `--user-data-dir` inside that directory, plus+ * `CLERUM_DESKTOP_CONFIG_PATH` pointing at a file inside it, so the runtime+ * config layer cannot read the developer's shared `runtime-configs`+ * directory even before Electron is ready;+ * - explicit loopback REST/RPC endpoints taken from the command line;+ * - a unique visible identity (`PR660 · Minikube30488`) that the app applies to+ * the process name, the application name and the window title.+ *+ * The app then refuses to register OS protocol handlers and refuses to process+ * deep links, and it verifies the effective runtime (real userData, app path,+ * endpoints, config storage path) against this declaration before initializing+ * any service. A divergence aborts the launch instead of falling back to the+ * shared profile.+ *+ * Safety properties of this script:+ * - it never copies or reads a session, a keychain entry, a `.env` file or any+ * private config; it only creates a fresh directory and inspects the+ * Electron binary and the existing build;+ * - it never kills, reuses or adopts another instance, and it refuses+ * `--force-*` passthrough flags;+ * - the default action is to PRINT THE PLAN. It only spawns Electron with an+ * explicit `--launch`, which is what keeps this launcher dormant until the+ * main coordinator wires it up with #654/#651.+ *+ * Usage:+ * node scripts/start-isolated-app.mjs --target <profile-label> --pr <number> \+ * --rest-url <rest-origin> --rpc-url <rpc-origin>+ * node scripts/start-isolated-app.mjs ... --launch+ *+ * Options:+ * --target <slug> required, e.g. minikube-30488 (safe slug, 1-64 chars)+ * --rest-url <url> required, loopback http(s) URL with an explicit port+ * --rpc-url <url> required, loopback http(s) URL with an explicit port+ * --pr <number> optional, digits only; makes the label `PR<n> · …`+ * --base-dir <path> optional, absolute parent for the per-run directory+ * (default: platform application-support directory)+ * --launch spawn Electron (default: print the plan only)+ * --json print the plan as JSON instead of one log line+ * --help print usage+ * -- <args...> extra Electron arguments (no `--force-*`, no+ * `--user-data-dir`: this script owns both)+ */+import { spawn } from 'node:child_process'+import fs from 'node:fs'+import { createRequire } from 'node:module'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++const require = createRequire(import.meta.url)+const projectDirectory = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')+const repoRoot = path.resolve(projectDirectory, '..')++function fail(message) {+ console.error(`[dev-isolation] ${message}`)+ process.exitCode = 1+ return null+}++/**+ * The contract lives in `src/devIsolation.ts`; the launcher consumes the+ * existing compiled build so the two can never disagree about paths, identity+ * or validation.+ */+function loadContract() {+ const compiled = path.join(projectDirectory, 'dist', 'devIsolation.js')+ if (!fs.existsSync(compiled)) {+ fail(+ `missing ${compiled}. Build the main process first: ` ++ `(cd ${path.relative(repoRoot, projectDirectory)} && npm run build:main)`+ )+ return null+ }+ try {+ return require(compiled)+ } catch (error) {+ fail(`could not load ${compiled}: ${error instanceof Error ? error.message : error}`)+ return null+ }+}++function parseArgs(argv) {+ const options = { launch: false, json: false, passthrough: [] }+ for (let index = 0; index < argv.length; index += 1) {+ const argument = argv[index]+ if (argument === '--') {+ options.passthrough = argv.slice(index + 1)+ break+ }+ if (argument === '--launch') {+ options.launch = true+ continue+ }+ if (argument === '--json') {+ options.json = true+ continue+ }+ if (argument === '--help' || argument === '-h') {+ options.help = true+ continue+ }+ const next = argv[index + 1]+ const readValue = name => {+ if (typeof next !== 'string' || next.startsWith('--')) {+ fail(`${name} requires a value`)+ return null+ }+ index += 1+ return next+ }+ if (argument === '--target') options.target = readValue('--target')+ else if (argument === '--pr') options.pr = readValue('--pr')+ else if (argument === '--rest-url') options.restUrl = readValue('--rest-url')+ else if (argument === '--rpc-url') options.rpcUrl = readValue('--rpc-url')+ else if (argument === '--base-dir') options.baseDir = readValue('--base-dir')+ else {+ fail(`unknown argument ${argument}`)+ return null+ }+ if (options.target === null || options.pr === null) return null+ if (options.restUrl === null || options.rpcUrl === null || options.baseDir === null) return null+ }+ return options+}++function assertPassthroughAllowed(passthrough) {+ for (const argument of passthrough) {+ if (argument.startsWith('--force-')) {+ return fail(`refusing passthrough flag ${argument}: forced flags are not allowed`)+ }+ if (argument === '--user-data-dir' || argument.startsWith('--user-data-dir=')) {+ return fail('refusing passthrough --user-data-dir: the launcher owns the isolated profile')+ }+ }+ return true+}++function resolveElectronBinary() {+ let binary+ try {+ binary = require('electron')+ } catch {+ return fail('Electron is not installed. Run: (cd desktop-app && npm run verify:electron)')+ }+ if (typeof binary !== 'string' || !binary) {+ return fail(+ 'Electron runtime path is unavailable. Run: (cd desktop-app && npm run verify:electron)'+ )+ }+ try {+ fs.accessSync(binary, process.platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK)+ } catch {+ return fail(`Electron runtime is not executable at ${binary}. Run: npm run verify:electron`)+ }+ return binary+}++function createRunDirectory(contract, options) {+ const baseDirResult = contract.admitIsolationBaseDir({+ requested: options.baseDir,+ repoRoot,+ platform: process.platform,+ homedir: os.homedir(),+ env: process.env,+ })+ if (!baseDirResult.ok) {+ return fail(`${baseDirResult.code}: ${baseDirResult.message}`)+ }+ const prefix = ['evenfire', options.pr ? `pr${options.pr}` : '', options.target, '']+ .filter(Boolean)+ .join('-')+ fs.mkdirSync(baseDirResult.baseDir, { recursive: true, mode: 0o700 })+ const realBase = fs.realpathSync.native(baseDirResult.baseDir)+ const realAdmission = contract.admitIsolationBaseDir({+ requested: realBase,+ repoRoot: fs.realpathSync.native(repoRoot),+ platform: process.platform,+ homedir: os.homedir(),+ env: process.env,+ })+ if (!realAdmission.ok) return fail(realAdmission.code)+ const runDir = fs.mkdtempSync(path.join(realBase, `${prefix}-`))+ const runPaths = contract.devIsolationPaths(runDir)+ fs.mkdirSync(runPaths.userDataDir, { recursive: true, mode: 0o700 })+ return runPaths+}++function childEnvironment(contract, runPaths, options, appPath) {+ return {+ ...process.env,+ [contract.DEV_ISOLATION_ENABLE_ENV]: '1',+ [contract.DEV_ISOLATION_ENV.runDir]: runPaths.runDir,+ [contract.DEV_ISOLATION_ENV.restUrl]: options.restUrl,+ [contract.DEV_ISOLATION_ENV.rpcUrl]: options.rpcUrl,+ [contract.DEV_ISOLATION_ENV.target]: options.target,+ ...(options.pr ? { [contract.DEV_ISOLATION_ENV.pr]: options.pr } : {}),+ [contract.DEV_ISOLATION_ENV.appPath]: appPath,+ EXTERNAL_REST_API_BASE_URL: options.restUrl,+ RPC_PROXY_BASE_URL: options.rpcUrl,+ EVENFIRE_RENDERER_URL: '',+ // Second isolation layer: the runtime-config layer reads this file instead+ // of the shared `runtime-configs` directory, including before Electron ready.+ CLERUM_DESKTOP_CONFIG_PATH: runPaths.configPath,+ }+}++function planRecord(plan, runPaths, electronBinary, entrypoint, launch) {+ return {+ kind: 'evenfire-dev-isolation-plan',+ mode: launch ? 'launch' : 'plan-only',+ target: plan.identity.target,+ label: plan.label,+ appName: plan.appName,+ runDir: runPaths.runDir,+ userDataDir: runPaths.userDataDir,+ configPath: runPaths.configPath,+ restUrl: plan.restUrl,+ rpcUrl: plan.rpcUrl,+ appPath: plan.appPath ?? '',+ electron: electronBinary ?? '',+ entrypoint,+ }+}++function printRecord(contract, record, json) {+ if (json) {+ console.log(JSON.stringify(record, null, 2))+ return+ }+ console.log(contract.formatDevIsolationLogLine(record))+}++function writeRunMetadata(runPaths, record, pid) {+ const metadata = { ...record, pid }+ const temporary = `${runPaths.recordPath}.tmp`+ fs.writeFileSync(temporary, `${JSON.stringify(metadata, null, 2)}\n`, { mode: 0o600 })+ fs.renameSync(temporary, runPaths.recordPath)+ fs.writeFileSync(runPaths.pidPath, `${pid}\n`, { mode: 0o600 })+}++function launch(contract, plan, runPaths, options, electronBinary, entrypoint, record) {+ const env = childEnvironment(contract, runPaths, options, path.dirname(entrypoint))+ // Self-check with the same contract the app applies: a declaration this+ // launcher cannot itself validate must never reach Electron.+ const decision = contract.resolveDevIsolation(env, [+ contract.DEV_ISOLATION_FLAG,+ '--user-data-dir',+ runPaths.userDataDir,+ ])+ if (decision.mode !== 'isolated') {+ const detail =+ decision.mode === 'refused' ? `${decision.code}: ${decision.message}` : decision.mode+ return fail(`the launcher's own declaration does not validate: ${detail}`)+ }++ const child = spawn(+ electronBinary,+ [`--user-data-dir=${runPaths.userDataDir}`, contract.DEV_ISOLATION_FLAG, entrypoint],+ { env, cwd: projectDirectory, stdio: 'inherit' }+ )+ if (typeof child.pid !== 'number') {+ return fail('Electron did not start')+ }+ writeRunMetadata(runPaths, record, child.pid)+ console.log(`[dev-isolation] launched pid=${child.pid} entrypoint=${entrypoint}`)+ console.log(`[dev-isolation] metadata=${runPaths.recordPath}`)++ for (const signal of ['SIGINT', 'SIGTERM']) {+ process.once(signal, () => child.kill(signal))+ }+ child.once('error', error => {+ console.error(`[dev-isolation] Electron failed to start: ${error.message}`)+ process.exitCode = 1+ })+ child.once('exit', (code, signal) => {+ process.exitCode = signal ? 1 : (code ?? 0)+ })+ return true+}++function main() {+ const options = parseArgs(process.argv.slice(2))+ if (!options) return+ if (options.help) {+ console.log('See the header of scripts/start-isolated-app.mjs for usage.')+ return+ }+ if (!options.target || !options.restUrl || !options.rpcUrl) {+ fail('--target, --rest-url and --rpc-url are required')+ return+ }+ if (!assertPassthroughAllowed(options.passthrough)) return++ const contract = loadContract()+ if (!contract) return++ const entrypoint = path.join(projectDirectory, 'dist', 'main.js')+ if (!fs.existsSync(entrypoint)) {+ fail(`missing ${entrypoint}. Build first: (cd desktop-app && npm run build:main)`)+ return+ }+ const electronBinary = resolveElectronBinary()+ if (!electronBinary) return++ const runPaths = createRunDirectory(contract, options)+ if (!runPaths) return++ const env = childEnvironment(contract, runPaths, options, path.dirname(entrypoint))+ const decision = contract.resolveDevIsolation(env, [+ contract.DEV_ISOLATION_FLAG,+ '--user-data-dir',+ runPaths.userDataDir,+ ])+ if (decision.mode !== 'isolated') {+ const detail =+ decision.mode === 'refused' ? `${decision.code}: ${decision.message}` : decision.mode+ fail(`the launcher's declaration does not validate: ${detail}`)+ return+ }+ const plan = decision.plan+ const record = planRecord(plan, runPaths, electronBinary, entrypoint, options.launch)+ printRecord(contract, record, options.json)++ if (!options.launch) {+ console.log(+ '[dev-isolation] plan only: nothing was launched. ' ++ 'Re-run with --launch once the coordinator enables the isolated lane.'+ )+ return+ }+ launch(contract, plan, runPaths, options, electronBinary, entrypoint, record)+}++main()diff --git a/desktop-app/src/__tests__/devIsolation.test.ts b/desktop-app/src/__tests__/devIsolation.test.tsnew file mode 100644index 000000000..25500d548--- /dev/null+++ b/desktop-app/src/__tests__/devIsolation.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from 'vitest'+import {+ admitIsolationBaseDir,+ devIsolationRuntimePolicy,+ publicDevIsolationRecord,+ resolveDevIsolation,+ verifyDevIsolationRuntime,+} from '../devIsolation'++const env = {+ EVENFIRE_DEV_ISOLATION: '1',+ EVENFIRE_DEV_ISOLATION_RUN_DIR: '/tmp/isolated-run',+ EVENFIRE_DEV_ISOLATION_TARGET: 'minikube-30488',+ EVENFIRE_DEV_ISOLATION_PR: '660',+ EVENFIRE_DEV_ISOLATION_REST_URL: 'http://127.0.0.1:30579',+ EVENFIRE_DEV_ISOLATION_RPC_URL: 'http://127.0.0.1:30582',+ EVENFIRE_DEV_ISOLATION_APP_PATH: '/repo/desktop-app/dist',+ EXTERNAL_REST_API_BASE_URL: 'http://127.0.0.1:30579',+ RPC_PROXY_BASE_URL: 'http://127.0.0.1:30582',+ CLERUM_DESKTOP_CONFIG_PATH: '/tmp/isolated-run/runtime-config.json',+}+const argv = [+ 'electron',+ '--user-data-dir=/tmp/isolated-run/user-data',+ '/repo/desktop-app/dist/main.js',+]++describe('explicit development instance isolation', () => {+ it('leaves normal packaged and development launches unchanged', () => {+ expect(resolveDevIsolation({}, [], false)).toEqual({ mode: 'normal' })+ expect(resolveDevIsolation({}, [], true)).toEqual({ mode: 'normal' })+ expect(devIsolationRuntimePolicy(null)).toMatchObject({+ registerOsProtocols: true,+ acceptDeepLinks: true,+ pinWindowTitle: false,+ })+ })+ it('refuses an opt-in in a packaged application', () => {+ expect(resolveDevIsolation(env, argv, true)).toMatchObject({+ mode: 'refused',+ code: 'DEV_ISOLATION_PACKAGED',+ })+ })+ it('requires the explicit directory before single-instance/protocol setup', () => {+ expect(resolveDevIsolation(env, [])).toMatchObject({ mode: 'refused' })+ expect(resolveDevIsolation(env, ['--user-data-dir=/tmp/another-run'])).toMatchObject({+ mode: 'refused',+ })+ })+ it.each(['CLERUM_DESKTOP_CONFIG_PATH', 'EXTERNAL_REST_API_BASE_URL', 'RPC_PROXY_BASE_URL'])(+ 'refuses missing or divergent %s',+ key => {+ expect(resolveDevIsolation({ ...env, [key]: '' }, argv)).toMatchObject({ mode: 'refused' })+ expect(resolveDevIsolation({ ...env, [key]: 'http://127.0.0.1:33333' }, argv)).toMatchObject({+ mode: 'refused',+ })+ }+ )+ it.each([+ 'https://example.com:443',+ 'http://user:[email protected]:30579',+ 'http://127.0.0.1:30579/?private=value',+ ])('refuses unsafe endpoint %s', value => {+ expect(+ resolveDevIsolation(+ { ...env, EVENFIRE_DEV_ISOLATION_REST_URL: value, EXTERNAL_REST_API_BASE_URL: value },+ argv+ )+ ).toMatchObject({ mode: 'refused' })+ })+ it('isolates OS routing and verifies effective identity before exposing metadata', () => {+ const result = resolveDevIsolation(env, argv)+ expect(result.mode).toBe('isolated')+ if (result.mode !== 'isolated') throw new Error('expected isolated plan')+ const { plan } = result+ expect(devIsolationRuntimePolicy(plan)).toMatchObject({+ registerOsProtocols: false,+ acceptDeepLinks: false,+ pinWindowTitle: true,+ })+ expect(plan.label).toContain('PR660')+ const observed = {+ pid: 123,+ userDataDir: plan.userDataDir,+ appPath: plan.appPath!,+ restUrl: plan.restUrl,+ rpcUrl: plan.rpcUrl,+ configStoragePath: plan.configPath,+ envKey: 'fixture-environment',+ }+ expect(verifyDevIsolationRuntime(plan, observed)).toEqual({ ok: true })+ expect(publicDevIsolationRecord(plan, observed).pid).toBe(123)+ for (const key of ['userDataDir', 'appPath', 'restUrl', 'rpcUrl', 'configStoragePath']) {+ const wrong = { ...observed, [key]: 'foreign-value' }+ expect(verifyDevIsolationRuntime(plan, wrong).ok).toBe(false)+ expect(() => publicDevIsolationRecord(plan, wrong)).toThrow('before runtime verification')+ }+ })+ it('rejects application data inside the checkout', () => {+ expect(+ admitIsolationBaseDir({+ requested: '/repo/private-run',+ repoRoot: '/repo',+ platform: 'darwin',+ homedir: '/home/user',+ env: {},+ })+ ).toMatchObject({ ok: false })+ })+})diff --git a/desktop-app/src/devIsolation.ts b/desktop-app/src/devIsolation.tsnew file mode 100644index 000000000..176c3fd7c--- /dev/null+++ b/desktop-app/src/devIsolation.ts@@ -0,0 +1,603 @@+/**+ * Desktop dev-isolation contract.+ *+ * Three PRs have to be able to run the desktop app side by side on one machine.+ * Today they cannot, because three pieces of state are machine-wide:+ *+ * - the OS protocol handler. `registerCustomProtocols()` makes the *running*+ * bundle the default handler for `evenfire:`/`clerum:`, so whoever launches+ * last steals the deep links of everyone else — and a computer-use agent+ * that resolves the app by name lands on an arbitrary instance.+ * - the application name (`Evenfire`), which is exactly what a computer-use+ * agent has to disambiguate between.+ * - the user-data directory, which holds the Chromium profile, the stored+ * runtime-config profiles and the session material.+ *+ * This module is the pure contract for the explicit, opt-in isolation mode that+ * removes that sharing. It owns:+ *+ * - the opt-in itself (`--evenfire-dev-isolation` or+ * `EVENFIRE_DEV_ISOLATION=1`), so that a normal launch can never drift into+ * isolated behaviour and an isolated launch can never silently fall back to+ * the shared profile;+ * - validation of what the launcher declared: an absolute per-run directory, a+ * template of paths under it, loopback endpoints with explicit ports and no+ * embedded credentials, and a safe target slug;+ * - the derived visible identity (`PR660 · Minikube30488` plus an ASCII app+ * name) used for the process title, `app.setName` and the window title;+ * - the runtime policy that states, in one place, that an isolated run must+ * not register OS protocols and must not process deep links;+ * - verification of the *effective* runtime (real userData, app path,+ * endpoints, config storage path) against the declaration, so a divergence+ * aborts instead of quietly reading a shared profile.+ *+ * The module performs no I/O, imports nothing from Electron, and never reads a+ * profile, a keychain entry, an environment dump or a secret: the caller passes+ * in what it observed. That keeps every security-relevant invariant testable+ * without launching a GUI.+ *+ * Nothing here changes the normal startup path. With no opt-in the only result+ * is `{ mode: 'normal' }`, and callers keep today's behaviour unchanged.+ */+import path from 'node:path'++/** Opt-in flag accepted on the command line. */+export const DEV_ISOLATION_FLAG = '--evenfire-dev-isolation'+/** Opt-in environment variable; `1`/`true` enable, `0`/`false`/unset do not. */+export const DEV_ISOLATION_ENABLE_ENV = 'EVENFIRE_DEV_ISOLATION'++/**+ * Payload the launcher declares. Only the run directory, the two endpoints, the+ * target slug and (optionally) the PR number and expected app path are needed;+ * every other value is derived here so the launcher and the app cannot disagree+ * about names or paths.+ */+export const DEV_ISOLATION_ENV = {+ runDir: 'EVENFIRE_DEV_ISOLATION_RUN_DIR',+ restUrl: 'EVENFIRE_DEV_ISOLATION_REST_URL',+ rpcUrl: 'EVENFIRE_DEV_ISOLATION_RPC_URL',+ target: 'EVENFIRE_DEV_ISOLATION_TARGET',+ pr: 'EVENFIRE_DEV_ISOLATION_PR',+ appPath: 'EVENFIRE_DEV_ISOLATION_APP_PATH',+} as const++export const DEV_ISOLATION_USER_DATA_DIR_NAME = 'user-data'+export const DEV_ISOLATION_CONFIG_FILE_NAME = 'runtime-config.json'+export const DEV_ISOLATION_RECORD_FILE_NAME = 'run.json'+export const DEV_ISOLATION_PID_FILE_NAME = 'run.pid'+/** Prefix of the shared default app name; an isolated name must extend it. */+export const DEV_ISOLATION_APP_NAME_PREFIX = 'Evenfire'++const ENABLED_VALUES = new Set(['1', 'true'])+const DISABLED_VALUES = new Set(['0', 'false'])+const TARGET_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/+const PR_PATTERN = /^[0-9]{1,6}$/+// The visible label may contain the middle dot the operator reads; the app name+// stays plain ASCII because it becomes a process and application name.+const LABEL_PATTERN = /^[\x20-\x7e\u00b7]{1,80}$/+const APP_NAME_PATTERN = /^[\x20-\x7e]{1,64}$/+const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]'])++export type DevIsolationEnablement = 'disabled' | 'enabled' | 'invalid'++/**+ * Read the opt-in. An unrecognized value is `invalid` rather than `disabled`:+ * a typo must refuse the launch instead of quietly starting the shared-profile+ * app the operator was trying to avoid.+ */+export function readDevIsolationEnablement(+ env: NodeJS.ProcessEnv,+ argv: readonly string[]+): DevIsolationEnablement {+ const raw = String(env[DEV_ISOLATION_ENABLE_ENV] ?? '')+ .trim()+ .toLowerCase()+ const flagged = argv.includes(DEV_ISOLATION_FLAG)+ if (ENABLED_VALUES.has(raw) || flagged) return 'enabled'+ if (raw === '' || DISABLED_VALUES.has(raw)) return 'disabled'+ return 'invalid'+}++export type DevIsolationPaths = {+ runDir: string+ userDataDir: string+ configPath: string+ recordPath: string+ pidPath: string+}++/** Template of the per-run paths, derived from the run directory alone. */+export function devIsolationPaths(runDir: string): DevIsolationPaths {+ const root = path.resolve(runDir)+ return {+ runDir: root,+ userDataDir: path.join(root, DEV_ISOLATION_USER_DATA_DIR_NAME),+ configPath: path.join(root, DEV_ISOLATION_CONFIG_FILE_NAME),+ recordPath: path.join(root, DEV_ISOLATION_RECORD_FILE_NAME),+ pidPath: path.join(root, DEV_ISOLATION_PID_FILE_NAME),+ }+}++export type DevIsolationIdentity = {+ target: string+ pr: string | null+ /** Visible, non-ASCII-safe label, e.g. `PR660 · Minikube30488`. */+ label: string+ /** Process and application name, e.g. `Evenfire PR660 Minikube30488`. */+ appName: string+}++function titleCaseToken(value: string): string {+ return value+ .split(/[^A-Za-z0-9]+/)+ .filter(Boolean)+ .map(token => token.charAt(0).toUpperCase() + token.slice(1).toLowerCase())+ .join('')+}++/**+ * Derive the unique visible identity from the target slug and the optional PR+ * number. Deterministic: the launcher and the app compute the same value from+ * the same inputs, so a drifted name is a detectable divergence, not a silent+ * difference.+ */+export function deriveDevIsolationIdentity(input: {+ target: string+ pr?: string | null+}): DevIsolationIdentity {+ const target = String(input.target ?? '').trim()+ const pr = typeof input.pr === 'string' && input.pr.trim() ? input.pr.trim() : null+ const targetLabel = titleCaseToken(target) || 'Target'+ const prLabel = pr ? `PR${pr}` : ''+ const label = prLabel ? `${prLabel} \u00b7 ${targetLabel}` : targetLabel+ const appName = `${DEV_ISOLATION_APP_NAME_PREFIX} ${[prLabel, targetLabel]+ .filter(Boolean)+ .join(' ')}`+ return { target, pr, label, appName }+}++/**+ * A loopback endpoint with an explicit port and no embedded credentials. This+ * is deliberately strict: an isolated run must not be pointable at a shared or+ * remote deployment by a mistyped or hostile input, and a URL that carries a+ * user/password must never reach the public run record.+ */+export function isLoopbackEndpointUrl(value: string): boolean {+ const raw = String(value ?? '').trim()+ if (!raw) return false+ let url: URL+ try {+ url = new URL(raw)+ } catch {+ return false+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false+ if (url.username || url.password) return false+ if (!LOOPBACK_HOSTS.has(url.hostname)) return false+ if (!url.port) return false+ const port = Number(url.port)+ if (!Number.isInteger(port) || port < 1 || port > 65535) return false+ if (url.pathname !== '/' || url.search || url.hash) return false+ return true+}++/** Strict containment: a path equal to `parent` is not "inside" it. */+export function isPathInside(parent: string, child: string): boolean {+ const from = path.resolve(parent)+ const to = path.resolve(child)+ if (from === to) return false+ const prefix = from.endsWith(path.sep) ? from : `${from}${path.sep}`+ return to.startsWith(prefix)+}++export type DevIsolationPlan = DevIsolationPaths & {+ restUrl: string+ rpcUrl: string+ appPath: string | null+ identity: DevIsolationIdentity+ label: string+ appName: string+}++export type DevIsolationRefusal = { code: string; message: string }+export type DevIsolationPlanResult =+ | { ok: true; plan: DevIsolationPlan }+ | ({ ok: false } & DevIsolationRefusal)++/**+ * Validate the launcher's declaration and build the plan. Every failure is a+ * refusal, never a fallback: the caller aborts.+ */+export function buildDevIsolationPlan(env: NodeJS.ProcessEnv): DevIsolationPlanResult {+ const rawRunDir = String(env[DEV_ISOLATION_ENV.runDir] ?? '').trim()+ if (!rawRunDir) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_RUN_DIR_REQUIRED',+ message: `${DEV_ISOLATION_ENV.runDir} is required`,+ }+ }+ if (!path.isAbsolute(rawRunDir)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_RUN_DIR_NOT_ABSOLUTE',+ message: `${DEV_ISOLATION_ENV.runDir} must be an absolute path`,+ }+ }++ const rawTarget = String(env[DEV_ISOLATION_ENV.target] ?? '').trim()+ if (!TARGET_PATTERN.test(rawTarget)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_TARGET_INVALID',+ message: `${DEV_ISOLATION_ENV.target} must match ${TARGET_PATTERN.source}`,+ }+ }++ const rawPr = String(env[DEV_ISOLATION_ENV.pr] ?? '').trim()+ if (rawPr && !PR_PATTERN.test(rawPr)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_PR_INVALID',+ message: `${DEV_ISOLATION_ENV.pr} must be digits only`,+ }+ }++ const rawRestUrl = String(env[DEV_ISOLATION_ENV.restUrl] ?? '').trim()+ if (!isLoopbackEndpointUrl(rawRestUrl)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_REST_URL_INVALID',+ message: `${DEV_ISOLATION_ENV.restUrl} must be an http(s) loopback URL with an explicit port and no credentials`,+ }+ }+ const rawRpcUrl = String(env[DEV_ISOLATION_ENV.rpcUrl] ?? '').trim()+ if (!isLoopbackEndpointUrl(rawRpcUrl)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_RPC_URL_INVALID',+ message: `${DEV_ISOLATION_ENV.rpcUrl} must be an http(s) loopback URL with an explicit port and no credentials`,+ }+ }++ const rawAppPath = String(env[DEV_ISOLATION_ENV.appPath] ?? '').trim()+ if (rawAppPath && !path.isAbsolute(rawAppPath)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_APP_PATH_NOT_ABSOLUTE',+ message: `${DEV_ISOLATION_ENV.appPath} must be an absolute path when set`,+ }+ }++ const identity = deriveDevIsolationIdentity({ target: rawTarget, pr: rawPr || null })+ if (!LABEL_PATTERN.test(identity.label)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_LABEL_INVALID',+ message: 'derived isolation label must be 1-80 printable characters',+ }+ }+ if (!APP_NAME_PATTERN.test(identity.appName)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_APP_NAME_INVALID',+ message: 'derived isolation app name must be 1-64 printable ASCII characters',+ }+ }+ if (identity.appName === DEV_ISOLATION_APP_NAME_PREFIX) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_APP_NAME_NOT_UNIQUE',+ message: `an isolated app name must extend ${DEV_ISOLATION_APP_NAME_PREFIX}, not collide with it`,+ }+ }++ const paths = devIsolationPaths(rawRunDir)+ return {+ ok: true,+ plan: {+ ...paths,+ restUrl: rawRestUrl,+ rpcUrl: rawRpcUrl,+ appPath: rawAppPath || null,+ identity,+ label: identity.label,+ appName: identity.appName,+ },+ }+}++export type DevIsolationDecision =+ | { mode: 'normal' }+ | { mode: 'isolated'; plan: DevIsolationPlan }+ | ({ mode: 'refused' } & DevIsolationRefusal)++/**+ * Total decision for the main process: normal, isolated, or refused. Refused is+ * a distinct outcome on purpose — an isolation request that cannot be honoured+ * must never continue as a shared-profile launch.+ */+export function resolveDevIsolation(+ env: NodeJS.ProcessEnv,+ argv: readonly string[],+ isPackaged = false+): DevIsolationDecision {+ const enablement = readDevIsolationEnablement(env, argv)+ if (enablement === 'disabled') return { mode: 'normal' }+ if (enablement === 'invalid') {+ return {+ mode: 'refused',+ code: 'DEV_ISOLATION_ENABLE_INVALID',+ message: `${DEV_ISOLATION_ENABLE_ENV} must be 1/true/0/false or unset, or ${DEV_ISOLATION_FLAG} must be passed`,+ }+ }+ if (isPackaged) {+ return {+ mode: 'refused',+ code: 'DEV_ISOLATION_PACKAGED',+ message: 'Isolation is development-only',+ }+ }+ const plan = buildDevIsolationPlan(env)+ if (!plan.ok) return { mode: 'refused', code: plan.code, message: plan.message }+ const inline = argv.find(argument => argument.startsWith('--user-data-dir='))+ const index = argv.indexOf('--user-data-dir')+ const userData = inline?.slice('--user-data-dir='.length) ?? (index >= 0 ? argv[index + 1] : '')+ if (+ !userData ||+ !path.isAbsolute(userData) ||+ path.resolve(userData) !== plan.plan.userDataDir ||+ env.CLERUM_DESKTOP_CONFIG_PATH !== plan.plan.configPath ||+ env.EXTERNAL_REST_API_BASE_URL !== plan.plan.restUrl ||+ env.RPC_PROXY_BASE_URL !== plan.plan.rpcUrl+ ) {+ return {+ mode: 'refused',+ code: 'DEV_ISOLATION_LAUNCH_MISMATCH',+ message:+ 'Explicit user data, config path and effective endpoints must match the isolation plan',+ }+ }+ return { mode: 'isolated', plan: plan.plan }+}++export type DevIsolationRuntimePolicy = {+ isolate: boolean+ /** Isolated runs leave the machine-wide protocol handler untouched. */+ registerOsProtocols: boolean+ /** Isolated runs never route deep links, including another session's. */+ acceptDeepLinks: boolean+ /** Isolated runs keep their label as the window title. */+ pinWindowTitle: boolean+ /** Unique process/application name, or null to keep the shipped name. */+ appName: string | null+ /** Visible window title, or null to keep the derived production title. */+ windowTitle: string | null+}++/**+ * The single place that decides what an isolated run may do with machine-wide+ * state. With no plan every field is the production value, so the normal path+ * stays unchanged.+ */+export function devIsolationRuntimePolicy(+ plan: DevIsolationPlan | null+): DevIsolationRuntimePolicy {+ if (!plan) {+ return {+ isolate: false,+ registerOsProtocols: true,+ acceptDeepLinks: true,+ pinWindowTitle: false,+ appName: null,+ windowTitle: null,+ }+ }+ return {+ isolate: true,+ registerOsProtocols: false,+ acceptDeepLinks: false,+ pinWindowTitle: true,+ appName: plan.appName,+ windowTitle: plan.label,+ }+}++export type DevIsolationObservation = {+ pid: number+ /** Real (`realpath`) userData directory Electron resolved. */+ userDataDir: string+ /** Real app path the process is running from. */+ appPath: string+ /** Effective endpoints after config hydration. */+ restUrl: string+ rpcUrl: string+ /** Effective runtime-config storage path after hydration. */+ configStoragePath: string+ /** Derived environment key of the hydrated runtime. */+ envKey: string+}++export type DevIsolationMismatch = {+ field: 'userDataDir' | 'appPath' | 'restUrl' | 'rpcUrl' | 'configStoragePath'+ expected: string+ actual: string+}++export type DevIsolationVerdict = { ok: true } | { ok: false; mismatches: DevIsolationMismatch[] }++function samePath(left: string, right: string): boolean {+ return path.resolve(left) === path.resolve(right)+}++/**+ * Compare what the app actually resolved against what the launcher declared.+ *+ * The config storage path is compared exactly, not by containment: it is the+ * proof that the runtime-config layer pointed at the isolated file instead of+ * the developer's shared `runtime-configs` directory. Callers pass `realpath`+ * results for the paths, so a symlinked parent cannot fake a match.+ */+export function verifyDevIsolationRuntime(+ plan: DevIsolationPlan,+ observed: DevIsolationObservation+): DevIsolationVerdict {+ const mismatches: DevIsolationMismatch[] = []+ if (!samePath(plan.userDataDir, observed.userDataDir)) {+ mismatches.push({+ field: 'userDataDir',+ expected: plan.userDataDir,+ actual: observed.userDataDir,+ })+ }+ if (plan.appPath && !samePath(plan.appPath, observed.appPath)) {+ mismatches.push({ field: 'appPath', expected: plan.appPath, actual: observed.appPath })+ }+ if (plan.restUrl !== observed.restUrl) {+ mismatches.push({ field: 'restUrl', expected: plan.restUrl, actual: observed.restUrl })+ }+ if (plan.rpcUrl !== observed.rpcUrl) {+ mismatches.push({ field: 'rpcUrl', expected: plan.rpcUrl, actual: observed.rpcUrl })+ }+ if (!samePath(plan.configPath, observed.configStoragePath)) {+ mismatches.push({+ field: 'configStoragePath',+ expected: plan.configPath,+ actual: observed.configStoragePath,+ })+ }+ return mismatches.length === 0 ? { ok: true } : { ok: false, mismatches }+}++/** Keys a public run record may contain. Nothing else is ever serialized. */+export const DEV_ISOLATION_RECORD_FIELDS = [+ 'kind',+ 'pid',+ 'label',+ 'appName',+ 'target',+ 'envKey',+ 'runDir',+ 'userDataDir',+ 'configPath',+ 'configStoragePath',+ 'appPath',+ 'restUrl',+ 'rpcUrl',+] as const++/**+ * Public metadata for one isolated run: the identity, the pid and the paths and+ * endpoints the operator asked to see. Built from an allow-list so a caller+ * cannot leak an environment dump, a token or a credential into the record, and+ * so the record is byte-identical between the launcher and the app.+ */+export function publicDevIsolationRecord(+ plan: DevIsolationPlan,+ observed: DevIsolationObservation+): Record<string, string | number> {+ if (!verifyDevIsolationRuntime(plan, observed).ok) {+ throw new Error('Isolation metadata is unavailable before runtime verification')+ }+ return {+ kind: 'evenfire-dev-isolation',+ pid: observed.pid,+ label: plan.label,+ appName: plan.appName,+ target: plan.identity.target,+ envKey: observed.envKey,+ runDir: plan.runDir,+ userDataDir: observed.userDataDir,+ configPath: plan.configPath,+ configStoragePath: observed.configStoragePath,+ appPath: observed.appPath,+ restUrl: observed.restUrl,+ rpcUrl: observed.rpcUrl,+ }+}++function singleLineValue(value: string | number | undefined): string {+ const raw = typeof value === 'number' ? String(value) : String(value ?? '')+ return raw+ .replace(/[\u0000-\u001f\u007f]/g, '?')+ .replace(/\s+/g, ' ')+ .trim()+}++/** One log line, deterministic order, never multi-line. */+export function formatDevIsolationLogLine(record: Record<string, string | number>): string {+ const fields = Object.keys(record)+ .sort()+ .map(key => `${key}=${singleLineValue(record[key])}`)+ return `[Desktop][dev-isolation] ${fields.join(' ')}`+}++export type IsolationBaseDirDecision =+ | { ok: true; baseDir: string }+ | ({ ok: false } & DevIsolationRefusal)++/** Platform default parent directory for per-run directories. */+export function defaultIsolationBaseDir(input: {+ platform: NodeJS.Platform+ homedir: string+ env: NodeJS.ProcessEnv+}): string {+ if (input.platform === 'darwin') {+ return path.join(+ input.homedir,+ 'Library',+ 'Application Support',+ `${DEV_ISOLATION_APP_NAME_PREFIX} Dev Isolation`+ )+ }+ if (input.platform === 'win32') {+ const localAppData = String(input.env.LOCALAPPDATA ?? '').trim()+ return path.join(+ localAppData || path.join(input.homedir, 'AppData', 'Local'),+ `${DEV_ISOLATION_APP_NAME_PREFIX} Dev Isolation`+ )+ }+ const stateHome = String(input.env.XDG_STATE_HOME ?? '').trim()+ return path.join(+ stateHome || path.join(input.homedir, '.local', 'state'),+ 'evenfire-dev-isolation'+ )+}++/**+ * Admit the parent directory of the per-run directories. A requested directory+ * must be absolute and outside the repository: run state holds credentials-side+ * material (the Chromium profile), and it must never land in the worktree where+ * it could be committed or copied into notes.+ */+export function admitIsolationBaseDir(input: {+ requested?: string+ repoRoot: string+ platform: NodeJS.Platform+ homedir: string+ env: NodeJS.ProcessEnv+}): IsolationBaseDirDecision {+ const requested = String(input.requested ?? '').trim()+ if (requested && !path.isAbsolute(requested)) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_BASE_DIR_NOT_ABSOLUTE',+ message: 'the isolation base directory must be an absolute path',+ }+ }+ const baseDir = requested+ ? path.resolve(requested)+ : defaultIsolationBaseDir({+ platform: input.platform,+ homedir: input.homedir,+ env: input.env,+ })+ if (isPathInside(input.repoRoot, baseDir) || path.resolve(input.repoRoot) === baseDir) {+ return {+ ok: false,+ code: 'DEV_ISOLATION_BASE_DIR_INSIDE_REPO',+ message: 'the isolation base directory must be outside the repository',+ }+ }+ return { ok: true, baseDir }+}diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.tsindex fc6034a08..354c31680 100644--- a/desktop-app/src/main.ts+++ b/desktop-app/src/main.ts@@ -1,9 +1,23 @@import { BrowserWindow, app, ipcMain, nativeTheme, powerMonitor } from 'electron'+import fs from 'node:fs'import path from 'node:path'import { AppService } from './appService.js'import { routeClerumOauthCompleted } from './clerumDeepLink.js'-import { config } from './config.js'+import {+ config,+ getActiveEnvKey,+ getDesktopRuntimeConfigState,+ hydrateDesktopRuntimeConfig,+} from './config.js'import { installDesktopTextContextMenus } from './desktopTextContextMenu.js'+import {+ type DevIsolationPlan,+ devIsolationRuntimePolicy,+ formatDevIsolationLogLine,+ publicDevIsolationRecord,+ resolveDevIsolation,+ verifyDevIsolationRuntime,+} from './devIsolation.js'import { createEvenfireDeepLinkRouter } from './evenfireDeepLinkRouter.js'import { assertTrustedSender, registerIpcHandlers } from './ipc.js'import { createMainWindowCoordinator, createRetryableInitializer } from './mainWindowCoordinator.js'@@ -25,8 +39,23 @@ import { installAdaptiveSystemIcon, resolveSystemIconPath } from './systemIcon.jconst EVENFIRE_APP_NAME = 'Evenfire'const EVENFIRE_APP_ID = 'ai.evenfire.desktop'-process.title = EVENFIRE_APP_NAME-app.setName(EVENFIRE_APP_NAME)+/**+ * Dev isolation is opt-in and fail-closed. A launch that asked for an isolated+ * instance must never continue into the shared user profile or the machine-wide+ * OS protocol handler, so an unhonourable request aborts here — before+ * `registerCustomProtocols()` can touch the default handler.+ */+const devIsolation = resolveDevIsolation(process.env, process.argv, app.isPackaged)+if (devIsolation.mode === 'refused') {+ console.error(`[Desktop] Dev isolation refused: ${devIsolation.code}: ${devIsolation.message}`)+ process.exit(1)+}+const devIsolationPlan: DevIsolationPlan | null =+ devIsolation.mode === 'isolated' ? devIsolation.plan : null+const devIsolationPolicy = devIsolationRuntimePolicy(devIsolationPlan)++process.title = devIsolationPolicy.appName ?? EVENFIRE_APP_NAME+app.setName(devIsolationPolicy.appName ?? EVENFIRE_APP_NAME)app.setAppUserModelId(EVENFIRE_APP_ID)// Prevent crash on EPIPE when stdout/stderr pipe is broken (e.g., parent terminal closed)@@ -327,13 +356,20 @@ function handleClerumUrl(rawUrl: string): void {focusMainWindow()}-registerCustomProtocols()+// An isolated run leaves the machine-wide default handler exactly as it is: the+// normal app keeps owning `evenfire:`/`clerum:` deep links.+if (devIsolationPolicy.registerOsProtocols) {+ registerCustomProtocols()+}const gotSingleInstanceLock = app.requestSingleInstanceLock()if (!gotSingleInstanceLock) {app.quit()} else {app.on('second-instance', (_event, argv) => {+ // An isolated instance never routes deep links: a URL delivered here belongs+ // to the session that owns the OS handler, not to this one.+ if (!devIsolationPolicy.acceptDeepLinks) returnconst protocolUrls = collectInitialProtocolUrls(argv)protocolUrls.evenfireUrls.forEach(evenfireDeepLinkRouter.handle)protocolUrls.clerumUrls.forEach(handleClerumUrl)@@ -341,15 +377,64 @@ if (!gotSingleInstanceLock) {})}-app.on('open-url', (event, rawUrl) => {- event.preventDefault()- const lowerUrl = rawUrl.toLowerCase()- if (lowerUrl.startsWith(`${DESKTOP_SETUP_PROTOCOL}:`)) {- evenfireDeepLinkRouter.handle(rawUrl)- } else if (lowerUrl.startsWith(`${CLERUM_PROTOCOL}:`)) {- handleClerumUrl(rawUrl)+if (devIsolationPolicy.acceptDeepLinks) {+ app.on('open-url', (event, rawUrl) => {+ event.preventDefault()+ const lowerUrl = rawUrl.toLowerCase()+ if (lowerUrl.startsWith(`${DESKTOP_SETUP_PROTOCOL}:`)) {+ evenfireDeepLinkRouter.handle(rawUrl)+ } else if (lowerUrl.startsWith(`${CLERUM_PROTOCOL}:`)) {+ handleClerumUrl(rawUrl)+ }+ })+}++/**+ * Verify the effective runtime against the launcher's declaration and log the+ * public metadata for this run. Returns false when the process must abort:+ * continuing would use a profile the operator did not ask for.+ *+ * Paths are compared after `realpath`, so a symlinked parent cannot fake a+ * match, and the config storage path is compared exactly — it is the proof that+ * the runtime-config layer pointed at the isolated file rather than the shared+ * `runtime-configs` directory.+ */+function verifyDevIsolationBeforeServices(plan: DevIsolationPlan): boolean {+ hydrateDesktopRuntimeConfig()+ const runtimeState = getDesktopRuntimeConfigState()+ const realPath = (value: string): string => {+ try {+ return fs.realpathSync.native(value)+ } catch {+ return path.resolve(value)+ }}-})+ const observed = {+ pid: process.pid,+ userDataDir: realPath(app.getPath('userData')),+ appPath: realPath(app.getAppPath()),+ restUrl: config.externalRestApiBaseUrl,+ rpcUrl: config.rpcProxyBaseUrl,+ configStoragePath: runtimeState.storagePath,+ envKey: getActiveEnvKey(),+ }+ const expected: DevIsolationPlan = {+ ...plan,+ userDataDir: realPath(plan.userDataDir),+ appPath: plan.appPath ? realPath(plan.appPath) : null,+ }+ const verdict = verifyDevIsolationRuntime(expected, observed)+ if (verdict.ok) {+ console.log(formatDevIsolationLogLine(publicDevIsolationRecord(expected, observed)))+ return true+ }+ const detail = verdict.mismatches.map(mismatch => mismatch.field).join(', ')+ console.error(+ `[Desktop] Dev isolation refused: the effective runtime diverges from the launcher: ${detail}`+ )+ app.exit(1)+ return false+}async function createWindow(): Promise<void> {try {@@ -368,9 +453,10 @@ async function createWindow(): Promise<void> {show: false,frame: false,title:- config.appName === EVENFIRE_APP_NAME+ devIsolationPolicy.windowTitle ??+ (config.appName === EVENFIRE_APP_NAME? EVENFIRE_APP_NAME- : `${EVENFIRE_APP_NAME} — ${config.appName}`,+ : `${EVENFIRE_APP_NAME} — ${config.appName}`),icon: resolveSystemIconPath(systemIconAssetsDirectory(), nativeTheme.shouldUseDarkColors),webPreferences: {preload: path.join(__dirname, 'preload.js'),@@ -380,6 +466,14 @@ async function createWindow(): Promise<void> {},})mainWindow = window+ if (devIsolationPolicy.pinWindowTitle) {+ // Keep the isolated identity in the window title after the renderer updates+ // document.title: window/app automation resolves this instance by it.+ window.webContents.on('page-title-updated', event => {+ event.preventDefault()+ window.setTitle(devIsolationPolicy.windowTitle ?? window.getTitle())+ })+ }wireHostDesktopShortcutRouting(window)mainWindowRendererReady = falsewindow.on('closed', () => {@@ -439,6 +533,10 @@ if (gotSingleInstanceLock) {app.whenReady().then(async () => {+ // Before any service initializes: an isolated run that cannot prove its+ // own userData, app path, endpoints and config storage is the declared+ // isolated ones aborts instead of reading a shared profile.+ if (devIsolationPlan && !verifyDevIsolationBeforeServices(devIsolationPlan)) returninstallDesktopTextContextMenus()wireAdaptiveSystemIcon()// Must precede registerIpcHandlers: the SDK IPC handlers resolve the@@ -456,10 +554,14 @@ if (gotSingleInstanceLock) {// Collect startup argv once. The renderer-ready handshake drains queued// Evenfire URLs after its listeners are installed; rescanning argv would// dispatch setup links twice on Windows/Linux.- const initialProtocolUrls = collectInitialProtocolUrls(process.argv)+ // An isolated run collects nothing: its argv cannot contain a deep link+ // that belongs to this session.+ const initialProtocolUrls = devIsolationPolicy.acceptDeepLinks+ ? collectInitialProtocolUrls(process.argv)+ : { evenfireUrls: [], clerumUrls: [] }initialProtocolUrls.evenfireUrls.forEach(evenfireDeepLinkRouter.enqueuePending)await mainWindowCoordinator.ensureWindow()- if (process.platform !== 'darwin') {+ if (devIsolationPolicy.acceptDeepLinks && process.platform !== 'darwin') {initialProtocolUrls.clerumUrls.forEach(handleClerumUrl)}})diff --git a/desktop-app/ui/src/components/agents/AnnotationCanvas.tsx b/desktop-app/ui/src/components/agents/AnnotationCanvas.tsxindex 4ba3edcce..1a5174d5a 100644--- a/desktop-app/ui/src/components/agents/AnnotationCanvas.tsx+++ b/desktop-app/ui/src/components/agents/AnnotationCanvas.tsx@@ -155,13 +155,19 @@ export function AnnotationCanvas({ attachment, onSave, onClose }: AnnotationCanvtypeof URL !== 'undefined' && typeof URL.createObjectURL === 'function'? URL.createObjectURL(blob): dataUrl- onSave({- ...attachment,- mimeType: nextMimeType,- dataBase64: dataUrl.slice(base64Index + 'base64,'.length),- sizeBytes: blob.size,- previewDataUrl: nextPreviewUrl,- })+ try {+ onSave({+ ...attachment,+ mimeType: nextMimeType,+ dataBase64: dataUrl.slice(base64Index + 'base64,'.length),+ sizeBytes: blob.size,+ previewDataUrl: nextPreviewUrl,+ })+ } catch (error) {+ // The rejected replacement never becomes the attachment's preview.+ if (nextPreviewUrl !== dataUrl) URL.revokeObjectURL(nextPreviewUrl)+ throw error+ }setPreviewIsAnnotating(false)} catch (error) {setAnnotationError(error instanceof Error ? error.message : String(error))diff --git a/desktop-app/ui/src/components/agents/ComposerPanel.tsx b/desktop-app/ui/src/components/agents/ComposerPanel.tsxindex 265800452..8ecc065e8 100644--- a/desktop-app/ui/src/components/agents/ComposerPanel.tsx+++ b/desktop-app/ui/src/components/agents/ComposerPanel.tsx@@ -22,6 +22,7 @@ import {COMPOSER_ACCEPT_IMAGE_MIME_TYPES,COMPOSER_MAX_IMAGE_ATTACHMENTS,COMPOSER_MAX_IMAGE_BYTES,+ COMPOSER_MAX_TOTAL_IMAGE_BYTES,ZAI_IMAGE_ATTACHMENT_UNSUPPORTED_MESSAGE,} from '@constants/attachments'import { useContextsDataController } from '@hooks/domain/useContextsDataController'@@ -55,6 +56,26 @@ function getComposerImageTooltip(attachment: ComposerImageAttachment): string {return `Uploaded File - ${Math.max(1, Math.round(attachment.sizeBytes / 1024))} KB`}+function formatComposerMebibytes(bytes: number): number {+ return Math.round(bytes / (1024 * 1024))+}++type ComposerImageBudgetRejection = 'image-too-large' | 'total-too-large' | null++/**+ * Budget decision for one image of `sizeBytes` placed next to `otherImagesBytes`+ * already attached. Shared by the picker/paste/drop path and the annotation-save+ * path so neither route can exceed the per-image limit or the per-message total.+ */+function composerImageBudgetRejection(+ sizeBytes: number,+ otherImagesBytes: number+): ComposerImageBudgetRejection {+ if (sizeBytes > COMPOSER_MAX_IMAGE_BYTES) return 'image-too-large'+ if (otherImagesBytes + sizeBytes > COMPOSER_MAX_TOTAL_IMAGE_BYTES) return 'total-too-large'+ return null+}+function getComposerReferenceIcon(attachment: ComposerReferenceAttachment) {if (attachment.type === 'plugin') return <IconWorkflows />if (attachment.type === 'connector') return <IconConnectors />@@ -436,6 +457,18 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPrconst accepted: ComposerImageAttachment[] = []const validationErrors: string[] = []const selected = candidates.slice(0, availableSlots)+ if (candidates.length > selected.length) {+ validationErrors.push(+ `You can attach up to ${COMPOSER_MAX_IMAGE_ATTACHMENTS} images per message.`+ )+ }+ // The budget runs across the images already attached plus the ones accepted+ // below, so a selection cannot exceed the per-message total even when every+ // file is individually allowed.+ let plannedBytes = composerImageAttachments.reduce(+ (total, attachment) => total + attachment.sizeBytes,+ 0+ )for (const [index, file] of selected.entries()) {const mimeType = inferComposerImageMimeType(file)@@ -443,11 +476,16 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPrvalidationErrors.push(`${file.name || 'Image'} is not supported. Use PNG or JPEG.`)continue}- if (file.size > COMPOSER_MAX_IMAGE_BYTES) {+ const rejection = composerImageBudgetRejection(file.size, plannedBytes)+ if (rejection) {validationErrors.push(- `${file.name || 'Image'} is too large. Max size is ${Math.round(- COMPOSER_MAX_IMAGE_BYTES / (1024 * 1024)- )} MB.`+ rejection === 'image-too-large'+ ? `${file.name || 'Image'} is too large. Max size is ${formatComposerMebibytes(+ COMPOSER_MAX_IMAGE_BYTES+ )} MiB.`+ : `${file.name || 'Image'} was not added. Attachments can total at most ${formatComposerMebibytes(+ COMPOSER_MAX_TOTAL_IMAGE_BYTES+ )} MiB per message.`)continue}@@ -475,6 +513,7 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPrsizeBytes: file.size,previewDataUrl: previewUrl || dataUrl,})+ plannedBytes += file.size} catch (error) {revokePreviewUrl(previewUrl)validationErrors.push(@@ -491,7 +530,7 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr[activeProviderDoesNotSupportImages,buildAttachmentName,- composerImageAttachments.length,+ composerImageAttachments,inferComposerImageMimeType,onAddComposerImageAttachments,readFileAsDataUrl,@@ -500,6 +539,44 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr])+ /**+ * An annotation save re-encodes the image, so the result can be larger than the+ * file the picker accepted. Apply the same budget before the attachment is+ * replaced; a refusal never calls through, so the original attachment, its+ * preview URL and its bytes stay exactly as they were.+ *+ * The refusal is thrown rather than returned: AnnotationCanvas runs `onSave`+ * inside its own try/catch and renders the thrown message in+ * `.composer-image-preview-error` within its dialog. That is the only error+ * surface above the full-screen annotation overlay — the composer's own banner+ * sits behind that overlay's 86%-opaque backdrop — and throwing also skips the+ * canvas's `setPreviewIsAnnotating(false)`, so the user keeps their strokes.+ */+ const handleAnnotatedImageSave = useCallback(+ (updated: ComposerImageAttachment) => {+ const otherImagesBytes = composerImageAttachments.reduce(+ (total, attachment) =>+ attachment.id === updated.id ? total : total + attachment.sizeBytes,+ 0+ )+ const rejection = composerImageBudgetRejection(updated.sizeBytes, otherImagesBytes)+ if (!rejection) {+ onUpdateComposerImageAttachment(updated)+ return+ }+ throw new Error(+ rejection === 'image-too-large'+ ? `${updated.name || 'Image'} was kept unchanged. Max size is ${formatComposerMebibytes(+ COMPOSER_MAX_IMAGE_BYTES+ )} MiB per image.`+ : `${updated.name || 'Image'} was kept unchanged. Attachments can total at most ${formatComposerMebibytes(+ COMPOSER_MAX_TOTAL_IMAGE_BYTES+ )} MiB per message.`+ )+ },+ [composerImageAttachments, onUpdateComposerImageAttachment]+ )+const handleComposerPaste = useCallback((event: React.ClipboardEvent<HTMLTextAreaElement>) => {const filesFromClipboard = Array.from(event.clipboardData.files || [])@@ -949,7 +1026,7 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr{previewAttachment && (<AnnotationCanvasattachment={previewAttachment}- onSave={onUpdateComposerImageAttachment}+ onSave={handleAnnotatedImageSave}onClose={() => setPreviewAttachmentId(null)}/>)}diff --git a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsxindex 15baecd24..88bb542d3 100644--- a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx@@ -1,8 +1,9 @@// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { readFileSync } from 'node:fs'import { resolve } from 'node:path'+import type { ComposerImageAttachment } from '../../../uiTypes'import { ComposerPanel } from '../ComposerPanel'// Resolve the stylesheet relative to THIS test file (not process.cwd()) so the@@ -12,7 +13,7 @@ import { ComposerPanel } from '../ComposerPanel'const composerStyles = readFileSync(resolve(__dirname, '../../../styles.css'), 'utf8')const composerState = {- composerImageAttachments: [],+ composerImageAttachments: [] as ComposerImageAttachment[],composerReferenceAttachments: [],agentSending: false,agentError: null,@@ -24,16 +25,22 @@ const composerState = {const draftState = { value: '', set: vi.fn() }+// Stable spies so the image-budget cases can assert exactly what the panel hands+// to the composer-actions layer.+const composerActions = {+ handleAddComposerImageAttachments: vi.fn(),+ handleUpdateComposerImageAttachment: vi.fn(),+ handleRemoveComposerImageAttachment: vi.fn(),+ handleAddComposerReferenceAttachments: vi.fn(),+ handleRemoveComposerReferenceAttachment: vi.fn(),+ handleSendAgentMessage: vi.fn(),+ handleRetryFailedAgentSend: vi.fn(),+}+vi.mock('@contexts/AgentChatActionsContext', () => ({useAgentChatActionsContext: () => ({clearComposerSendError: vi.fn(),- handleAddComposerImageAttachments: vi.fn(),- handleUpdateComposerImageAttachment: vi.fn(),- handleRemoveComposerImageAttachment: vi.fn(),- handleAddComposerReferenceAttachments: vi.fn(),- handleRemoveComposerReferenceAttachment: vi.fn(),- handleSendAgentMessage: vi.fn(),- handleRetryFailedAgentSend: vi.fn(),+ ...composerActions,}),}))@@ -83,7 +90,43 @@ vi.mock('@hooks/useHostModels', () => ({}))vi.mock('../ComposerAgentFilesModal', () => ({ ComposerAgentFilesModal: () => null }))vi.mock('../ComposerGlobalFilesModal', () => ({ ComposerGlobalFilesModal: () => null }))-vi.mock('../AnnotationCanvas', () => ({ AnnotationCanvas: () => null }))+// The annotation-budget cases drive the panel's own save handler. The canvas is+// a heavyweight sibling that needs a real 2D context, so it stays a test double+// (as it always was here) that simply exposes the `onSave` the panel supplies.+const annotationStub = vi.hoisted(() => ({+ next: null as null | {+ id: string+ addedOrder?: number+ name: string+ mimeType: 'image/png' | 'image/jpeg'+ dataBase64: string+ sizeBytes: number+ previewDataUrl: string+ },+ /** Message AnnotationCanvas would render from a thrown `onSave`. */+ threw: null as string | null,+}))++vi.mock('../AnnotationCanvas', () => ({+ AnnotationCanvas: ({ onSave }: { onSave: (updated: ComposerImageAttachment) => void }) => (+ <button+ type="button"+ onClick={() => {+ if (!annotationStub.next) return+ // AnnotationCanvas awaits `onSave` inside its own try/catch and renders a+ // thrown message in `.composer-image-preview-error` inside its dialog.+ annotationStub.threw = null+ try {+ onSave(annotationStub.next)+ } catch (error) {+ annotationStub.threw = error instanceof Error ? error.message : String(error)+ }+ }}+ >+ Apply annotation+ </button>+ ),+}))function setScrollHeight(textarea: HTMLTextAreaElement, value: number) {Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value })@@ -101,6 +144,10 @@ afterEach(() => {draftState.value = ''draftState.set.mockReset()composerState.composerFocusRequestId = 0+ composerState.composerImageAttachments = []+ annotationStub.next = null+ annotationStub.threw = null+ for (const spy of Object.values(composerActions)) spy.mockReset()delete (window as Partial<typeof window>).clerum})@@ -193,3 +240,207 @@ describe.each([otherInput.remove()})})++const MIB = 1024 * 1024++/**+ * A picked image whose reported size is `sizeBytes`. The guard decides on+ * `File.size` — what the browser reports for the chosen file — so binding the+ * size drives the real code path without allocating and base64-encoding 10MiB+ * blobs per case.+ */+function imageFile(name: string, sizeBytes: number): File {+ const file = new File([new Uint8Array([0x41])], name, { type: 'image/png' })+ Object.defineProperty(file, 'size', { configurable: true, value: sizeBytes })+ return file+}++function existingAttachment(name: string, sizeBytes: number): ComposerImageAttachment {+ return {+ id: `existing-${name}`,+ name,+ mimeType: 'image/png',+ dataBase64: 'QQ==',+ sizeBytes,+ previewDataUrl: '',+ addedOrder: 0,+ }+}++function pickFiles(container: HTMLElement, files: File[]) {+ const input = container.querySelector('input[type="file"]') as HTMLInputElement+ Object.defineProperty(input, 'files', { configurable: true, value: files })+ fireEvent.change(input)+}++/** Every image the panel handed to the composer-actions layer, in order. */+function attachedImages(): ComposerImageAttachment[] {+ return composerActions.handleAddComposerImageAttachments.mock.calls.flatMap(+ call => call[0] as ComposerImageAttachment[]+ )+}++describe('ComposerPanel image budget', () => {+ it('accepts an image at the 10MiB per-image limit', async () => {+ const { container } = render(<ComposerPanel inline={false} />)+ pickFiles(container, [imageFile('at-limit.png', 10 * MIB)])+ await waitFor(() => expect(attachedImages()).toHaveLength(1))+ expect(attachedImages()[0]?.sizeBytes).toBe(10 * MIB)+ expect(screen.queryByRole('alert')).toBeNull()+ })++ it('accepts 10MiB + 5MiB, the 15MiB per-message total', async () => {+ const { container } = render(<ComposerPanel inline={false} />)+ pickFiles(container, [imageFile('ten.png', 10 * MIB), imageFile('five.png', 5 * MIB)])+ await waitFor(() => expect(attachedImages()).toHaveLength(2))+ expect(screen.queryByRole('alert')).toBeNull()+ })++ it('accepts three 5MiB images', async () => {+ const { container } = render(<ComposerPanel inline={false} />)+ pickFiles(container, [+ imageFile('a.png', 5 * MIB),+ imageFile('b.png', 5 * MIB),+ imageFile('c.png', 5 * MIB),+ ])+ await waitFor(() => expect(attachedImages()).toHaveLength(3))+ expect(screen.queryByRole('alert')).toBeNull()+ })++ it('refuses an image over the 10MiB limit and names the limit in MiB', async () => {+ const { container } = render(<ComposerPanel inline={false} />)+ pickFiles(container, [imageFile('over.png', 11 * MIB)])+ await waitFor(() =>+ expect(screen.getByRole('alert').textContent).toContain(+ 'over.png is too large. Max size is 10 MiB.'+ )+ )+ expect(composerActions.handleAddComposerImageAttachments).not.toHaveBeenCalled()+ })++ it('refuses the over-total file in a selection and keeps the one that fits', async () => {+ const { container } = render(<ComposerPanel inline={false} />)+ pickFiles(container, [imageFile('fits.png', 10 * MIB), imageFile('over-total.png', 6 * MIB)])+ await waitFor(() =>+ expect(screen.getByRole('alert').textContent).toContain(+ 'over-total.png was not added. Attachments can total at most 15 MiB per message.'+ )+ )+ expect(attachedImages().map(attachment => attachment.name)).toEqual(['fits.png'])+ })++ it('refuses an added image that would pass the total with 10MiB already attached', async () => {+ composerState.composerImageAttachments = [existingAttachment('kept.png', 10 * MIB)]+ const { container } = render(<ComposerPanel inline={false} />)+ pickFiles(container, [imageFile('over-total.png', 6 * MIB)])+ await waitFor(() =>+ expect(screen.getByRole('alert').textContent).toContain(+ 'can total at most 15 MiB per message'+ )+ )+ expect(composerActions.handleAddComposerImageAttachments).not.toHaveBeenCalled()+ })++ it('accepts a 5MiB image when 10MiB is already attached', async () => {+ composerState.composerImageAttachments = [existingAttachment('kept.png', 10 * MIB)]+ const { container } = render(<ComposerPanel inline={false} />)+ pickFiles(container, [imageFile('five.png', 5 * MIB)])+ await waitFor(() => expect(attachedImages()).toHaveLength(1))+ expect(screen.queryByRole('alert')).toBeNull()+ })++ it('explains files beyond the 3-image cap instead of dropping them silently', async () => {+ composerState.composerImageAttachments = [+ existingAttachment('a.png', MIB),+ existingAttachment('b.png', MIB),+ ]+ const { container } = render(<ComposerPanel inline={false} />)+ pickFiles(container, [imageFile('c.png', MIB), imageFile('d.png', MIB)])+ await waitFor(() => expect(attachedImages()).toHaveLength(1))+ expect(screen.getByRole('alert').textContent).toContain(+ 'You can attach up to 3 images per message.'+ )+ })+})++/** Open the annotation canvas for the attached image named `name`. */+function openAnnotation(container: HTMLElement, name: string) {+ const triggers = Array.from(container.querySelectorAll('.composer-attachment-preview-trigger'))+ const trigger = triggers.find(node => node.textContent?.includes(name))+ if (!trigger) throw new Error(`annotation trigger for ${name} not found`)+ fireEvent.click(trigger)+}++function applyAnnotation() {+ fireEvent.click(screen.getByRole('button', { name: 'Apply annotation' }))+}++describe('ComposerPanel annotation budget', () => {+ it('applies an annotation that stays inside both limits', () => {+ const original = existingAttachment('photo.png', 8 * MIB)+ composerState.composerImageAttachments = [original]+ const { container } = render(<ComposerPanel inline={false} />)+ openAnnotation(container, 'photo.png')++ annotationStub.next = { ...original, sizeBytes: 9 * MIB }+ applyAnnotation()++ expect(annotationStub.threw).toBeNull()+ expect(composerActions.handleUpdateComposerImageAttachment).toHaveBeenCalledTimes(1)+ expect(composerActions.handleUpdateComposerImageAttachment.mock.calls[0]?.[0]).toMatchObject({+ id: original.id,+ sizeBytes: 9 * MIB,+ })+ })++ it('refuses an annotation over the 10MiB per-image limit and keeps the original', () => {+ const original = existingAttachment('photo.png', 4 * MIB)+ composerState.composerImageAttachments = [original]+ const { container } = render(<ComposerPanel inline={false} />)+ openAnnotation(container, 'photo.png')++ annotationStub.next = { ...original, sizeBytes: 11 * MIB }+ applyAnnotation()++ expect(composerActions.handleUpdateComposerImageAttachment).not.toHaveBeenCalled()+ // The message the annotation dialog renders above its overlay; the original+ // attachment is never replaced.+ expect(annotationStub.threw).toContain(+ 'photo.png was kept unchanged. Max size is 10 MiB per image.'+ )+ })++ it('refuses an annotation that would push the message past the 15MiB total', () => {+ const original = existingAttachment('photo.png', 4 * MIB)+ composerState.composerImageAttachments = [original, existingAttachment('other.png', 10 * MIB)]+ const { container } = render(<ComposerPanel inline={false} />)+ openAnnotation(container, 'photo.png')++ // 10MiB sibling + 7MiB annotation = 17MiB. The annotated image alone is under+ // the per-image limit, so only the per-message total can refuse this.+ annotationStub.next = { ...original, sizeBytes: 7 * MIB }+ applyAnnotation()++ expect(composerActions.handleUpdateComposerImageAttachment).not.toHaveBeenCalled()+ expect(annotationStub.threw).toContain(+ 'photo.png was kept unchanged. Attachments can total at most 15 MiB per message.'+ )+ })++ it('applies an annotation that exactly reaches the 15MiB total', () => {+ const original = existingAttachment('photo.png', 4 * MIB)+ composerState.composerImageAttachments = [original, existingAttachment('other.png', 10 * MIB)]+ const { container } = render(<ComposerPanel inline={false} />)+ openAnnotation(container, 'photo.png')++ annotationStub.next = { ...original, sizeBytes: 5 * MIB }+ applyAnnotation()++ expect(annotationStub.threw).toBeNull()+ expect(composerActions.handleUpdateComposerImageAttachment).toHaveBeenCalledTimes(1)+ expect(composerActions.handleUpdateComposerImageAttachment.mock.calls[0]?.[0]).toMatchObject({+ id: original.id,+ sizeBytes: 5 * MIB,+ })+ })+})diff --git a/desktop-app/ui/src/constants/attachments.ts b/desktop-app/ui/src/constants/attachments.tsindex ef3dc30ba..e8da613dd 100644--- a/desktop-app/ui/src/constants/attachments.ts+++ b/desktop-app/ui/src/constants/attachments.ts@@ -1,5 +1,12 @@export const COMPOSER_MAX_IMAGE_ATTACHMENTS = 3-export const COMPOSER_MAX_IMAGE_BYTES = 3 * 1024 * 1024+/**+ * Composer image budget. These mirror the server-side chat body budget shared by+ * rpc-proxy and mcp-host (10MiB per image, 3 images / 15MiB of image bytes in a+ * 24MiB JSON body), so an image the composer accepts is also one the runtime+ * will carry. Change them together with that budget.+ */+export const COMPOSER_MAX_IMAGE_BYTES = 10 * 1024 * 1024+export const COMPOSER_MAX_TOTAL_IMAGE_BYTES = 15 * 1024 * 1024export const COMPOSER_ACCEPT_IMAGE_MIME_TYPES = ['image/jpeg', 'image/png'] as constexport const ZAI_IMAGE_ATTACHMENT_UNSUPPORTED_MESSAGE ='Image attachments are not supported for agents running on Z AI yet. Switch this agent to a provider with image input support before attaching images.'diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.mdindex 62b15867b..e39755c4e 100644--- a/docs/architecture/codex-subscription-transport-contract.md+++ b/docs/architecture/codex-subscription-transport-contract.md@@ -33,21 +33,34 @@ retain one remaining image per MIME/bytes pair and its explanatory text. They donot restore pixels removed by pruning. The user-facing attachment collectionkeeps its existing deduplication behavior.-Local visual budgets are three images, 512 KiB decoded per image, 640 KiB decoded-across a request, 8192 pixels per dimension and 16,777,216 pixels per image.+Local visual budgets are three images, 10 MiB decoded per image, 15 MiB decoded+across a request, 8192 pixels per dimension and 64,000,000 pixels per image.+The aggregate is independent: one 10 MiB image plus one 5 MiB image fits, as do+three 5 MiB images; three 10 MiB images do not. Original bytes are preserved.These are conservative Evenfire limits, not claims about upstream capabilities.The shared pure validator checks canonical base64, MIME/container framing andheader dimensions; it does not decode pixels or prove image decodability.The fixtures contain independently decoded 2x2 PNG/JPEG images.-The existing 1 MiB bound still applies to each complete serialized request and-HTTP envelope, including text, tools, history and the signed execution ticket.+V1 keeps its existing 1 MiB request/envelope ceiling. V2 has a 24 MiB ceiling+for the complete serialized request and HTTP envelope, including base64,+history and the signed execution ticket. V2 text, tools and other non-image+fields remain bounded to 1 MiB, measured with only image data blanked in a+temporary size projection; the actual request and its hash are not modified.The authorizer builds the exact V2 proxy envelope inside its transaction aftersigning but before commit. Exceeding the bound rolls back the new attempt,ticket and new reservation; it does not call the receipt finalizer before redeem.The Host uses the same envelope builder. V2 has no outer deadline: its deadlineis `request.deadlineMs`, part of the authorized hash. A proxy configured below-the shared envelope budget refuses visual activation at startup.+the shared visual envelope budget refuses visual activation at startup.++Desktop enforces the 10 MiB individual and 15 MiB combined attachment budgets.+RPC and Host permit a 24 MiB JSON body only on their message POST routes; their+6 MiB budget for other content and routes remains unchanged. The proxy's larger+parser requires a valid platform identity on the visual completion route.+Admin and unauthenticated requests retain the ordinary configured body limit.+`CODEX_LLM_PROXY_MAX_VISUAL_BODY_BYTES` controls the visual transport ceiling;+`CODEX_LLM_PROXY_MAX_BODY_BYTES` continues to control ordinary requests.The proxy projects parts to Responses `input_text` and `input_image` items withan inline data URL. The shape is grounded in the official Codex clientdiff --git a/docs/testing/codex-subscription-validation.md b/docs/testing/codex-subscription-validation.mdindex 84d70c011..1c6f5b9d3 100644--- a/docs/testing/codex-subscription-validation.md+++ b/docs/testing/codex-subscription-validation.md@@ -10,6 +10,15 @@ ordered text/image content and local image/envelope budgets. Its`fixtures/canonical-request-hashes.v2.json` freezes the new projection separately.The image parser validates container structure and dimensions, not decoded pixels.+Capacity checks cover 10 MiB per image, 15 MiB across up to three images, and a+24 MiB V2 envelope. Exercise 10 MiB, 10+5 MiB and 3x5 MiB acceptance, plus+individual/aggregate overflow. V1 and V2 non-image fields keep a 1 MiB ceiling;+unrelated RPC/Host routes keep 6 MiB. The larger proxy parser must not admit an+anonymous, wrong-scope or admin request, or enlarge V1's effective body limit.+Changing these budgets does not change OAuth, grants, ticket binding, origins,+fallback, or connection selection. Local capacity evidence is separate from+successful image interpretation by a real model.+Provider tests must cover both completion methods, direct/tool origins, promptcontext, redacted text parts, repeated bytes from distinct tool calls and thedefault-disabled model gate. Proxy conformance inspects the final upstream body,diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.tsindex f6145e1a7..6cef924d4 100644--- a/external-rest-api/src/releaseManifest.ts+++ b/external-rest-api/src/releaseManifest.ts@@ -9,7 +9,7 @@ export type ReleaseManifest = {export const releaseManifest: ReleaseManifest = {releaseId: 'v0.8.1',externalRestApiVersion: '0.1.82',- rpcProxyVersion: '0.1.77',+ rpcProxyVersion: '0.1.78',desktopVersion: '0.8.1',minimumDesktopVersion: '0.1.252',}diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 238251a96..f05a8e63b 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.339",+ "version": "0.1.340","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.339",+ "version": "0.1.340","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 7ab100ca0..0b6cff67a 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.339",+ "version": "0.1.340","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/bodylimits.test.ts b/mcp-host/src/__tests__/bodylimits.test.tsnew file mode 100644index 000000000..6cb3937c9--- /dev/null+++ b/mcp-host/src/__tests__/bodylimits.test.ts@@ -0,0 +1,251 @@+/**+ * Body-budget tests for the mcp-host runtime JSON parser.+ *+ * Proves on a real listening `RPCServer` socket:+ * - `POST /v1/runtime/messages` carries the documented image payloads (a 10MiB+ * image, 10MiB + 5MiB, and three 5MiB images) to the message handler instead+ * of being rejected as too large.+ * - The attachments arrive byte-identical: nothing is dropped, truncated or+ * re-encoded on the way through the parser.+ * - The larger ceiling is NOT a general text allowance: non-image bytes stay+ * capped at 6MiB, and every other route keeps its 6MiB parser.+ *+ * The auth boundary is exercised in its documented "auth disabled" test mode+ * (`CLERUM_ENABLE_AUTH=false`), matching server.attachments.test.ts; the edge+ * identity headers are the same ones rpc-proxy injects.+ */+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import type { AddressInfo } from 'net'+import type { IncomingMessage } from '../server/types'++const MIB = 1024 * 1024+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'++let baseUrl: string+let server: { start(): Promise<void>; stop(): Promise<void> }+let captured: IncomingMessage[] = []++beforeAll(async () => {+ process.env.CLERUM_ENABLE_AUTH = 'false'+ process.env.CLERUM_HOST_NAME = 'chatllm'+ vi.resetModules()+ // config reads auth settings at module load, so import after the test env is set.+ const { RPCServer } = await import('../server')+ const rpcServer = new RPCServer(0)+ rpcServer.onMessage(async (message: IncomingMessage) => {+ captured.push(message)+ return { success: true, status: 'completed', response: 'ok' }+ })+ await rpcServer.start()+ server = rpcServer+ const address = (rpcServer as unknown as { server: { address(): AddressInfo } }).server.address()+ baseUrl = `http://127.0.0.1:${address.port}`+})++afterAll(async () => {+ await server.stop()+})++const pngBase64Cache = new Map<number, string>()++/** Canonical base64 of a PNG whose decoded length is exactly `sizeBytes`. */+function pngBase64(sizeBytes: number): string {+ const cached = pngBase64Cache.get(sizeBytes)+ if (cached !== undefined) return cached+ const bytes = Buffer.alloc(sizeBytes)+ PNG_SIGNATURE.copy(bytes, 0)+ bytes.fill(0x41, PNG_SIGNATURE.length)+ const encoded = bytes.toString('base64')+ pngBase64Cache.set(sizeBytes, encoded)+ return encoded+}++/**+ * Flip a spare bit inside the final padded sextet. The payload still decodes to+ * the same length, but it is no longer the canonical encoding of those bytes,+ * so nothing may be credited for it.+ */+function withNonCanonicalTailBits(base64: string): string {+ const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0+ if (padding === 0) throw new Error('fixture expects a padded base64 payload')+ const lastIndex = base64.length - 1 - padding+ const value = BASE64_ALPHABET.indexOf(base64[lastIndex]!)+ if (value < 0) throw new Error('fixture expects a base64 alphabet character')+ const mutated = BASE64_ALPHABET[value | 1]!+ return base64.slice(0, lastIndex) + mutated + base64.slice(lastIndex + 1)+}++function imageAttachment(id: string, sizeBytes: number) {+ return {+ id,+ kind: 'image' as const,+ mimeType: 'image/png' as const,+ encoding: 'base64' as const,+ dataBase64: pngBase64(sizeBytes),+ filename: `${id}.png`,+ }+}++function rpcProxyEdgeHeaders(): Record<string, string> {+ return {+ 'content-type': 'application/json',+ 'x-clerum-edge-caller': 'rpc-proxy',+ 'x-clerum-edge-host-ref': 'chatllm',+ 'x-clerum-edge-user-id': 'user-1',+ }+}++function messagePayload(attachments: unknown) {+ return {+ content: 'look',+ channelType: 'rpc',+ channelId: 'c1',+ sender: 'user-1',+ timestamp: '2026-01-01T00:00:00.000Z',+ messageId: 'm-1',+ hostRef: 'chatllm',+ attachments,+ }+}++async function postMessage(payload: unknown): Promise<Response> {+ return fetch(`${baseUrl}/v1/runtime/messages`, {+ method: 'POST',+ headers: rpcProxyEdgeHeaders(),+ body: JSON.stringify(payload),+ })+}++describe('mcp-host runtime message body budget', () => {+ it('delivers a single 10MiB image (the per-image limit) byte-identical', async () => {+ captured = []+ const attachment = imageAttachment('a1', 10 * MIB)+ const response = await postMessage(messagePayload([attachment]))+ expect(response.status).toBe(200)+ expect(captured).toHaveLength(1)+ expect(captured[0].attachments).toEqual([attachment])+ })++ it('delivers 10MiB + 5MiB (the 15MiB total limit) in order', async () => {+ captured = []+ const attachments = [imageAttachment('a1', 10 * MIB), imageAttachment('a2', 5 * MIB)]+ const response = await postMessage(messagePayload(attachments))+ expect(response.status).toBe(200)+ expect(captured).toHaveLength(1)+ expect(captured[0].attachments?.map(item => item.dataBase64)).toEqual(+ attachments.map(item => item.dataBase64)+ )+ })++ it('delivers three 5MiB images in order', async () => {+ captured = []+ const attachments = [+ imageAttachment('a1', 5 * MIB),+ imageAttachment('a2', 5 * MIB),+ imageAttachment('a3', 5 * MIB),+ ]+ const response = await postMessage(messagePayload(attachments))+ expect(response.status).toBe(200)+ expect(captured).toHaveLength(1)+ expect(captured[0].attachments?.map(item => item.id)).toEqual(['a1', 'a2', 'a3'])+ expect(captured[0].attachments?.map(item => item.dataBase64)).toEqual(+ attachments.map(item => item.dataBase64)+ )+ })++ it('rejects a single image over the 10MiB per-image limit', async () => {+ captured = []+ const response = await postMessage(messagePayload([imageAttachment('a1', 11 * MIB)]))+ expect(response.status).toBe(413)+ expect(captured).toHaveLength(0)+ })++ it('rejects two 10MiB images because together they exceed the 15MiB total', async () => {+ captured = []+ const response = await postMessage(+ messagePayload([imageAttachment('a1', 10 * MIB), imageAttachment('a2', 10 * MIB)])+ )+ expect(response.status).toBe(413)+ expect(captured).toHaveLength(0)+ })++ it('rejects two 8MiB images on the 15MiB total alone, under the 24MiB ceiling', async () => {+ captured = []+ // Each image is under the 10MiB per-image limit and the body fits the 24MiB+ // ceiling, so the only rule that can reject this pair is the 15MiB total.+ const response = await postMessage(+ messagePayload([imageAttachment('a1', 8 * MIB), imageAttachment('a2', 8 * MIB)])+ )+ expect(response.status).toBe(413)+ expect(captured).toHaveLength(0)+ })++ it('still rejects text-only content over the 6MiB non-image budget', async () => {+ captured = []+ const response = await postMessage({+ ...messagePayload(undefined),+ content: 'x'.repeat(7 * MIB),+ })+ expect(response.status).toBe(413)+ expect(captured).toHaveLength(0)+ })++ it('rejects a body past the 24MiB ceiling', async () => {+ captured = []+ const response = await postMessage({+ ...messagePayload(undefined),+ content: 'x'.repeat(25 * MIB),+ })+ expect(response.status).toBe(413)+ expect(captured).toHaveLength(0)+ })++ it('does not credit an attachment that only claims to be an image', async () => {+ captured = []+ const response = await postMessage(+ messagePayload([+ {+ id: 'a1',+ kind: 'image',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: Buffer.alloc(5 * MIB, 0x41).toString('base64'),+ },+ ])+ )+ expect(response.status).toBe(413)+ expect(captured).toHaveLength(0)+ })++ it('does not credit base64 whose padding carries non-zero unused bits', async () => {+ captured = []+ const canonical = pngBase64(5 * MIB)+ const nonCanonical = withNonCanonicalTailBits(canonical)+ // Sanity: permissive decoding still yields the same bytes, so the only+ // thing that can reject this payload is the canonical-encoding rule.+ expect(Buffer.from(nonCanonical, 'base64').length).toBe(Buffer.from(canonical, 'base64').length)+ const response = await postMessage(+ messagePayload([+ {+ id: 'a1',+ kind: 'image',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: nonCanonical,+ },+ ])+ )+ expect(response.status).toBe(413)+ expect(captured).toHaveLength(0)+ })++ it('keeps the 6MiB parser on every other POST route', async () => {+ const response = await fetch(`${baseUrl}/v1/runtime/model`, {+ method: 'POST',+ headers: rpcProxyEdgeHeaders(),+ body: JSON.stringify({ model: 'x'.repeat(7 * MIB) }),+ })+ expect(response.status).toBe(413)+ })+})diff --git a/mcp-host/src/llm/providerAttemptAuthorizer.ts b/mcp-host/src/llm/providerAttemptAuthorizer.tsindex d6379d05b..49a36d1d8 100644--- a/mcp-host/src/llm/providerAttemptAuthorizer.ts+++ b/mcp-host/src/llm/providerAttemptAuthorizer.ts@@ -1,4 +1,7 @@-import { LIMITS, parseAuthorizeAttemptResponse } from '@clerum/llm-provider-attempt-contract'+import {+ parseAuthorizeAttemptResponse,+ requestBodyLimitBytes,+} from '@clerum/llm-provider-attempt-contract'export const AUTHORIZE_PATH = '/api/v1/mcp-host/llm/provider-attempts/authorize'@@ -77,10 +80,11 @@ export class ProviderAttemptAuthorizer {expiresAt: string}> {const serialized = JSON.stringify(body)- if (Buffer.byteLength(serialized, 'utf8') > LIMITS.maxRequestBodyBytes) {+ const bodyLimit = requestBodyLimitBytes(body.request)+ if (Buffer.byteLength(serialized, 'utf8') > bodyLimit) {throw new CodexAuthorizeError('payload_too_large',- 'Codex request exceeds 1 MiB; use fewer or smaller images, or reduce context'+ `Codex request exceeds ${bodyLimit / (1024 * 1024)} MiB; use fewer or smaller images, or reduce context`)}const jwt = this.options.readPlatformJwt()diff --git a/mcp-host/src/server.ts b/mcp-host/src/server.tsindex c7039bcea..1c6788290 100644--- a/mcp-host/src/server.ts+++ b/mcp-host/src/server.ts@@ -128,6 +128,116 @@ export type {SetTitleResult,} from './server/types'+/**+ * Body budgets for chat payloads carrying base64 image attachments.+ *+ * Intentional mirror of `rpc-proxy/src/app.ts`: rpc-proxy has no dependency on+ * any @clerum package, so the two services cannot share one source without a+ * new package. Both copies must change together.+ *+ * - MAX_CHAT_BODY_BYTES bounds the raw JSON body of `POST /v1/runtime/messages`.+ * 10MiB encodes to ~13.3MiB of base64, so a 10MiB image plus a 5MiB image+ * (the largest combination the 15MiB total allows) needs ~21MiB plus the+ * envelope. Every other route keeps the 6MiB default.+ * - MAX_NON_IMAGE_BODY_BYTES bounds that same body MINUS the base64 of images+ * counting against the documented attachment budget (10MiB per image, at+ * most 3 images / 15MiB total). Without the subtraction the attachment+ * budget would silently become a general 24MiB text budget.+ */+const MAX_CHAT_BODY_BYTES = 24 * 1024 * 1024+const MAX_NON_IMAGE_BODY_BYTES = 6 * 1024 * 1024+const MAX_CHAT_IMAGES = 3+const MAX_IMAGE_DECODED_BYTES = 10 * 1024 * 1024+const MAX_IMAGE_DECODED_BYTES_TOTAL = 15 * 1024 * 1024+const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+const JPEG_SIGNATURE = Buffer.from([0xff, 0xd8, 0xff])++/** Base64 alphabet value of one character, or null when it is not a base64 char. */+function base64SextetValue(char: string): number | null {+ const code = char.charCodeAt(0)+ if (code >= 0x41 && code <= 0x5a) return code - 0x41+ if (code >= 0x61 && code <= 0x7a) return code - 0x61 + 26+ if (code >= 0x30 && code <= 0x39) return code - 0x30 + 52+ if (code === 0x2b) return 62+ if (code === 0x2f) return 63+ return null+}++/**+ * Decoded byte length of a base64 payload, or null when it is not canonical.+ *+ * '=' padding makes the final group carry fewer bits than it encodes, so the+ * unused low bits of that group's last sextet must be zero (RFC 4648 §3.5). A+ * payload padding a non-zero tail still decodes in a permissive decoder, but it+ * is not the canonical encoding of its bytes: accepting it would let a caller+ * park arbitrary unused bytes inside the base64 length that the body budget is+ * asked to credit.+ */+function decodedBase64Bytes(dataBase64: string): number | null {+ if (dataBase64.length === 0 || dataBase64.length % 4 !== 0) return null+ if (!BASE64_RE.test(dataBase64)) return null+ const padding = dataBase64.endsWith('==') ? 2 : dataBase64.endsWith('=') ? 1 : 0+ if (padding > 0) {+ const lastSextet = base64SextetValue(dataBase64[dataBase64.length - 1 - padding] ?? '')+ if (lastSextet === null) return null+ if (padding === 1 && (lastSextet & 0b11) !== 0) return null+ if (padding === 2 && (lastSextet & 0b1111) !== 0) return null+ }+ // A 4-char group decodes to 3 bytes, the pad chars each drop one byte.+ return (dataBase64.length / 4) * 3 - padding+}++/**+ * Byte length of the base64 that counts against the documented image budget.+ * Only attachments with the exact wire shape the composer produces qualify:+ * `kind: 'image'`, `encoding: 'base64'`, a PNG/JPEG MIME type, canonical+ * base64 whose leading bytes are that image's signature, and at most 10MiB+ * decoded each within a 3-image / 15MiB total budget. Anything else is charged+ * to the non-image budget, so a claim cannot be smuggled through by mislabelling+ * a payload.+ */+function budgetedImageBase64Length(body: unknown): number {+ if (!body || typeof body !== 'object' || Array.isArray(body)) return 0+ const attachments = (body as { attachments?: unknown }).attachments+ if (!Array.isArray(attachments)) return 0++ let credited = 0+ let decodedTotal = 0+ let counted = 0+ for (const attachment of attachments) {+ if (counted >= MAX_CHAT_IMAGES) break+ if (!attachment || typeof attachment !== 'object') continue+ const candidate = attachment as {+ kind?: unknown+ encoding?: unknown+ mimeType?: unknown+ dataBase64?: unknown+ }+ if (candidate.kind !== 'image' || candidate.encoding !== 'base64') continue+ const mimeType = typeof candidate.mimeType === 'string' ? candidate.mimeType : ''+ if (mimeType !== 'image/png' && mimeType !== 'image/jpeg') continue+ const dataBase64 = typeof candidate.dataBase64 === 'string' ? candidate.dataBase64 : ''+ const decoded = decodedBase64Bytes(dataBase64)+ if (decoded === null || decoded <= 0 || decoded > MAX_IMAGE_DECODED_BYTES) continue+ if (decodedTotal + decoded > MAX_IMAGE_DECODED_BYTES_TOTAL) continue+ const signature = Buffer.from(dataBase64.slice(0, 16), 'base64')+ const matchesSignature =+ mimeType === 'image/png'+ ? signature.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)+ : signature.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)+ if (!matchesSignature) continue+ credited += dataBase64.length+ decodedTotal += decoded+ counted += 1+ }+ return credited+}++function chatBodyExceedsNonImageBudget(rawBodyBytes: number, body: unknown): boolean {+ return rawBodyBytes - budgetedImageBase64Length(body) > MAX_NON_IMAGE_BODY_BYTES+}+export class RPCServer {private server: http.Server | null = nullprivate app = express()@@ -190,8 +300,31 @@ export class RPCServer {})// Image attachments are sent as base64 in /v1/runtime/messages.- // 6mb comfortably covers the default 3mb binary limit plus JSON overhead.- this.app.use(express.json({ limit: '6mb' }))+ // That route alone gets the larger ceiling described above; every other+ // route keeps the 6mb default.+ const jsonParser = express.json({ limit: '6mb' })+ const chatJsonParser = express.json({+ limit: MAX_CHAT_BODY_BYTES,+ verify: (req, _res, buffer) => {+ ;(req as Request & { rawBodyBytes?: number }).rawBodyBytes = buffer.length+ },+ })+ this.app.use((req, res, next) => {+ const isChatMessagePost = req.method === 'POST' && req.path === '/v1/runtime/messages'+ const parser = isChatMessagePost ? chatJsonParser : jsonParser+ parser(req, res, error => {+ if (error || !isChatMessagePost) {+ next(error)+ return+ }+ const rawBodyBytes = (req as Request & { rawBodyBytes?: number }).rawBodyBytes+ if (rawBodyBytes !== undefined && chatBodyExceedsNonImageBudget(rawBodyBytes, req.body)) {+ json(res, 413, { error: 'Payload Too Large' })+ return+ }+ next()+ })+ })this.registerRoutes()}diff --git a/packages/llm-provider-attempt-contract/index.cjs b/packages/llm-provider-attempt-contract/index.cjsindex c431a3f5a..5329e8983 100644--- a/packages/llm-provider-attempt-contract/index.cjs+++ b/packages/llm-provider-attempt-contract/index.cjs@@ -16,7 +16,20 @@ const PROVIDER_ID = 'codex-subscription'const TICKET_TYP = 'codex-execution-ticket'const LIMITS = Object.freeze({+ // V1 ceiling, and the V2 ceiling for everything that is not image data. The+ // measurement that enforces the second half lives in+ // `measureNonImageRequestBytes` below.maxRequestBodyBytes: 1048576,+ /**+ * V2 request/envelope ceiling. It is deliberately larger than+ * `maxRequestBodyBytes` because a V2 body carries base64 image payloads, and+ * it is deliberately larger than the largest legal V2 image set+ * (`maxImages` * `maxImageBytes` decoded ≈ 21 MiB encoded) so the same number+ * covers the non-image share and the envelope's ticket and digest. It is not a+ * text/tool allowance: `measureNonImageRequestBytes` keeps that share on the+ * V1 ceiling.+ */+ maxVisualRequestBodyBytes: 25165824,maxMessages: 128,// Bound calls in each assistant message independently of advertised definitions.maxToolCalls: 32,@@ -144,6 +157,55 @@ function unknownKeys(obj, allowed) {return Object.keys(obj).filter(k => !allowed.has(k))}+/**+ * Request/envelope byte ceiling for a schema version. V2 raises the ceiling so+ * a body can carry image payloads; every other value keeps the V1 ceiling, so a+ * missing, unknown or lower version can never buy the larger budget.+ */+function schemaRequestBodyLimit(schemaVersion) {+ return schemaVersion === SCHEMA_VERSION_V2+ ? LIMITS.maxVisualRequestBodyBytes+ : LIMITS.maxRequestBodyBytes+}++/**+ * Ceiling for a request body, or for the envelope that carries it, BEFORE+ * parsing. Callers that must size an HTTP body — the client, the authorizer and+ * the proxy — only have the declared document at that point, so this keys off+ * the declaration and falls back to the V1 ceiling for anything else.+ */+function requestBodyLimitBytes(request) {+ return schemaRequestBodyLimit(isPlainObject(request) ? request.schemaVersion : undefined)+}++/**+ * UTF-8 length of a request with every image payload replaced by an empty+ * string: the caller-controlled text/tool share of the body.+ *+ * V2's larger ceiling exists for image data only, so this share stays on the V1+ * budget and declaring V2 never buys 24 MiB of text or tool definitions. The+ * measurement builds a detached shadow — the input's key order, shallow copies,+ * only image `data` blanked — measures it and discards it. The original+ * request, its hash and its projection are never touched, so this cannot change+ * what is authorized or signed.+ */+function measureNonImageRequestBytes(input) {+ const messages = input.messages+ const shadowMessages = Array.isArray(messages)+ ? messages.map(message => {+ const parts = isPlainObject(message) ? message.contentParts : undefined+ if (!Array.isArray(parts)) return message+ return {+ ...message,+ contentParts: parts.map(part =>+ isPlainObject(part) && part.type === 'image' ? { ...part, data: '' } : part+ ),+ }+ })+ : messages+ return Buffer.byteLength(JSON.stringify({ ...input, messages: shadowMessages }), 'utf8')+}+function isBoundedId(value) {return typeof value === 'string' && ID_PATTERN.test(value)}@@ -355,12 +417,29 @@ function parseTransportHints(raw) {* the same ordered checks and the same projection. Only the schema version* literal and the message field set differ, so a new version cannot become a* looser root by accident.+ *+ * Two size gates run first, before any key, id or payload work:+ * 1. the whole body against this version's ceiling (24 MiB for V2, 1 MiB+ * otherwise), then+ * 2. for V2 only, the body with every image payload blanked against the V1+ * ceiling — the images, not the text, are what the larger budget buys.+ * Both are pure measurements, so the projected value and its hash are+ * unaffected by them.*/function parseCodexCompletionRequestRoot(input, schemaVersion, messageKeys) {if (!isPlainObject(input)) return fail('invalid', 'request must be an object')+ const visualSchema = schemaVersion === SCHEMA_VERSION_V2const encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')- if (encoded > LIMITS.maxRequestBodyBytes) {- return fail('limit', 'request exceeds maxRequestBodyBytes')+ if (encoded > schemaRequestBodyLimit(schemaVersion)) {+ return fail(+ 'limit',+ visualSchema+ ? 'request exceeds maxVisualRequestBodyBytes'+ : 'request exceeds maxRequestBodyBytes'+ )+ }+ if (visualSchema && measureNonImageRequestBytes(input) > LIMITS.maxRequestBodyBytes) {+ return fail('limit', 'request exceeds maxRequestBodyBytes outside image data')}const extra = rejectUnknown(input, ROOT_KEYS, 'request')if (extra) return extra@@ -554,10 +633,15 @@ function hashCodexCompletionRequest(request) {* The returned envelope is re-parsed and re-hashed here, so it cannot carry a* request the contract rejects or a hash that disagrees with the request it* carries. Its exact UTF-8 byte length (JSON.stringify minus whitespace, the- * same serialization the transport sends) must fit `LIMITS.maxRequestBodyBytes`- * — the default the proxy enforces through CODEX_LLM_PROXY_MAX_BODY_BYTES. A- * deployment that lowers that proxy limit below the contract limit is not- * covered by this measurement.+ * same serialization the transport sends) must fit the ceiling of the schema it+ * carries — `requestBodyLimitBytes(request)`, i.e. 24 MiB for V2 and 1 MiB+ * otherwise — which is the number the proxy enforces through+ * CODEX_LLM_PROXY_MAX_BODY_BYTES. A deployment that lowers that proxy limit+ * below the contract limit is not covered by this measurement.+ *+ * The request inside the envelope already passed the V2 non-image budget, so+ * the V2 headroom here can only be spent by the ticket and the digest the+ * authorizer produced; a caller cannot reach this ceiling with text.*/function buildCodexProxyEnvelope(input) {if (!isPlainObject(input)) return fail('invalid', 'proxy envelope must be an object')@@ -577,9 +661,15 @@ function buildCodexProxyEnvelope(input) {return fail('request_hash_mismatch', 'requestHash does not match the request')}const envelope = { executionTicket: ticket, requestHash, request: parsed.value }+ const visualSchema = parsed.value.schemaVersion === SCHEMA_VERSION_V2const encoded = Buffer.byteLength(JSON.stringify(envelope), 'utf8')- if (encoded > LIMITS.maxRequestBodyBytes) {- return fail('limit', 'proxy envelope exceeds maxRequestBodyBytes')+ if (encoded > requestBodyLimitBytes(parsed.value)) {+ return fail(+ 'limit',+ visualSchema+ ? 'proxy envelope exceeds maxVisualRequestBodyBytes'+ : 'proxy envelope exceeds maxRequestBodyBytes'+ )}return ok(Object.freeze(envelope))}@@ -752,6 +842,7 @@ module.exports = {TICKET_TYP,LIMITS,VISUAL_LIMITS,+ requestBodyLimitBytes,stableStringify,parseCodexCompletionRequestV1,parseCodexCompletionRequestV2,diff --git a/packages/llm-provider-attempt-contract/index.d.ts b/packages/llm-provider-attempt-contract/index.d.tsindex 713140707..17a912308 100644--- a/packages/llm-provider-attempt-contract/index.d.ts+++ b/packages/llm-provider-attempt-contract/index.d.ts@@ -12,6 +12,12 @@* `codex-completion-request.v2` (the same closed root plus optional ordered* `contentParts` on user messages). V2 shares the V1 root field set on* purpose: it is not a looser schema.+ *+ * Two size ceilings, one policy: V1 keeps the 1 MiB body ceiling, and V2 raises+ * it to 24 MiB for image payloads only. Everything a caller writes that is not+ * image data — content, tool definitions, ids — stays on the 1 MiB budget in+ * both versions, and `requestBodyLimitBytes` is the number a pre-parse HTTP+ * body cap should use.*/export declare const SCHEMA_VERSION: 'codex-completion-request.v1'@@ -21,7 +27,10 @@ export declare const PROVIDER_ID: 'codex-subscription'export declare const TICKET_TYP: 'codex-execution-ticket'export declare const LIMITS: {+ /** V1 ceiling, and the V2 ceiling for everything that is not image data. */readonly maxRequestBodyBytes: 1048576+ /** V2 request/envelope ceiling; covers image payloads plus the V1 share. */+ readonly maxVisualRequestBodyBytes: 25165824readonly maxMessages: 128readonly maxToolCalls: 32readonly maxOutputTokens: 16384@@ -32,14 +41,15 @@ export declare const LIMITS: {/*** Conservative local safety/product budgets for V2 image parts. These are* deliberately not upstream facts: the frozen ChatGPT endpoint is not- * certified by these numbers.+ * certified by these numbers. The aggregate budget remains below three+ * maximum-sized images, so callers must satisfy both independent byte caps.*/export declare const VISUAL_LIMITS: {readonly maxImages: 3- readonly maxImageBytes: 524288- readonly maxTotalImageBytes: 655360+ readonly maxImageBytes: 10485760+ readonly maxTotalImageBytes: 15728640readonly maxImageDimension: 8192- readonly maxImagePixels: 16777216+ readonly maxImagePixels: 64000000}export type ContractResult<T> =@@ -218,6 +228,14 @@ export type CodexAttemptReceiptV1 = {}export declare function stableStringify(value: unknown): string+/**+ * Byte ceiling for a request body, or for the envelope that carries it, applied+ * BEFORE parsing: 24 MiB for a document that declares+ * `codex-completion-request.v2`, 1 MiB for anything else. Declaring V2 does not+ * raise the budget for text or tool definitions — the parser measures the body+ * with every image payload blanked and keeps that share on the 1 MiB ceiling.+ */+export declare function requestBodyLimitBytes(request: unknown): numberexport declare function parseCodexCompletionRequestV1(input: unknown): ContractResult<CodexCompletionRequestV1>diff --git a/packages/llm-provider-attempt-contract/index.test.cjs b/packages/llm-provider-attempt-contract/index.test.cjsindex bf762ea90..77df9820d 100644--- a/packages/llm-provider-attempt-contract/index.test.cjs+++ b/packages/llm-provider-attempt-contract/index.test.cjs@@ -549,6 +549,70 @@ function declaredHeaderPngOfSize(targetBytes) {])}+const MIB = 1024 * 1024+// The per-image ceiling this suite replaced. Kept as a literal so the tests+// prove the raise rather than restating the current constant.+const FORMER_IMAGE_CEILING = 524288++/**+ * Real PNG (correct CRCs, inflatable scanlines) padded to an exact byte length+ * with an ancillary tEXt chunk inserted before IEND. Ancillary chunks are+ * legal anywhere before IEND, so the image stays decodable while the file size+ * is exact.+ */+function realPngOfSize(targetBytes, width, height, seed) {+ const base = realPng(width, height, seed)+ const padding = targetBytes - base.length+ assert.ok(padding >= 0, `target ${targetBytes} is smaller than the real PNG ${base.length}`)+ if (padding === 0) return base+ assert.ok(padding >= 12, 'target must leave room for the padding chunk')+ const iend = base.subarray(base.length - 12)+ const body = base.subarray(0, base.length - 12)+ const payloadLength = padding - 12+ const text = Buffer.concat([+ Buffer.from('pad\0', 'latin1'),+ Buffer.alloc(Math.max(payloadLength - 4, 0), 0x20),+ ])+ assert.equal(text.length, payloadLength)+ return Buffer.concat([body, pngChunk('tEXt', text), iend])+}++/**+ * Structurally framed JPEG of an exact byte length: SOI, a frame header that+ * declares the dimensions, a start-of-scan segment, entropy payload and EOI.+ * This is the container the v2 JPEG checks were written against — marker+ * framing and declared dimensions — not an entropy-decodable image; the module+ * documents that it never decodes scan data.+ */+function jpegOfSize(targetBytes, width = 2, height = 2) {+ const sofPayload = Buffer.alloc(9)+ sofPayload[0] = 8+ sofPayload.writeUInt16BE(height, 1)+ sofPayload.writeUInt16BE(width, 3)+ sofPayload[5] = 1+ sofPayload[6] = 1+ sofPayload[7] = 0x11+ sofPayload[8] = 0+ const segmentLength = Buffer.alloc(2)+ segmentLength.writeUInt16BE(sofPayload.length + 2, 0)+ const sof = Buffer.concat([Buffer.from([0xff, 0xc0]), segmentLength, sofPayload])++ const sosPayload = Buffer.alloc(6)+ const sosLength = Buffer.alloc(2)+ sosLength.writeUInt16BE(sosPayload.length + 2, 0)+ const sos = Buffer.concat([Buffer.from([0xff, 0xda]), sosLength, sosPayload])++ const entropyLength = targetBytes - (2 + sof.length + sos.length + 2)+ assert.ok(entropyLength >= 1, 'target must leave room for entropy-coded data')+ return Buffer.concat([+ Buffer.from([0xff, 0xd8]),+ sof,+ sos,+ Buffer.alloc(entropyLength, 0x2a),+ Buffer.from([0xff, 0xd9]),+ ])+}+function imagePart(data, mimeType = 'image/png') {return {type: 'image',@@ -806,20 +870,59 @@ test('v2 limits: image count, encoder bound, per-image bytes, total bytes, dimen)assert.equal(decoded.code, 'limit')- const bigA = realPng(335, 335, 1)- const bigB = realPng(335, 335, 2)- assert.ok(bigA.length < contract.VISUAL_LIMITS.maxImageBytes)- assert.ok(bigA.length + bigB.length > contract.VISUAL_LIMITS.maxTotalImageBytes)- const single = contract.parseCodexCompletionRequest(- v2WithParts([imagePart(bigA.toString('base64'))])+ // Above the ceiling this suite replaced, in both accepted containers.+ const pngOverFormerCeiling = declaredHeaderPngOfSize(FORMER_IMAGE_CEILING + 1)+ assert.equal(pngOverFormerCeiling.length, FORMER_IMAGE_CEILING + 1)+ const acceptedPng = contract.parseCodexCompletionRequest(+ v2WithParts([imagePart(pngOverFormerCeiling.toString('base64'))])+ )+ assert.equal(acceptedPng.ok, true, acceptedPng.message)+ const acceptedJpeg = contract.parseCodexCompletionRequest(+ v2WithParts([imagePart(jpegOfSize(FORMER_IMAGE_CEILING + 1).toString('base64'), 'image/jpeg')])+ )+ assert.equal(acceptedJpeg.ok, true, acceptedJpeg.message)++ // 3 MiB, and exactly the per-image ceiling, are inside the budget.+ const acceptedThreeMiB = contract.parseCodexCompletionRequest(+ v2WithParts([imagePart(declaredHeaderPngOfSize(3 * MIB).toString('base64'))]))- assert.equal(single.ok, true, single.message)- const total = contract.parseCodexCompletionRequest(- v2WithParts([imagePart(bigA.toString('base64')), imagePart(bigB.toString('base64'))])+ assert.equal(acceptedThreeMiB.ok, true, acceptedThreeMiB.message)+ const acceptedCeiling = contract.parseCodexCompletionRequest(+ v2WithParts([+ imagePart(declaredHeaderPngOfSize(contract.VISUAL_LIMITS.maxImageBytes).toString('base64')),+ ])+ )+ assert.equal(acceptedCeiling.ok, true, acceptedCeiling.message)++ // One byte over the per-image ceiling, as a container that is otherwise valid.+ const overCeiling = contract.parseCodexCompletionRequest(+ v2WithParts([+ imagePart(+ declaredHeaderPngOfSize(contract.VISUAL_LIMITS.maxImageBytes + 1).toString('base64')+ ),+ ])+ )+ assert.equal(overCeiling.ok, false)+ assert.equal(overCeiling.code, 'limit')+ assert.match(overCeiling.message, /image exceeds/)+ assert.match(overCeiling.message, new RegExp(String(contract.VISUAL_LIMITS.maxImageBytes)))++ // A larger individual image does not increase the aggregate resource budget.+ const tenMiB = declaredHeaderPngOfSize(10 * MIB).toString('base64')+ const fiveMiB = declaredHeaderPngOfSize(5 * MIB).toString('base64')+ const combined = contract.parseCodexCompletionRequest(+ v2WithParts([imagePart(tenMiB), imagePart(fiveMiB)])+ )+ assert.equal(combined.ok, true, combined.message)+ const overAggregate = contract.parseCodexCompletionRequest(+ v2WithParts([+ imagePart(tenMiB),+ imagePart(declaredHeaderPngOfSize(5 * MIB + 1).toString('base64')),+ ]))- assert.equal(total.ok, false)- assert.equal(total.code, 'limit')- assert.match(total.message, /total image bytes/)+ assert.equal(overAggregate.ok, false)+ assert.equal(overAggregate.code, 'limit')+ assert.match(overAggregate.message, /total image bytes/)const atDimension = contract.parseCodexCompletionRequest(v2WithParts([@@ -835,29 +938,41 @@ test('v2 limits: image count, encoder bound, per-image bytes, total bytes, dimenassert.equal(overDimension.code, 'limit')assert.match(overDimension.message, /dimension/)- const pixelsAtLimit =- contract.VISUAL_LIMITS.maxImagePixels / contract.VISUAL_LIMITS.maxImageDimension+ // A 48 MP phone capture (8064x6048) is the payload the raise exists for.+ const phonePixels = 8064 * 6048+ assert.ok(phonePixels < contract.VISUAL_LIMITS.maxImagePixels)+ const atPhoneShape = contract.parseCodexCompletionRequest(+ v2WithParts([imagePart(declaredHeaderPng(8064, 6048).toString('base64'))])+ )+ assert.equal(atPhoneShape.ok, true, atPhoneShape.message)++ // Exactly the pixel ceiling, then one row over it.+ const pixelsAtLimit = 8000+ assert.equal(pixelsAtLimit * pixelsAtLimit, contract.VISUAL_LIMITS.maxImagePixels)const atPixels = contract.parseCodexCompletionRequest(- v2WithParts([- imagePart(- declaredHeaderPng(contract.VISUAL_LIMITS.maxImageDimension, pixelsAtLimit).toString(- 'base64'- )- ),- ])+ v2WithParts([imagePart(declaredHeaderPng(pixelsAtLimit, pixelsAtLimit).toString('base64'))]))assert.equal(atPixels.ok, true, atPixels.message)const overPixels = contract.parseCodexCompletionRequest(+ v2WithParts([imagePart(declaredHeaderPng(pixelsAtLimit, pixelsAtLimit + 1).toString('base64'))])+ )+ assert.equal(overPixels.code, 'limit')+ assert.match(overPixels.message, /pixel count/)++ // Both dimensions inside the dimension ceiling, product over the pixel+ // ceiling: isolates the pixel rule from the dimension rule.+ const squareOverPixels = contract.parseCodexCompletionRequest(v2WithParts([imagePart(- declaredHeaderPng(contract.VISUAL_LIMITS.maxImageDimension, pixelsAtLimit + 1).toString(- 'base64'- )+ declaredHeaderPng(+ contract.VISUAL_LIMITS.maxImageDimension,+ contract.VISUAL_LIMITS.maxImageDimension+ ).toString('base64')),]))- assert.equal(overPixels.code, 'limit')- assert.match(overPixels.message, /pixel count/)+ assert.equal(squareOverPixels.code, 'limit')+ assert.match(squareOverPixels.message, /pixel count/)const wrongMime = contract.parseCodexCompletionRequest(v2WithParts([imagePart(png, 'image/jpeg')])@@ -869,7 +984,7 @@ test('v2 limits: image count, encoder bound, per-image bytes, total bytes, dimenassert.equal(jpegAsPng.ok, false)})-test('v2 visual budgets are request-scoped across messages, not per message', () => {+test('v2 visual budgets are request-scoped across messages: three 5 MiB images fit, four do not', () => {const png = IMAGE_DATA.pngconst userWithImages = count => ({role: 'user',@@ -891,13 +1006,213 @@ test('v2 visual budgets are request-scoped across messages, not per message', ())assert.equal(oneEach.ok, true, oneEach.message)- // The same aggregate rule holds for total bytes with one image per message.- const bigA = realPng(335, 335, 5)- const bigB = realPng(335, 335, 7)- const splitBytes = contract.parseCodexCompletionRequest(- v2WithMessages([userWithImages(0), userWithImages(0)])+ // Three 5 MiB images across messages fill the unchanged aggregate budget.+ const atCeiling = declaredHeaderPngOfSize(5 * MIB).toString('base64')+ const messageWith = encoded => ({+ role: 'user',+ content: '',+ contentParts: [imagePart(encoded)],+ })+ const oneEachAtCeiling = contract.parseCodexCompletionRequest(+ v2WithMessages([messageWith(atCeiling), messageWith(atCeiling), messageWith(atCeiling)])+ )+ assert.equal(oneEachAtCeiling.ok, true, oneEachAtCeiling.message)+ // Three ceiling images are the exact aggregate boundary, and the encoded body+ // is larger than the V1 ceiling — this is the request that needs the V2 budget.+ const ceilingBody = Buffer.byteLength(+ JSON.stringify(+ v2WithMessages([messageWith(atCeiling), messageWith(atCeiling), messageWith(atCeiling)])+ ),+ 'utf8'+ )+ assert.ok(ceilingBody > contract.LIMITS.maxRequestBodyBytes)+ assert.ok(ceilingBody <= contract.LIMITS.maxVisualRequestBodyBytes)++ // A fourth ceiling image is refused before the count gate is reached: four+ // 5 MiB payloads encode to more than the 24 MiB body ceiling. The count rule+ // is exercised with small images above; this asserts which gate fires first+ // for maximum-size payloads.+ const fourMessages = contract.parseCodexCompletionRequest(+ v2WithMessages([+ messageWith(atCeiling),+ messageWith(atCeiling),+ messageWith(atCeiling),+ messageWith(atCeiling),+ ])+ )+ assert.equal(fourMessages.ok, false)+ assert.equal(fourMessages.code, 'limit')+ assert.equal(fourMessages.message, 'request exceeds maxVisualRequestBodyBytes')+})++/**+ * The request with every image payload replaced by an empty string — the+ * non-image share the V2 budget is defined on. Used to find an exact boundary;+ * the assertions below always check the contract's verdict, not this helper.+ */+function nonImageBytes(request) {+ return Buffer.byteLength(+ JSON.stringify({+ ...request,+ messages: request.messages.map(message =>+ Array.isArray(message.contentParts)+ ? {+ ...message,+ contentParts: message.contentParts.map(part =>+ part.type === 'image' ? { ...part, data: '' } : part+ ),+ }+ : message+ ),+ }),+ 'utf8'+ )+}++test('requestBodyLimitBytes: V2 declares 24 MiB; every other body keeps the 1 MiB ceiling', () => {+ assert.equal(contract.LIMITS.maxRequestBodyBytes, 1048576)+ assert.equal(contract.LIMITS.maxVisualRequestBodyBytes, 25165824)+ assert.equal(contract.VISUAL_LIMITS.maxImages, 3)+ assert.equal(contract.VISUAL_LIMITS.maxImageBytes, 10485760)+ assert.equal(contract.VISUAL_LIMITS.maxTotalImageBytes, 15728640)+ assert.equal(contract.VISUAL_LIMITS.maxImageDimension, 8192)+ assert.equal(contract.VISUAL_LIMITS.maxImagePixels, 64000000)++ for (const v2 of [VISUAL_FIXTURE.png, VISUAL_FIXTURE.jpeg, VISUAL_FIXTURE.pngImageOnly]) {+ assert.equal(v2.schemaVersion, contract.SCHEMA_VERSION_V2)+ assert.equal(contract.requestBodyLimitBytes(v2), 25165824)+ }+ // A declaration is not a payload: unknown, missing and non-object bodies keep+ // the smaller ceiling so a caller cannot ask for the larger budget it has not+ // satisfied.+ for (const other of [+ BASE,+ { ...BASE, schemaVersion: 'codex-completion-request.v3' },+ { ...BASE, schemaVersion: undefined },+ {},+ null,+ undefined,+ 'x',+ 7,+ [],+ ]) {+ assert.equal(contract.requestBodyLimitBytes(other), 1048576, String(other))+ }+})++test('v2 preserves the non-image budget: text and tools stay on the 1 MiB ceiling', () => {+ const { maxRequestBodyBytes, maxVisualRequestBodyBytes } = contract.LIMITS+ const image = imagePart(IMAGE_DATA.png)+ const overflow = 'request exceeds maxRequestBodyBytes outside image data'+ const longText = 'x'.repeat(2 * MIB)++ // Images do not buy text: 2 MiB of content-class payload is refused far below+ // the 24 MiB ceiling the same body is allowed to use for image data.+ const textHeavy = contract.parseCodexCompletionRequest(+ v2WithParts([image, { type: 'text', text: longText }], longText)+ )+ assert.equal(textHeavy.ok, false)+ assert.equal(textHeavy.code, 'limit')+ assert.equal(textHeavy.message, overflow)++ // A text-only V2 body is not a 24 MiB allowance either.+ assert.deepEqual(contract.parseCodexCompletionRequest(v2TextRequest(longText)), {+ ok: false,+ code: 'limit',+ message: overflow,+ })++ // Tool definitions are on the same caller-controlled budget.+ const toolHeavy = contract.parseCodexCompletionRequest({+ ...v2WithParts([image]),+ tools: [{ name: 'read', description: 'y'.repeat(2 * MIB), parameters: {} }],+ })+ assert.equal(toolHeavy.ok, false)+ assert.equal(toolHeavy.code, 'limit')+ assert.equal(toolHeavy.message, overflow)++ // Exact boundary. The image is blanked out of the measurement, so the largest+ // accepted text still leaves the body far under the V2 ceiling, and one byte+ // more is refused by the non-image rule.+ const withImageAndText = length =>+ v2WithParts([image, { type: 'text', text: 'z'.repeat(length) }], 'z'.repeat(length))+ const base = nonImageBytes(withImageAndText(0))+ const growth = (nonImageBytes(withImageAndText(10)) - base) / 10+ assert.equal(growth, 2, 'content and its text part both carry the payload')+ const exactLength = Math.floor((maxRequestBodyBytes - base) / growth)+ const boundary = nonImageBytes(withImageAndText(exactLength))+ assert.ok(+ boundary <= maxRequestBodyBytes && boundary > maxRequestBodyBytes - growth,+ `non-image boundary landed at ${boundary}`)- return undefined === splitBytes+ const bodyAtBoundary = Buffer.byteLength(JSON.stringify(withImageAndText(exactLength)), 'utf8')+ assert.ok(+ bodyAtBoundary < maxVisualRequestBodyBytes,+ 'the non-image boundary is decided well below the V2 ceiling'+ )+ const atLimit = contract.parseCodexCompletionRequest(withImageAndText(exactLength))+ assert.equal(atLimit.ok, true, atLimit.message)+ const overLimit = contract.parseCodexCompletionRequest(withImageAndText(exactLength + 1))+ assert.equal(overLimit.ok, false)+ assert.equal(overLimit.code, 'limit')+ assert.equal(overLimit.message, overflow)+ assert.ok(+ nonImageBytes(withImageAndText(exactLength + 1)) > maxRequestBodyBytes,+ 'the rejection is the non-image budget, not another gate'+ )+})++test('v2 total budget: the raw body is capped at 24 MiB and the three budgets stay consistent', () => {+ const { maxVisualRequestBodyBytes, maxRequestBodyBytes } = contract.LIMITS+ // The V2 ceiling must cover the largest legal image set (3 x 5 MiB decoded, so+ // ~21 MiB of canonical base64) plus the whole non-image share. Asserted so a+ // future change to any of the three image numbers is caught here.+ const aggregateEncoded = 4 * Math.ceil(contract.VISUAL_LIMITS.maxTotalImageBytes / 3) + 8+ assert.ok(aggregateEncoded + maxRequestBodyBytes < maxVisualRequestBodyBytes)++ // Over the ceiling is refused by the size gate, before any payload work.+ const oversized = v2WithParts([imagePart('A'.repeat(maxVisualRequestBodyBytes))])+ assert.ok(Buffer.byteLength(JSON.stringify(oversized), 'utf8') > maxVisualRequestBodyBytes)+ const refused = contract.parseCodexCompletionRequest(oversized)+ assert.equal(refused.ok, false)+ assert.equal(refused.code, 'limit')+ assert.equal(refused.message, 'request exceeds maxVisualRequestBodyBytes')++ // The same shape parsed as V1 keeps the V1 ceiling and its V1 message: the+ // larger budget is a property of the version, not of the payload.+ const asV1 = contract.parseCodexCompletionRequestV1({+ ...oversized,+ schemaVersion: contract.SCHEMA_VERSION,+ })+ assert.equal(asV1.ok, false)+ assert.equal(asV1.code, 'limit')+ assert.equal(asV1.message, 'request exceeds maxRequestBodyBytes')+})++test('large real PNG: CRCs and inflatable scanlines at 3 MiB and at the 10 MiB ceiling', () => {+ const cases = [+ ['3 MiB', 3 * MIB, 512, 512, 21],+ ['10 MiB ceiling', contract.VISUAL_LIMITS.maxImageBytes, 1150, 1150, 31],+ ]+ for (const [label, target, width, height, seed] of cases) {+ const png = realPngOfSize(target, width, height, seed)+ assert.equal(png.length, target, label)+ const chunks = pngChunks(png)+ assert.deepEqual(+ chunks.map(chunk => chunk.type),+ ['IHDR', 'IDAT', 'tEXt', 'IEND'],+ label+ )+ for (const chunk of chunks) {+ assert.equal(chunk.crc, zlib.crc32(chunk.crcInput) >>> 0, `${label} ${chunk.type} crc`)+ }+ const raw = zlib.inflateSync(chunks[1].data)+ assert.equal(raw.length, height * (1 + width * 3), label)+ const parsed = contract.parseCodexCompletionRequest(+ v2WithParts([imagePart(png.toString('base64'))])+ )+ assert.equal(parsed.ok, true, `${label}: ${parsed.message}`)+ }})test('buildCodexProxyEnvelope: exact shape, no outer deadline, exact size boundary', () => {@@ -925,7 +1240,7 @@ test('buildCodexProxyEnvelope: exact shape, no outer deadline, exact size boundaassert.equal(Object.isFrozen(envelope.value), true)assert.equal(Buffer.byteLength(JSON.stringify(envelope.value), 'utf8') <=- contract.LIMITS.maxRequestBodyBytes,+ contract.requestBodyLimitBytes(envelope.value.request),true)@@ -940,46 +1255,84 @@ test('buildCodexProxyEnvelope: exact shape, no outer deadline, exact size bounda'the deadline is bound by the request hash')- const envelopeFor = contentLength => {- const request = contract.parseCodexCompletionRequest(v2TextRequest('x'.repeat(contentLength)))+ // V2 exact boundary. The request's own share is bounded (images at ~21 MiB+ // encoded, everything else at 1 MiB), so padding its text can no longer reach+ // the envelope ceiling — the ticket is the field that moves it, and the ticket+ // is what the authorizer really adds.+ const envelopeForTicket = ticketBytes => {+ const request = contract.parseCodexCompletionRequest(VISUAL_FIXTURE.png)assert.equal(request.ok, true, request.message)const hash = contract.hashCodexCompletionRequest(request.value)+ const executionTicket = 't'.repeat(ticketBytes)return {- request,+ executionTicket,hash,+ request,size: Buffer.byteLength(- JSON.stringify({ executionTicket: ticket, requestHash: hash, request: request.value }),+ JSON.stringify({ executionTicket, requestHash: hash, request: request.value }),'utf8'),}}- const seed = 1000- const seedEnvelope = envelopeFor(seed)- const exactLength = seed + (contract.LIMITS.maxRequestBodyBytes - seedEnvelope.size)- const exact = envelopeFor(exactLength)+ const limit = contract.requestBodyLimitBytes(parsed.value)+ assert.equal(limit, contract.LIMITS.maxVisualRequestBodyBytes)+ const probe = envelopeForTicket(8)+ const exactTicket = 8 + (limit - probe.size)+ const exact = envelopeForTicket(exactTicket)+ assert.equal(exact.size, limit)const atLimit = contract.buildCodexProxyEnvelope({- executionTicket: ticket,+ executionTicket: exact.executionTicket,requestHash: exact.hash,request: exact.request.value,})assert.equal(atLimit.ok, true, atLimit.message)- assert.equal(- Buffer.byteLength(JSON.stringify(atLimit.value), 'utf8'),- contract.LIMITS.maxRequestBodyBytes- )+ assert.equal(Buffer.byteLength(JSON.stringify(atLimit.value), 'utf8'), limit)- const over = envelopeFor(exactLength + 1)- assert.ok(- Buffer.byteLength(JSON.stringify(over.request.value), 'utf8') <=- contract.LIMITS.maxRequestBodyBytes- )+ const over = envelopeForTicket(exactTicket + 1)+ assert.equal(over.size, limit + 1)const refused = contract.buildCodexProxyEnvelope({- executionTicket: ticket,+ executionTicket: over.executionTicket,requestHash: over.hash,request: over.request.value,})assert.equal(refused.ok, false)assert.equal(refused.code, 'limit')+ assert.equal(refused.message, 'proxy envelope exceeds maxVisualRequestBodyBytes')++ // V1 keeps the 1 MiB envelope ceiling: same construction, exact boundary, and+ // the V1 failure message.+ const v1Request = contract.parseCodexCompletionRequest({ ...BASE, deadlineMs: 5000 })+ assert.equal(v1Request.ok, true)+ const v1Hash = contract.hashCodexCompletionRequest(v1Request.value)+ const v1Size = ticketBytes =>+ Buffer.byteLength(+ JSON.stringify({+ executionTicket: 't'.repeat(ticketBytes),+ requestHash: v1Hash,+ request: v1Request.value,+ }),+ 'utf8'+ )+ const v1Ticket = 8 + (contract.LIMITS.maxRequestBodyBytes - v1Size(8))+ const v1Exact = contract.buildCodexProxyEnvelope({+ executionTicket: 't'.repeat(v1Ticket),+ requestHash: v1Hash,+ request: v1Request.value,+ })+ assert.equal(v1Exact.ok, true, v1Exact.message)+ assert.equal(Buffer.byteLength(JSON.stringify(v1Exact.value), 'utf8'), v1Size(v1Ticket))+ assert.equal(+ Buffer.byteLength(JSON.stringify(v1Exact.value), 'utf8'),+ contract.LIMITS.maxRequestBodyBytes+ )+ const v1Over = contract.buildCodexProxyEnvelope({+ executionTicket: 't'.repeat(v1Ticket + 1),+ requestHash: v1Hash,+ request: v1Request.value,+ })+ assert.equal(v1Over.ok, false)+ assert.equal(v1Over.code, 'limit')+ assert.equal(v1Over.message, 'proxy envelope exceeds maxRequestBodyBytes')})test('buildCodexProxyEnvelope: fails closed on hash mismatch, bad input and invalid requests', () => {diff --git a/packages/llm-provider-attempt-contract/visualPayload.cjs b/packages/llm-provider-attempt-contract/visualPayload.cjsindex a44978e2d..b8d2be46e 100644--- a/packages/llm-provider-attempt-contract/visualPayload.cjs+++ b/packages/llm-provider-attempt-contract/visualPayload.cjs@@ -13,14 +13,23 @@* The budget below is a conservative local safety/product decision. It is not* an upstream capability fact; the frozen ChatGPT endpoint is not certified by* these numbers.+ *+ * The raised ceiling supports larger original captures, including 8064x6048+ * frames, without requiring a lossy re-encode. `maxImageBytes` and+ * `maxImagePixels` independently bound the payload; the+ * container checks above are unchanged by the raise, and the pixel budget stays+ * a declared-header bound rather than a decode.+ *+ * The 15 MiB aggregate is independent from the 10 MiB per-image ceiling:+ * one large photo can fit without doubling the maximum request allocation.*/const VISUAL_LIMITS = Object.freeze({maxImages: 3,- maxImageBytes: 524288,- maxTotalImageBytes: 655360,+ maxImageBytes: 10485760,+ maxTotalImageBytes: 15728640,maxImageDimension: 8192,- maxImagePixels: 16777216,+ maxImagePixels: 64000000,})// Exact encoded length of a canonical base64 string that decodes todiff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex 13318c48c..75e769a23 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.77",+ "version": "0.1.78","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.77",+ "version": "0.1.78","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex 23471ba1e..78252bf44 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.77",+ "version": "0.1.78","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --git a/rpc-proxy/src/__tests__/bodylimits.test.ts b/rpc-proxy/src/__tests__/bodylimits.test.tsnew file mode 100644index 000000000..fa1cc0674--- /dev/null+++ b/rpc-proxy/src/__tests__/bodylimits.test.ts@@ -0,0 +1,255 @@+/**+ * Body-budget tests for the rpc-proxy JSON parser.+ *+ * Proves on a real listening `createApp()` socket:+ * - `POST /api/v1/rpc/hosts/:hostRef/messages` carries the documented image+ * payloads (a 10MiB image, 10MiB + 5MiB, and three 5MiB images) to the auth+ * boundary instead of being rejected as too large.+ * - The larger ceiling is NOT a general text allowance: non-image bytes stay+ * capped at 6MiB, and every other route keeps its 6MiB parser.+ * - The sandbox-ui view proxy stays parser-free, so http-proxy can stream the+ * raw body upstream instead of the parser draining it.+ *+ * Auth is deliberately NOT mocked. A 401 is the proof that the body crossed the+ * parser and only the auth boundary stopped it.+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import type { Server } from 'http'+import type { AddressInfo } from 'net'+import { createApp } from '../app.js'++const MIB = 1024 * 1024+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'++let baseUrl: string+let server: Server++beforeAll(async () => {+ server = createApp().listen(0)+ await new Promise<void>(resolve => server.once('listening', resolve))+ baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`+})++afterAll(async () => {+ // The view-proxy case aborts a request mid-body, so drop any socket that is+ // still open: a listener left behind here would surface as a parse error in+ // whichever sibling test file ran next.+ server.closeAllConnections()+ await new Promise<void>(resolve => server.close(() => resolve()))+})++const pngBase64Cache = new Map<number, string>()++/** Canonical base64 of a PNG whose decoded length is exactly `sizeBytes`. */+function pngBase64(sizeBytes: number): string {+ const cached = pngBase64Cache.get(sizeBytes)+ if (cached !== undefined) return cached+ const bytes = Buffer.alloc(sizeBytes)+ PNG_SIGNATURE.copy(bytes, 0)+ bytes.fill(0x41, PNG_SIGNATURE.length)+ const encoded = bytes.toString('base64')+ pngBase64Cache.set(sizeBytes, encoded)+ return encoded+}++/**+ * Flip a spare bit inside the final padded sextet. The payload still decodes to+ * the same length, but it is no longer the canonical encoding of those bytes,+ * so nothing may be credited for it.+ */+function withNonCanonicalTailBits(base64: string): string {+ const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0+ if (padding === 0) throw new Error('fixture expects a padded base64 payload')+ const lastIndex = base64.length - 1 - padding+ const value = BASE64_ALPHABET.indexOf(base64[lastIndex]!)+ if (value < 0) throw new Error('fixture expects a base64 alphabet character')+ const mutated = BASE64_ALPHABET[value | 1]!+ return base64.slice(0, lastIndex) + mutated + base64.slice(lastIndex + 1)+}++function imageAttachment(id: string, sizeBytes: number) {+ return {+ id,+ kind: 'image',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: pngBase64(sizeBytes),+ filename: `${id}.png`,+ }+}++async function post(path: string, body: string): Promise<Response> {+ return fetch(`${baseUrl}${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body,+ })+}++const MESSAGE_PATH = '/api/v1/rpc/hosts/chatllm/messages'++async function postMessage(payload: unknown): Promise<Response> {+ return post(MESSAGE_PATH, JSON.stringify(payload))+}++describe('rpc-proxy chat message body budget', () => {+ it('carries a 10MiB image (the per-image limit) to the auth boundary', async () => {+ const body = JSON.stringify({+ content: 'look',+ attachments: [imageAttachment('a1', 10 * MIB)],+ })+ // 10MiB of bytes encodes to more than 13MiB, well past the old 6MiB parser.+ expect(Buffer.byteLength(body)).toBeGreaterThan(13 * MIB)+ const response = await post(MESSAGE_PATH, body)+ expect(response.status).toBe(401)+ })++ it('carries 10MiB + 5MiB (the 15MiB total limit) to the auth boundary', async () => {+ const body = JSON.stringify({+ content: 'look',+ attachments: [imageAttachment('a1', 10 * MIB), imageAttachment('a2', 5 * MIB)],+ })+ expect(Buffer.byteLength(body)).toBeGreaterThan(20 * MIB)+ const response = await post(MESSAGE_PATH, body)+ expect(response.status).toBe(401)+ })++ it('carries three 5MiB images to the auth boundary', async () => {+ const body = JSON.stringify({+ content: 'look',+ attachments: [+ imageAttachment('a1', 5 * MIB),+ imageAttachment('a2', 5 * MIB),+ imageAttachment('a3', 5 * MIB),+ ],+ })+ expect(Buffer.byteLength(body)).toBeGreaterThan(20 * MIB)+ const response = await post(MESSAGE_PATH, body)+ expect(response.status).toBe(401)+ })++ it('rejects a single image over the 10MiB per-image limit', async () => {+ // Fits the 24MiB body ceiling, so this rejection is the budget gate, not the+ // parser: an uncredited 11MiB image is charged to the 6MiB non-image budget.+ const body = JSON.stringify({+ content: 'look',+ attachments: [imageAttachment('a1', 11 * MIB)],+ })+ expect(Buffer.byteLength(body)).toBeLessThan(24 * MIB)+ const response = await post(MESSAGE_PATH, body)+ expect(response.status).toBe(413)+ })++ it('rejects two 10MiB images because together they exceed the 15MiB total', async () => {+ const body = JSON.stringify({+ content: 'look',+ attachments: [imageAttachment('a1', 10 * MIB), imageAttachment('a2', 10 * MIB)],+ })+ const response = await post(MESSAGE_PATH, body)+ expect(response.status).toBe(413)+ })++ it('rejects two 8MiB images on the 15MiB total alone, under the 24MiB ceiling', async () => {+ // Each image is under the 10MiB per-image limit and the body fits the 24MiB+ // ceiling, so the only rule that can reject this pair is the 15MiB total:+ // the over-total image is not credited and lands on the 6MiB non-image budget.+ const body = JSON.stringify({+ content: 'look',+ attachments: [imageAttachment('a1', 8 * MIB), imageAttachment('a2', 8 * MIB)],+ })+ expect(Buffer.byteLength(body)).toBeLessThan(24 * MIB)+ const response = await post(MESSAGE_PATH, body)+ expect(response.status).toBe(413)+ })++ it('still rejects text-only content over the 6MiB non-image budget', async () => {+ const response = await postMessage({ content: 'x'.repeat(7 * MIB), attachments: [] })+ expect(response.status).toBe(413)+ })++ it('rejects a body past the 24MiB ceiling', async () => {+ const response = await postMessage({ content: 'x'.repeat(25 * MIB), attachments: [] })+ expect(response.status).toBe(413)+ })++ it('does not credit an attachment that only claims to be an image', async () => {+ // Same byte count as the accepted single-image case, but the payload is not+ // a real PNG, so it must be charged to the non-image budget.+ const body = JSON.stringify({+ content: 'look',+ attachments: [+ {+ id: 'a1',+ kind: 'image',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: Buffer.alloc(5 * MIB, 0x41).toString('base64'),+ },+ ],+ })+ const response = await post(MESSAGE_PATH, body)+ expect(response.status).toBe(413)+ })++ it('does not credit base64 whose padding carries non-zero unused bits', async () => {+ const canonical = pngBase64(5 * MIB)+ const nonCanonical = withNonCanonicalTailBits(canonical)+ // Sanity: permissive decoding still yields the same bytes, so the only+ // thing that can reject this payload is the canonical-encoding rule.+ expect(Buffer.from(nonCanonical, 'base64').length).toBe(Buffer.from(canonical, 'base64').length)+ // Without the rule this body would be accepted (base64 ~7MiB minus the+ // credited image leaves ~1MiB of content), so 413 proves no credit.+ const response = await postMessage({+ content: 'x'.repeat(MIB),+ attachments: [+ {+ id: 'a1',+ kind: 'image',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: nonCanonical,+ },+ ],+ })+ expect(response.status).toBe(413)+ })++ it('keeps the 6MiB parser on every other POST route', async () => {+ const response = await post(+ '/api/v1/rpc/hosts/chatllm/wake',+ JSON.stringify({ a: 'x'.repeat(7 * MIB) })+ )+ expect(response.status).toBe(413)+ })++ it('leaves the sandbox-ui view proxy parser-free so its stream is not drained', async () => {+ // A JSON parser on this path would answer 413 for any body over its limit,+ // because parsing has to consume the stream http-proxy needs to forward.+ // The route answers its cookie check first, so the observable proof is a+ // non-413 outcome while the request body is still unread.+ const abortController = new AbortController()+ const chunk = new Uint8Array(64 * 1024).fill(0x41)+ let sent = 0+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ if (sent >= 8 * MIB) return // hold the request open; never finish it+ sent += chunk.length+ controller.enqueue(chunk)+ },+ })+ try {+ const response = await fetch(`${baseUrl}/api/v1/sandbox-ui/ns/recipe/view/index.html`, {+ method: 'POST',+ headers: { 'content-type': 'text/plain' },+ body,+ duplex: 'half',+ signal: abortController.signal,+ } as RequestInit & { duplex: 'half' })+ expect(response.status).not.toBe(413)+ expect(response.status).toBe(401)+ } finally {+ abortController.abort()+ }+ })+})diff --git a/rpc-proxy/src/app.ts b/rpc-proxy/src/app.tsindex 5cb5bf351..dc3e804f1 100644--- a/rpc-proxy/src/app.ts+++ b/rpc-proxy/src/app.ts@@ -11,6 +11,131 @@ import { createRpcHostStatusStreamRouter } from './routes/rpcHostStatusStream.jsimport { createSandboxUiSessionRouter } from './routes/sandboxUi.js'import { isUpstreamTimeoutError } from './services/wakeAndHold.js'+/**+ * Body budgets for chat payloads carrying base64 image attachments.+ *+ * The interoperable budget is 10MiB per image, at most 3 images (15MiB of image+ * bytes). mcp-host holds its own copy of this policy: the two services share no+ * package (see routes/rpc.ts on SESSIONS_LIMIT_CAP), so each names its own and+ * the two edits must land together.+ *+ * Two ceilings are enforced here:+ * - MAX_CHAT_BODY_BYTES bounds the raw JSON body on the message route. 10MiB+ * encodes to ~13.3MiB of base64, so a 10MiB image plus a 5MiB image (the+ * largest combination the 15MiB total allows) needs ~21MiB plus the+ * envelope.+ * - MAX_NON_IMAGE_BODY_BYTES bounds the same body MINUS the base64 of images+ * counting against the documented budget. Without that subtraction the+ * attachment budget would silently become a general 24MiB text budget.+ */+const MAX_CHAT_BODY_BYTES = 24 * 1024 * 1024+const MAX_NON_IMAGE_BODY_BYTES = 6 * 1024 * 1024+const MAX_CHAT_IMAGES = 3+const MAX_IMAGE_DECODED_BYTES = 10 * 1024 * 1024+const MAX_IMAGE_DECODED_BYTES_TOTAL = 15 * 1024 * 1024+const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+const JPEG_SIGNATURE = Buffer.from([0xff, 0xd8, 0xff])++/** Base64 alphabet value of one character, or null when it is not a base64 char. */+function base64SextetValue(char: string): number | null {+ const code = char.charCodeAt(0)+ if (code >= 0x41 && code <= 0x5a) return code - 0x41+ if (code >= 0x61 && code <= 0x7a) return code - 0x61 + 26+ if (code >= 0x30 && code <= 0x39) return code - 0x30 + 52+ if (code === 0x2b) return 62+ if (code === 0x2f) return 63+ return null+}++/**+ * Decoded byte length of a base64 payload, or null when it is not canonical.+ *+ * '=' padding makes the final group carry fewer bits than it encodes, so the+ * unused low bits of that group's last sextet must be zero (RFC 4648 §3.5). A+ * payload padding a non-zero tail still decodes in a permissive decoder, but it+ * is not the canonical encoding of its bytes: accepting it would let a caller+ * park arbitrary unused bytes inside the base64 length that the body budget is+ * asked to credit.+ */+function decodedBase64Bytes(dataBase64: string): number | null {+ if (dataBase64.length === 0 || dataBase64.length % 4 !== 0) return null+ if (!BASE64_RE.test(dataBase64)) return null+ const padding = dataBase64.endsWith('==') ? 2 : dataBase64.endsWith('=') ? 1 : 0+ if (padding > 0) {+ const lastSextet = base64SextetValue(dataBase64[dataBase64.length - 1 - padding] ?? '')+ if (lastSextet === null) return null+ if (padding === 1 && (lastSextet & 0b11) !== 0) return null+ if (padding === 2 && (lastSextet & 0b1111) !== 0) return null+ }+ // A 4-char group decodes to 3 bytes, the pad chars each drop one byte.+ return (dataBase64.length / 4) * 3 - padding+}++/**+ * Byte length of the base64 that counts against the documented image budget.+ * Only attachments with the exact wire shape the composer produces qualify:+ * `kind: 'image'`, `encoding: 'base64'`, a PNG/JPEG MIME type, canonical+ * base64 whose leading bytes are that image's signature, and at most 10MiB+ * decoded each within a 3-image / 15MiB total budget. Anything else is charged+ * to the non-image budget, so a claim cannot be smuggled through by mislabelling+ * a payload.+ */+function budgetedImageBase64Length(body: unknown): number {+ if (!body || typeof body !== 'object' || Array.isArray(body)) return 0+ const attachments = (body as { attachments?: unknown }).attachments+ if (!Array.isArray(attachments)) return 0++ let credited = 0+ let decodedTotal = 0+ let counted = 0+ for (const attachment of attachments) {+ if (counted >= MAX_CHAT_IMAGES) break+ if (!attachment || typeof attachment !== 'object') continue+ const candidate = attachment as {+ kind?: unknown+ encoding?: unknown+ mimeType?: unknown+ dataBase64?: unknown+ }+ if (candidate.kind !== 'image' || candidate.encoding !== 'base64') continue+ const mimeType = typeof candidate.mimeType === 'string' ? candidate.mimeType : ''+ if (mimeType !== 'image/png' && mimeType !== 'image/jpeg') continue+ const dataBase64 = typeof candidate.dataBase64 === 'string' ? candidate.dataBase64 : ''+ const decoded = decodedBase64Bytes(dataBase64)+ if (decoded === null || decoded <= 0 || decoded > MAX_IMAGE_DECODED_BYTES) continue+ if (decodedTotal + decoded > MAX_IMAGE_DECODED_BYTES_TOTAL) continue+ const signature = Buffer.from(dataBase64.slice(0, 16), 'base64')+ const matchesSignature =+ mimeType === 'image/png'+ ? signature.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)+ : signature.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)+ if (!matchesSignature) continue+ credited += dataBase64.length+ decodedTotal += decoded+ counted += 1+ }+ return credited+}++function chatBodyExceedsNonImageBudget(rawBodyBytes: number, body: unknown): boolean {+ return rawBodyBytes - budgetedImageBase64Length(body) > MAX_NON_IMAGE_BODY_BYTES+}++/**+ * body-parser flags a request whose declared/streamed body crossed the parser's+ * `limit` with `type: 'entity.too.large'`. The terminal error handler below+ * would otherwise report it as a 500, which reads like a server fault for what+ * is a client-sized payload; mcp-host answers the same condition with 413.+ */+function isEntityTooLargeError(error: unknown): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ (error as { type?: unknown }).type === 'entity.too.large'+ )+}+export function createApp() {const app = express()@@ -25,11 +150,34 @@ export function createApp() {// recipe's upstream via http-proxy — running body-parser there would drain// the stream, so the proxied request hangs waiting for a body that never// arrives. Skip JSON parsing for that path; every other route still needs it.+ //+ // `POST /api/v1/rpc/hosts/:hostRef/messages` is the one route that carries+ // image attachments, so it alone gets the larger byte ceiling; the rest keep+ // the original 6MiB. The larger ceiling is not a general text allowance: the+ // verifier below subtracts only the base64 of images that validly count+ // against the documented attachment budget.+ const CHAT_MESSAGE_POST_PATH = /^\/api\/v1\/rpc\/hosts\/[^/]+\/messages\/?$/const jsonParser = express.json({ limit: '6mb' })+ const chatJsonParser = express.json({+ limit: MAX_CHAT_BODY_BYTES,+ verify: (req, _res, buffer) => {+ ;(req as Request & { rawBodyBytes?: number }).rawBodyBytes = buffer.length+ },+ })const VIEW_PROXY_PATH = /^\/api\/v1\/sandbox-ui\/[^/]+\/[^/]+\/view\//app.use((req, res, next) => {if (VIEW_PROXY_PATH.test(req.path)) return next()- jsonParser(req, res, next)+ const isChatMessagePost = req.method === 'POST' && CHAT_MESSAGE_POST_PATH.test(req.path)+ const parser = isChatMessagePost ? chatJsonParser : jsonParser+ parser(req, res, error => {+ if (error || !isChatMessagePost) return next(error)+ const rawBodyBytes = (req as Request & { rawBodyBytes?: number }).rawBodyBytes+ if (rawBodyBytes !== undefined && chatBodyExceedsNonImageBudget(rawBodyBytes, req.body)) {+ res.status(413).json({ error: 'Payload Too Large' })+ return+ }+ next()+ })})app.use(createHealthRouter())@@ -54,6 +202,11 @@ export function createApp() {return}+ if (isEntityTooLargeError(err)) {+ res.status(413).json({ error: 'Payload Too Large' })+ return+ }+res.status(500).json({error: 'Internal Server Error',message: err instanceof Error ? err.message : 'Unknown error',diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.shindex d63a10258..19a1b6d10 100755--- a/scripts/tests/test-codex-subscription-t0.sh+++ b/scripts/tests/test-codex-subscription-t0.sh@@ -248,6 +248,7 @@ run_group "codex-llm-proxy" "codex-llm-proxy" \"test/server.security.test.ts"run_group "mcp-host" "mcp-host" \+ "src/__tests__/bodylimits.test.ts" \"src/capabilities/toolCatalogTools.test.ts" \"src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts" \"src/core/orchestration/__tests__/toolUseLoop.spillover.test.ts" \@@ -277,6 +278,9 @@ run_group "mcp-host" "mcp-host" \"src/pluginWorkloadSdk/server/index.test.ts" \"src/core/adapters/__tests__/llmPortAdapter.test.ts"+run_group "rpc-proxy-image-budgets" "rpc-proxy" \+ "src/__tests__/bodylimits.test.ts"+run_group "host-context-controller" "host-context-controller" \"src/codexExecutionProjection.test.ts" \"src/hostReconciler.codexScopeProvenance.test.ts" \@@ -319,14 +323,16 @@ elseelsepass "desktop-app verify:electron"run_group "desktop-app" "desktop-app" \+ "src/__tests__/devIsolation.test.ts" \+ "ui/src/components/agents/__tests__/ComposerPanel.test.tsx" \"ui/src/components/agents/__tests__/ModelSelector.test.tsx" \"ui/src/hooks/__tests__/useHostModels.test.tsx" \"ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsx"fifi-if [[ "${GROUPS_RUN}" -ne 11 ]]; then- fail "expected all 11 T0 groups, ran ${GROUPS_RUN}"+if [[ "${GROUPS_RUN}" -ne 12 ]]; then+ fail "expected all 12 T0 groups, ran ${GROUPS_RUN}"fiif [[ "${FAIL}" -ne 0 ]]; thendiff --git a/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.json b/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.jsonindex 84d2863bc..ac8e5782a 100644--- a/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.json+++ b/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.json@@ -41,6 +41,7 @@"oauthScopes": ["openid", "profile", "email", "offline_access"],"limits": {"maxRequestBodyBytes": 1048576,+ "maxVisualRequestBodyBytes": 25165824,"maxMessages": 128,"maxToolCalls": 32,"maxOutputTokens": 16384,@@ -84,10 +85,10 @@"validation": "container-framing-and-dimensions","limits": {"maxImages": 3,- "maxImageBytes": 524288,- "maxTotalImageBytes": 655360,+ "maxImageBytes": 10485760,+ "maxTotalImageBytes": 15728640,"maxImageDimension": 8192,- "maxImagePixels": 16777216+ "maxImagePixels": 64000000}}}diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.jsonindex bd211be57..294dde8e7 100644--- a/tests/e2e/fixtures/package-lock.json+++ b/tests/e2e/fixtures/package-lock.json@@ -1,12 +1,12 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.80",+ "version": "1.0.81","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@clerum/e2e-test-fixtures",- "version": "1.0.80",+ "version": "1.0.81","dependencies": {"@kubernetes/client-node": "^1.0.0"},diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.jsonindex bb4df1519..2e65862dc 100644--- a/tests/e2e/fixtures/package.json+++ b/tests/e2e/fixtures/package.json@@ -1,6 +1,6 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.80",+ "version": "1.0.81","description": "E2E test fixtures and utilities for Clerum testing","type": "module","main": "index.ts",diff --git a/tests/e2e/integration/codex-subscription-contract-freeze.test.ts b/tests/e2e/integration/codex-subscription-contract-freeze.test.tsindex 496c735e0..6e60ca16a 100644--- a/tests/e2e/integration/codex-subscription-contract-freeze.test.ts+++ b/tests/e2e/integration/codex-subscription-contract-freeze.test.ts@@ -38,6 +38,7 @@ const REQUIRED_OPERATIONS = [const REQUIRED_LIMIT_KEYS = ['maxRequestBodyBytes',+ 'maxVisualRequestBodyBytes','maxMessages','maxToolCalls','maxOutputTokens',@@ -176,6 +177,7 @@ describe('codex-subscription contract freeze', () => {expect(limits).not.toHaveProperty('maxTools')expect(limits?.maxToolCalls).toBe(32)expect(limits?.maxRequestBodyBytes).toBe(1048576)+ expect(limits?.maxVisualRequestBodyBytes).toBe(25165824)const errors = contract.errorTaxonomyexpect(Array.isArray(errors) && (errors as unknown[]).length > 0).toBe(true)diff --git a/tests/e2e/package-lock.json b/tests/e2e/package-lock.jsonindex 35fedd54d..ea0cfa63e 100644--- a/tests/e2e/package-lock.json+++ b/tests/e2e/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-e2e-tests",- "version": "0.1.84",+ "version": "0.1.85","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-e2e-tests",- "version": "0.1.84",+ "version": "0.1.85","devDependencies": {"@types/jsonwebtoken": "^9.0.10","@types/node": "^22.0.0",diff --git a/tests/e2e/package.json b/tests/e2e/package.jsonindex 5291367a7..81bd1e857 100644--- a/tests/e2e/package.json+++ b/tests/e2e/package.json@@ -1,6 +1,6 @@{"name": "clerum-e2e-tests",- "version": "0.1.84",+ "version": "0.1.85","private": true,"type": "module","scripts": {