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
4 changes: 4 additions & 0 deletions apps/web/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ const providerSchema = z.object({
if (provider.harness === 'cli' ? !provider.execution?.cli : provider.execution?.cli || provider.execution?.files ||
provider.execution?.apiKeyEnvironment || provider.execution?.baseUrlEnvironment)
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'CLI launch configuration requires a CLI provider.' });
const research = provider.execution?.cli?.researchProvider;
if (provider.execution?.cli && (research?.apiKeyEnvironment !== (provider.execution.apiKeyEnvironment ?? 'OPENAI_API_KEY') ||
research.baseUrlEnvironment !== (provider.execution.baseUrlEnvironment ?? 'OPENAI_BASE_URL')))
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'CLI providers must declare researchProvider for their key and base URL variables.' });
for (const name of Object.keys(provider.execution?.files ?? {})) if (path.isAbsolute(name) || name.split(/[\\/]/u).some(part => !part || part === '..' || part === '.') || name === 'cli.json')
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'CLI configuration file paths must be relative ordinary files.' });
for (const name of [provider.execution?.apiKeyEnvironment, provider.execution?.baseUrlEnvironment].filter(Boolean))
Expand Down
3 changes: 3 additions & 0 deletions apps/web/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ export function prepareWebNativeProfile(profile: string, provider: WebWorkerProv
if (!actual.inheritEnvironment.includes(key) || !actual.inheritEnvironment.includes(base) ||
Object.hasOwn(actual.environment, key) || Object.hasOwn(actual.environment, base))
throw new Error('web_cli_provider_environment_unbound');
// The BYOK key reaches the native client only through the host research relay.
if (actual.researchProvider?.apiKeyEnvironment !== key || actual.researchProvider.baseUrlEnvironment !== base)
throw new Error('web_cli_research_provider_unbound');
if (!actual.efforts.includes(input.effort)) throw new Error('math_cli_effort_unsupported');
return;
}
Expand Down
9 changes: 9 additions & 0 deletions docs/generic-cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ Configured terminal failure classes are `authentication`, `context`, `rate-limit

`environment` maps explicit native environment values, for example `"HOME": "{profile}/home"`. `inheritEnvironment` lists existing process variables needed by that command, for example an API key or endpoint. CLI-only inherited values are excluded from host Lean environment records. Credentials should enter through `inheritEnvironment`, not literal config or argv values. Non-secret inherited values participate in the launch identity; recognized credential names may rotate. Runtime-owned environment names are reserved.

Research sessions keep native network access, so the provider key never enters the sandbox. Declare the native client's provider variables with `researchProvider`:

```json
"inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_BASE_URL"],
"researchProvider": { "wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_BASE_URL" }
```

Both names must be listed in `inheritEnvironment` and absent from `environment`. The host keeps the real key in a loopback relay. Inside the sandbox the key variable holds a disposable capability and the base variable holds the relay's `/v1` endpoint. The relay forwards only the wire API's request paths, relative to the base the client was configured with: `/responses`, `/chat/completions`, or Anthropic `/messages` and `/messages/count_tokens` (with or without a leading `/v1`). An unset base variable uses the provider's public endpoint. The upstream base must be HTTPS, or HTTP to a loopback/private host. Inherited variables whose names look like credentials (`API_KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `CREDENTIAL`, `PRIVATE_KEY`) are always removed. If one of them has a value and is not the declared `researchProvider` key, the session fails with `math_cli_provider_relay_unsupported` instead of projecting it. A `sealedRole` provider key is never passed to research sessions. Declare a credential with an unusual name through `researchProvider`, since name matching cannot recognize it.

`configurationFiles` lists existing relative files under the profile whose bytes must remain frozen, such as native settings. The host pins these files, `cli.json`, executable path/bytes and non-secret inherited environment before dispatch, source freezing and resume. Session/cache files can grow. Put every native settings file that affects execution in this list and disable undesired native project/global discovery in the native configuration.

