Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/harness-portability.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Additional harnesses default to `--research-mode skill --skill-loading file --wo

Only explicit provider definitions enter the OpenCode configuration. Project configuration, plugins, MCP, title models and child agents are disabled for this execution path. Claude disables project settings, hooks, plugins and child tools. The host points both agents to the identical frozen Skill file and generated command help. It does not translate mathematical methods into a separate backend-specific prompt library.

Native credentials enter an execution-only environment overlay and are excluded from host Lean environment records. Standard Anthropic/OpenAI credential names are supported. OpenCode also receives environment variables explicitly referenced by its selected provider's `{env:NAME}` fields; non-secret referenced values participate in the frozen configuration digest. API key rotation does not change that digest. Provider `{file:...}` interpolation and references to runtime-overridden environment variables are explicitly unsupported; use literal configuration or an explicit provider environment reference.
Native credentials enter an execution-only environment overlay and are excluded from host Lean environment records. For non-sealed Claude Code and OpenCode research sessions the provider key itself stays in the host process: `src/runtime/researchCredentialRelay.ts` starts a loopback relay that holds the key, and the sandboxed client receives only that relay's URL and a disposable capability (`ANTHROPIC_API_KEY`/`ANTHROPIC_BASE_URL` for Claude Code, a rewritten provider `baseURL`/`apiKey` for OpenCode). Credential variables, and any other variable carrying the key, are removed from the sandbox environment. Claude subscription OAuth (`CLAUDE_CODE_OAUTH_TOKEN` alone) and OpenCode providers outside `@ai-sdk/anthropic`, `@ai-sdk/openai` and `@ai-sdk/openai-compatible` fail closed instead of projecting a host key. Standard Anthropic/OpenAI credential names are supported. OpenCode also receives environment variables explicitly referenced by its selected provider's `{env:NAME}` fields; non-secret referenced values participate in the frozen configuration digest. API key rotation does not change that digest. Provider `{file:...}` interpolation and references to runtime-overridden environment variables are explicitly unsupported; use literal configuration or an explicit provider environment reference.

## Resume and isolation

Expand Down
11 changes: 9 additions & 2 deletions src/runtime/claudeCodeSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { MathAgentOptions, MathAgentSession } from './agentSession';
import { safeHttpStatusCode, type MathAgentFailureDiagnostic } from './failureDiagnostic';
import { prepareHarnessProcess } from './harnessProcess';
import { planMathAgentSession } from './agentSessionPlan';
import { prepareClaudeResearchRelay } from './researchCredentialRelay';
import { prepareSealedHarness, sealedRoleText } from './sealedHarness';

type Json = Record<string, unknown>;
Expand Down Expand Up @@ -96,6 +97,9 @@ export async function createClaudeCodeMathSession(options: MathAgentOptions): Pr
const threadId = options.threadId ?? crypto.randomUUID();
const temporary = path.join(options.profile, 'runtime-tmp');
if (!sealed) fs.mkdirSync(temporary, { recursive: true, mode: 0o700 });
// The Bash tool and /proc/$PPID/environ see only a loopback capability; the provider key stays on the host.
const credentialRelay = sealed ? undefined : await prepareClaudeResearchRelay(options.environment ?? process.env,
options.model, options.signal);
const instructions = (sealed ? sealedRoleText(options.instructions, options) : options.instructions) + (options.skills?.length ? '\n\nPinned research skills (read each file before researching):\n' +
options.skills.map(skill => `${skill.name}: ${JSON.stringify(skill.path)}; directory SHA256 ${skill.digest}`).join('\n') : '');
const args = ['--print', '--input-format', 'text', '--output-format', 'stream-json', '--verbose',
Expand All @@ -119,7 +123,10 @@ export async function createClaudeCodeMathSession(options: MathAgentOptions): Pr
if (owned) await (closing ??= closeMathProcess(owned));
};
const interrupt = async () => { active?.interrupt(); await stop(); };
const close = async () => { closed = true; try { await interrupt(); } finally { await sealed?.close(); } };
const close = async () => {
closed = true;
try { await interrupt(); } finally { try { await sealed?.close(); } finally { await credentialRelay?.close(); } }
};
const abort = () => { void interrupt(); };
options.signal?.addEventListener('abort', abort);

Expand All @@ -140,7 +147,7 @@ export async function createClaudeCodeMathSession(options: MathAgentOptions): Pr
if (child) { await stop(); const receipt = await confirmMathProcessStopped(child);
if (receipt.status !== 'stopped') throw new Error('math_claude_writer_stop_unconfirmed'); }
lastError = undefined; diagnostic = undefined; lastInputTokens = undefined; completedResponse = undefined; closing = undefined;
const invocation = sealed ? sealed.launch([...args, resume ? '--resume' : '--session-id', threadId]) : prepareHarnessProcess({ ...options, environment: { ...(options.environment ?? process.env),
const invocation = sealed ? sealed.launch([...args, resume ? '--resume' : '--session-id', threadId]) : prepareHarnessProcess({ ...options, environment: { ...(credentialRelay?.environment ?? options.environment ?? process.env),
CLAUDE_CONFIG_DIR: options.profile, TMPDIR: temporary, TMP: temporary, TEMP: temporary,
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_AUTOUPDATER: '1', DISABLE_TELEMETRY: '1',
CLAUDE_CODE_SIMPLE: '1', CLAUDE_CODE_SAFE_MODE: '1' } }, options.executable,
Expand Down
72 changes: 64 additions & 8 deletions src/runtime/formalizationRelay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,14 @@ export type NativeRelayProtocol = Readonly<{
route: string; routes?: readonly string[]; authHeader?: 'x-api-key';
upstreamAuthHeader?: 'authorization' | 'x-api-key';
headers?: Readonly<Record<string, string>>;
/** Upstream endpoint per admitted route; unlisted routes use `endpoint`. */
routeEndpoints?: Readonly<Record<string, string>>;
/** Lower-case request headers copied upstream after validation; never credentials or transport headers. */
forwardHeaders?: readonly string[];
/** Return bounded, redacted JSON provider errors so the native client keeps its own diagnostics. */
forwardUpstreamErrors?: boolean;
/** Request body cap; long native research conversations exceed the 8 MiB host-role default. */
maxRequestBytes?: number;
admit: (body: Record<string, unknown>, route: string) => Record<string, unknown>;
observe: (streaming: boolean) => ReturnType<typeof responseUsageObserver>;
}>;
Expand Down Expand Up @@ -297,17 +305,17 @@ function errorResponse(response: ServerResponse, status: number, code: string):
response.end(JSON.stringify({ error: { type: 'formalization_relay_error', code, message: code } }));
}

async function readRequest(request: IncomingMessage): Promise<Record<string, unknown>> {
async function readRequest(request: IncomingMessage, limit = MAX_REQUEST_BYTES): Promise<Record<string, unknown>> {
if (request.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json')
throw new RelayError(415, 'expected_json_request');
if (request.headers['content-encoding'] && request.headers['content-encoding'] !== 'identity')
throw new RelayError(415, 'unsupported_content_encoding');
const length = request.headers['content-length'];
if (length && (!/^\d+$/u.test(length) || Number(length) > MAX_REQUEST_BYTES)) throw new RelayError(413, 'request_too_large');
if (length && (!/^\d+$/u.test(length) || Number(length) > limit)) throw new RelayError(413, 'request_too_large');
const chunks: Buffer[] = []; let bytes = 0;
for await (const chunk of request) {
const buffer = Buffer.from(chunk); bytes += buffer.length;
if (bytes > MAX_REQUEST_BYTES) throw new RelayError(413, 'request_too_large');
if (bytes > limit) throw new RelayError(413, 'request_too_large');
chunks.push(buffer);
}
try {
Expand Down Expand Up @@ -336,6 +344,51 @@ function redactor(secret: string) {
};
}

const FORWARDABLE_HEADER = /^(?:anthropic-(?:version|beta)|openai-beta)$/u;
const MAX_FORWARDED_ERROR_BYTES = 64 * 1024;

function forwardedHeaders(request: IncomingMessage, names: readonly string[] = []): Record<string, string> {
const headers: Record<string, string> = {};
for (const name of names) {
if (!FORWARDABLE_HEADER.test(name)) throw new RelayError(500, 'relay_header_policy_invalid');
const value = request.headers[name];
if (value === undefined) continue;
if (typeof value !== 'string' || value.length > 4096 || !/^[\x20-\x7e]*$/u.test(value))
throw new RelayError(400, 'invalid_forwarded_header');
headers[name] = value;
}
return headers;
}

/** Forward one bounded JSON error body; anything else falls back to the relay's own error. */
async function forwardUpstreamError(upstream: Response, response: ServerResponse, status: number, key: string,
signal: AbortSignal): Promise<boolean> {
const contentType = upstream.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
if (contentType !== 'application/json' || !upstream.body) return false;
const reader = upstream.body.getReader(), chunks: Uint8Array[] = [];
let bytes = 0;
try {
for (;;) {
const chunk = await reader.read();
signal.throwIfAborted();
if (chunk.done) break;
bytes += chunk.value.byteLength;
if (bytes > MAX_FORWARDED_ERROR_BYTES) return false;
chunks.push(chunk.value);
}
} finally { await reader.cancel().catch(() => {}); }
const filter = redactor(key), body = Buffer.concat([...filter(Buffer.concat(chunks)), ...filter(undefined)]);
try { JSON.parse(body.toString('utf8')); } catch { return false; }
if (response.destroyed || response.headersSent) return true;
const retry = ['retry-after', 'retry-after-ms', 'x-should-retry'].flatMap(name => {
const value = upstream.headers.get(name);
return value && value.length <= 64 && /^[\x20-\x7e]*$/u.test(value) ? [[name, value]] : [];
});
response.writeHead(status, { ...Object.fromEntries(retry), 'Content-Type': 'application/json', 'Cache-Control': 'no-store', Connection: 'close' });
response.end(body);
return true;
}

/**
* Host-only credential relay for one isolated formalization role. It exposes a Unix HTTP
* socket, never arbitrary networking. The trusted sandbox helper must set Host to httpHost.
Expand Down Expand Up @@ -442,7 +495,7 @@ export async function startFormalizationRelay(input: {
idleTimer.unref();
};
try {
let body = await readRequest(request);
let body = await readRequest(request, input.native?.maxRequestBytes);
if (input.native) body = input.native.admit(body, request.url!);
else admitResponsesRequest(body, input.model, input.effort, input.outputSchema);
controller.signal.throwIfAborted();
Expand All @@ -453,21 +506,24 @@ export async function startFormalizationRelay(input: {
admission = input.requestGate?.({ requestId: randomUUID(), source: input.native ? 'native-model-relay' : 'responses-relay',
...(nativeThread ? { threadId: nativeThread } : {}) });
if (admission?.allowed === false) throw new RelayError(403, admission.reason);
// Never copy caller headers, URL components, cookies or proxy settings upstream.
// Copy no caller URL components, cookies, proxy settings or headers beyond the protocol's validated list.
// Bun's implicit fetch socket timeout must not impose a model deadline.
const upstreamInit: RequestInit & { timeout: false } = {
method: 'POST', redirect: 'error', signal: controller.signal, timeout: false,
headers: { ...((input.native?.upstreamAuthHeader ?? input.native?.authHeader) === 'x-api-key' ? { 'x-api-key': key } : { Authorization: 'Bearer ' + key }),
headers: { ...forwardedHeaders(request, input.native?.forwardHeaders),
...((input.native?.upstreamAuthHeader ?? input.native?.authHeader) === 'x-api-key' ? { 'x-api-key': key } : { Authorization: 'Bearer ' + key }),
...input.native?.headers, 'Content-Type': 'application/json',
Accept: body.stream === true ? 'text/event-stream' : 'application/json' }, body: JSON.stringify(body) };
upstreamAttempted = true;
renewIdleTimeout();
const upstream = await globalThis.fetch(profile.endpoint, upstreamInit);
const upstream = await globalThis.fetch(input.native?.routeEndpoints?.[request.url!] ?? profile.endpoint, upstreamInit);
controller.signal.throwIfAborted();
if (!upstream.ok) {
failure = 'upstream-http-error';
const status = upstream.status >= 400 && upstream.status <= 599 ? upstream.status : 502;
if (input.native?.forwardUpstreamErrors && await forwardUpstreamError(upstream, response, status, key, controller.signal)) return;
void upstream.body?.cancel().catch(() => {});
throw new RelayError(upstream.status >= 400 && upstream.status <= 599 ? upstream.status : 502, 'upstream_request_failed');
throw new RelayError(status, 'upstream_request_failed');
}
const contentType = upstream.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
if (!upstream.body || !['application/json', 'text/event-stream'].includes(contentType ?? '') ||
Expand Down
28 changes: 21 additions & 7 deletions src/runtime/openCodeSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { scheduleMathTimeout } from '../math/mathTimers';
import { assertMathAgentSkillsCurrent } from './agentSkills';
import type { MathAgentOptions, MathAgentSession } from './agentSession';
import { prepareHarnessProcess } from './harnessProcess';
import { prepareOpenCodeResearchRelay } from './researchCredentialRelay';
import { planMathAgentSession } from './agentSessionPlan';
import { safeHttpStatusCode, type MathAgentFailureDiagnostic } from './failureDiagnostic';
import { prepareSealedHarness, sealedControlFetch, sealedOpenCodeProvider, sealedRoleText } from './sealedHarness';
Expand Down Expand Up @@ -47,7 +48,11 @@ export async function createOpenCodeMathSession(options: MathAgentOptions): Prom
question: 'deny', skill: 'deny', doom_loop: 'deny' };
const sealedProvider = options.readIsolation ? sealedOpenCodeProvider(options) : undefined;
const instructions = options.readIsolation ? sealedRoleText(options.instructions, options) : options.instructions;
const config = { provider: { [providerID]: sealedProvider?.provider ?? provider[providerID] }, enabled_providers: [providerID],
// Research providers reach the model through a host relay; the sandbox gets neither the key nor its variable.
const research = options.readIsolation ? undefined : await prepareOpenCodeResearchRelay({ providerID,
provider: object(provider[providerID]), model: options.model, environment: options.environment ?? {}, signal: options.signal });
const credentialRelay = research?.relay;
const config = { provider: { [providerID]: sealedProvider?.provider ?? research?.provider ?? provider[providerID] }, enabled_providers: [providerID],
model: options.model, small_model: options.model, default_agent: agent, plugin: [], mcp: {},
lsp: false, formatter: false, snapshot: false, autoupdate: false, share: 'disabled', instructions: [],
compaction: { auto: false, prune: false }, permission,
Expand All @@ -57,7 +62,7 @@ export async function createOpenCodeMathSession(options: MathAgentOptions): Prom
const server = net.createServer(); server.once('error', reject);
server.listen(0, '127.0.0.1', () => { const address = server.address();
server.close(error => error ? reject(error) : resolve((address as net.AddressInfo).port)); });
});
}).catch(async error => { await credentialRelay?.close(); throw error; });
const password = randomUUID();
const nativeProfile = options.readIsolation ? '/profile' : profile;
const nativeWorkspace = options.readIsolation ? '/workspace' : workspace;
Expand All @@ -73,10 +78,16 @@ export async function createOpenCodeMathSession(options: MathAgentOptions): Prom
const sealed = options.readIsolation ? await prepareSealedHarness('opencode', options,
{ environment: nativeEnvironment, controlPort: port, openCode: sealedProvider }) : undefined;
const arguments_ = ['serve', '--pure', '--hostname=127.0.0.1', `--port=${port}`];
const launch = sealed ? sealed.launch(arguments_) : prepareHarnessProcess({ ...options, profile, workspace,
environment: { ...options.environment, ...nativeEnvironment } }, options.executable, arguments_);
const child = spawn(launch.command, launch.args, { cwd: workspace, env: launch.env, detached: true,
stdio: ['ignore', 'pipe', 'pipe', ...('inheritedFds' in launch ? launch.inheritedFds ?? [] : [])] });
let started;
try {
const environment = { ...(research?.environment ?? options.environment), ...nativeEnvironment };
credentialRelay?.assertNotProjected(Object.values(environment));
const launch = sealed ? sealed.launch(arguments_) : prepareHarnessProcess({ ...options, profile, workspace, environment },
options.executable, arguments_);
started = { launch, child: spawn(launch.command, launch.args, { cwd: workspace, env: launch.env, detached: true,
stdio: ['ignore', 'pipe', 'pipe', ...('inheritedFds' in launch ? launch.inheritedFds ?? [] : [])] }) };
} catch (error) { await credentialRelay?.close(); throw error; }
const { launch, child } = started;
trackMathProcessSession(child);
const lifetime = new AbortController();
let closing: Promise<void> | undefined, running = false, settled = true, threadId = '';
Expand All @@ -86,7 +97,10 @@ export async function createOpenCodeMathSession(options: MathAgentOptions): Prom
let active: { abort: () => void } | undefined;
const close = () => closing ??= (async () => {
lifetime.abort(); active?.abort();
try { await closeMathProcess(child); } finally { options.signal?.removeEventListener('abort', aborted); await sealed?.close(); }
try { await closeMathProcess(child); } finally {
options.signal?.removeEventListener('abort', aborted);
try { await sealed?.close(); } finally { await credentialRelay?.close(); }
}
})();
const aborted = () => { void close(); };
options.signal?.addEventListener('abort', aborted, { once: true });
Expand Down
Loading
Loading