Execution requires Linux bubblewrap. The host root is read-only; the proof worktree and dedicated profile are writable. HOME defaults to the dedicated profile, XDG state stays there, temporary files stay in the worktree, protected roots and host socket directories are masked, and research networking remains available. The host waits for confirmed process shutdown before freezing source. A valid completion file may stop the process early; it is a handoff for independent verification, never proof acceptance.
Expand Down
2 changes: 1 addition & 1 deletion resources/cli-harnesses/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ bun bin/math.ts run --harness cli --harness-profile DEDICATED_PROFILE \
--output RESULT_FILE --build-manifest BUILD_MANIFEST
```

Supply credentials using the names in `inheritEnvironment`. Keep them out of profile files and args. HOME defaults to the dedicated profile. Gemini additionally sets `GEMINI_CLI_HOME` to a private home root; the native CLI appends `.gemini`. Qwen sets `QWEN_HOME` to a private settings/session directory. Explicit system settings paths prevent fallback to host system paths; Gemini may ignore these profile files when its privileged settings ownership checks fail. Do not interpret that as those files taking effect.
Supply credentials using the names in `inheritEnvironment`. Keep them out of profile files and args. Qwen and Aider declare `researchProvider`, so the host relay holds the OpenAI-compatible key and the native process sees only a disposable capability. Aider's profile relays only its OpenAI-compatible provider; it no longer inherits `ANTHROPIC_API_KEY`. Gemini's native API has no host relay yet: a research session with `GEMINI_API_KEY` set fails with `math_cli_provider_relay_unsupported` rather than exposing the key. HOME defaults to the dedicated profile. Gemini additionally sets `GEMINI_CLI_HOME` to a private home root; the native CLI appends `.gemini`. Qwen sets `QWEN_HOME` to a private settings/session directory. Explicit system settings paths prevent fallback to host system paths; Gemini may ignore these profile files when its privileged settings ownership checks fail. Do not interpret that as those files taking effect.

Gemini and Qwen retain `usage.completeness: "partial"`: the local probes establish event mapping and continuity, not complete accounting for every provider/tool/background combination. With a finite token budget the host stops subsequent dispatches after an incomplete turn. Cached counters are already part of input totals. Gemini headless resume was measured at 40/5 then 40/5 tokens; Qwen at 40/5 then 80/10. Neither preset claims a latest individual request size.

Expand Down
3 changes: 2 additions & 1 deletion resources/cli-harnesses/aider/cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"output": {"format": "text"},
"efforts": ["none"],
"environment": {"NO_COLOR": "1"},
"inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_API_BASE", "ANTHROPIC_API_KEY"],
"inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_API_BASE"],
"researchProvider": {"wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_API_BASE"},
"configurationFiles": ["aider.conf.yml", "empty.env"]
}
1 change: 1 addition & 0 deletions resources/cli-harnesses/qwen/cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,6 @@
"NO_COLOR": "1"
},
"inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_BASE_URL"],
"researchProvider": {"wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_BASE_URL"},
"configurationFiles": ["qwen-home/settings.json", "system-defaults.json", "system-settings.json"]
}
8 changes: 8 additions & 0 deletions src/runtime/cliConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ export const cliConfigurationSchema = z.object({
client: z.object({ baseUrlEnvironment: environmentName, apiKeyEnvironment: environmentName }).strict(),
profileFiles: z.record(argument).default({}),
runtime: sealedRuntime.optional() }).strict().optional(),
/** Research sessions: the native client's provider variables. The host relay keeps the real key. */
researchProvider: z.object({ wireApi: sealedRoleProviderSchema.shape.wireApi,
apiKeyEnvironment: environmentName, baseUrlEnvironment: environmentName }).strict().optional(),
}).strict();

export type CliConfiguration = z.infer<typeof cliConfigurationSchema>;
Expand Down Expand Up @@ -94,6 +97,11 @@ export function readCliConfiguration(profile: string): CliConfiguration {
throw new Error('math_cli_runtime_environment_reserved');
if (config.inheritEnvironment.some(name => /^(?:HOME|PATH|ELAN_HOME|LAKE_HOME|LEAN_.+)$/u.test(name)))
throw new Error('math_cli_runtime_environment_reserved');
const research = config.researchProvider;
if (research && (research.apiKeyEnvironment === research.baseUrlEnvironment ||
[research.apiKeyEnvironment, research.baseUrlEnvironment].some(name =>
!config.inheritEnvironment.includes(name) || Object.hasOwn(config.environment, name))))
throw new Error('math_cli_research_provider_binding_invalid');
for (const name of config.configurationFiles) {
const selected = path.resolve(profile, name);
if (path.isAbsolute(name) || !isMathPathWithin(profile, selected) || selected === profile ||
Expand Down
9 changes: 7 additions & 2 deletions src/runtime/cliSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { cliFieldMatches, cliFieldValue, expandCliTemplate, readCliConfiguration
import type { MathAgentFailureDiagnostic } from './failureDiagnostic';
import { prepareHarnessProcess } from './harnessProcess';
import { planMathAgentSession } from './agentSessionPlan';
import { prepareCliResearchRelay } from './researchCredentialRelay';
import { prepareSealedHarness, sealedRolePath, sealedRoleText } from './sealedHarness';

type Json = Record<string, unknown>;
Expand Down Expand Up @@ -49,6 +50,9 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
workspace: '/workspace', prompt: '', promptFile: '', sessionId: threadId, turnId: '' };
const sealed = options.readIsolation ? await prepareSealedHarness('cli', options, { environment:
Object.fromEntries(Object.entries(configuration.environment).map(([name, value]) => [name, expandCliTemplate(value, sealedValues)])) }) : undefined;
// Research keeps native network, so inherited provider keys stay in a host relay.
const research = sealed ? undefined : await prepareCliResearchRelay({ configuration,
environment: options.environment ?? process.env, model: options.model, signal: options.signal });
let resume = configuration.session.mode !== 'fresh' && Boolean(options.threadId), closed = false;
let child: ChildProcess | undefined, closing: Promise<void> | undefined;
let active: { interrupt: () => void } | undefined;
Expand Down Expand Up @@ -101,9 +105,10 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
? configuration.session.resumeArgs : configuration.session.startArgs;
const arguments_ = [...configuration.args, ...sessionArgs].map(argument => expandCliTemplate(argument, values));
const invocation = sealed ? sealed.launch(arguments_) : prepareHarnessProcess({ ...options, environment: {
...(options.environment ?? process.env), HOME: options.profile,
...research!.environment, HOME: options.profile,
...Object.fromEntries(Object.entries(configuration.environment).map(([key, value]) => [key, expandCliTemplate(value, values)])),
} }, options.executable, arguments_);
research?.relay?.assertNotProjected([...Object.values(invocation.env ?? {}), ...invocation.args]);
isolationReceipt = sealed?.receipt ?? ('isolationReceipt' in invocation ? invocation.isolationReceipt as Json : undefined);
let owned: ChildProcess;
try { owned = child = spawn(invocation.command, invocation.args, { cwd: workspace, env: invocation.env,
Expand Down Expand Up @@ -245,7 +250,7 @@ export async function createCliMathSession(options: MathAgentOptions): Promise<M
},
interrupt,
async close() { closed = true; options.signal?.removeEventListener('abort', abort);
try { await interrupt(); } finally { await sealed?.close(); } },
try { await interrupt(); } finally { try { await sealed?.close(); } finally { await research?.relay?.close(); } } },
async stopForFreeze() {
if (active) return { status: 'unconfirmed', reason: 'turn-not-settled' };
try { await stop(); } catch { return { status: 'unconfirmed', reason: 'shutdown-failed' }; }
Expand Down
40 changes: 40 additions & 0 deletions src/runtime/researchCredentialRelay.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { isIP } from 'node:net';
import { RelayError, responseUsageObserver, startFormalizationRelay,
type FormalizationRelay, type NativeRelayProtocol } from './formalizationRelay';
import type { CliConfiguration } from './cliConfiguration';
import { nativeUsageObserver } from './sealedRoleProtocol';

/* Research sessions keep their native tools and network, but the provider credential stays in
Expand Down Expand Up @@ -155,3 +156,42 @@ export async function prepareOpenCodeResearchRelay(input: { providerID: string;
return { environment: sandbox, relay: custody(relay, credential, sandbox),
provider: { ...provider, npm, options: { ...remaining, baseURL: relay.baseUrl, apiKey: relay.apiKey } } };
}

/** Paths a native client appends to its configured base, per wire API. Anthropic clients differ on
* whether that base already ends in `/v1`, so both relative forms are accepted. */
const cliRelativeRoutes: Record<WireApi, readonly string[]> = {
responses: ['/responses'], 'chat-completions': ['/chat/completions'],
'anthropic-messages': ['/messages', '/messages/count_tokens', '/v1/messages', '/v1/messages/count_tokens']
.flatMap(route => [route, route + '?beta=true']),
};
const cliDefaultBase: Record<WireApi, string> = { responses: 'https://api.openai.com/v1',
'chat-completions': 'https://api.openai.com/v1', 'anthropic-messages': 'https://api.anthropic.com' };

/** Generic CLI research launch. Inherited credentials never enter the sandbox: the declared
* `researchProvider` key is held by a host relay and the client base points at that relay, which
* forwards the client's base-relative path unchanged. Any other inherited credential, or one without
* a declared wire API, fails closed instead of being projected. */
export async function prepareCliResearchRelay(input: { configuration: Pick<CliConfiguration,
'inheritEnvironment' | 'researchProvider' | 'sealedRole'>; environment: NodeJS.ProcessEnv; model: string;
signal?: AbortSignal }): Promise<{ environment: NodeJS.ProcessEnv; relay?: ResearchCredentialRelay }> {
const { configuration } = input, env = input.environment, binding = configuration.researchProvider;
const inherited = configuration.inheritEnvironment.filter(name => secretName.test(name));
const credentialNames = new Set([...inherited, ...(binding ? [binding.apiKeyEnvironment] : []),
// The sealed-role host key is loaded for formalization only; research never receives it.
...(configuration.sealedRole ? [configuration.sealedRole.provider.apiKeyEnvironment] : [])]);
const sandbox: NodeJS.ProcessEnv = { ...env };
for (const name of credentialNames) delete sandbox[name];
if ([...credentialNames].some(name => env[name] && name !== binding?.apiKeyEnvironment &&
configuration.inheritEnvironment.includes(name))) throw new Error('math_cli_provider_relay_unsupported');
const credential = binding && env[binding.apiKeyEnvironment];
if (!binding || !credential) return { environment: sandbox };
for (const [name, value] of Object.entries(sandbox)) if (value?.includes(credential)) delete sandbox[name];
const base = researchUpstreamBase(env[binding.baseUrlEnvironment] || cliDefaultBase[binding.wireApi]);
const routes = Object.fromEntries(cliRelativeRoutes[binding.wireApi].map(route => ['/v1' + route, base + route.replace(/\?.*$/u, '')]));
const relay = await startRelay(researchRelayProtocol({ wireApi: binding.wireApi, routes,
upstreamAuthHeader: binding.wireApi === 'anthropic-messages' ? 'x-api-key' : 'authorization' }), credential, input.model, input.signal);
sandbox[binding.apiKeyEnvironment] = relay.apiKey; sandbox[binding.baseUrlEnvironment] = 'http://' + relay.httpHost + '/v1';
const selected = custody(relay, credential, sandbox);
try { selected.assertNotProjected(Object.values(sandbox)); } catch (error) { await relay.close(); throw error; }
return { environment: sandbox, relay: selected };
}
5 changes: 5 additions & 0 deletions tests/cliConfiguration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ describe('declarative headless CLI configuration', () => {
[{ inheritEnvironment: ['PATH'] }, 'math_cli_runtime_environment_reserved'],
[{ environment: { THEOREMOS_PRIVATE: 'override' } }, 'math_cli_runtime_environment_reserved'],
[{ configurationFiles: ['../outside.json'] }, 'math_cli_configuration_path_invalid'],
[{ researchProvider: { wireApi: 'responses', apiKeyEnvironment: 'KEY', baseUrlEnvironment: 'BASE' } }, 'math_cli_research_provider_binding_invalid'],
[{ inheritEnvironment: ['KEY'], environment: { BASE: 'x' }, researchProvider: { wireApi: 'responses', apiKeyEnvironment: 'KEY',
baseUrlEnvironment: 'BASE' } }, 'math_cli_research_provider_binding_invalid'],
[{ inheritEnvironment: ['KEY'], researchProvider: { wireApi: 'responses', apiKeyEnvironment: 'KEY', baseUrlEnvironment: 'KEY' } },
'math_cli_research_provider_binding_invalid'],
])('rejects an unusable launch contract %j', (overrides, reason) => {
const f = fixture(overrides); expect(() => readCliConfiguration(f.profile)).toThrow(reason);
});
Expand Down
Loading
Loading