The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Add local-sandbox SRT provider with path-UDS Code Mode.
debajyoti-truefoundry3c3ec956baa1
diff --git a/package.json b/package.jsonindex abaf7b96e..5034dbefd 100644--- a/package.json+++ b/package.json@@ -46,7 +46,7 @@"test:store:sqlite": "pnpm --filter @truefoundry/trueforge test:store:sqlite","test:trueforge-ui": "pnpm --filter @truefoundry/trueforge-ui test","test": "pnpm test:harness && pnpm test:trueforge-ui && pnpm test:server && pnpm test:frontend",- "typecheck": "pnpm --filter @truefoundry/trueforge-core typecheck && pnpm --filter @truefoundry/trueforge-ui typecheck && pnpm --filter @truefoundry/trueforge typecheck && pnpm --filter frontend typecheck",+ "typecheck": "pnpm --filter @truefoundry/trueforge-core typecheck && pnpm --filter @truefoundry/trueforge-ui typecheck && pnpm --filter @truefoundry/trueforge typecheck && pnpm --filter frontend typecheck && pnpm --filter @truefoundry/local-sandbox typecheck","version": "node scripts/version.mjs"},"devDependencies": {diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.tsindex 9edf1195b..03be317a9 100644--- a/packages/harness/src/core/index.ts+++ b/packages/harness/src/core/index.ts@@ -137,9 +137,18 @@ export { describeUnknownError, extractErrorLogFields } from './util/errorLogFielexport { PromiseTimeoutError, withTimeout } from './util/promiseUtils';// Sandbox (concrete implementation; provider details exported for composition)+export { CodeModeDispatcher } from './sandbox/codeMode/CodeModeDispatcher';+export type { CodeModeLogger } from './sandbox/codeMode/CodeModeDispatcher';+export type { CodeModeTransport } from './sandbox/codeMode/CodeModeTransport';+export { CodeModeErrorSourceSchema, CodeModeReplySchema, CodeModeRequestSchema } from './sandbox/codeMode/types';+export type { CodeModeErrorSource, CodeModeReply, CodeModeRequest } from './sandbox/codeMode/types';export { DaytonaSandboxProvider } from './sandbox/provider/DaytonaProvider';export type { DaytonaSandboxProviderOptions } from './sandbox/provider/DaytonaProvider';+export { ensureExecSuccess, shellEscape } from './sandbox/provider/Provider';export type {+ ExecErrorResult,+ ExecResult,+ ExecSuccessResult,SandboxBuild,SandboxBuildMetadata,SandboxBuildStatus,@@ -150,7 +159,15 @@ export type {export { TFYSandboxProvider } from './sandbox/provider/TFYSandboxProvider';export { SKILL_DOWNLOAD_TIMEOUT_SECONDS, Sandbox, buildWriteAndRunScriptCommand } from './sandbox/Sandbox';export type { SandboxInfo } from './sandbox/Sandbox';-export { SandboxError, validateNoPathTraversal, validateSandboxOwnedByTenant } from './sandbox/SandboxErrors';+export {+ SandboxError,+ SandboxFileNotFoundError,+ SandboxFileTooLargeError,+ SandboxNotAvailableError,+ SandboxPathIsDirectoryError,+ validateNoPathTraversal,+ validateSandboxOwnedByTenant,+} from './sandbox/SandboxErrors';export { SANDBOX_IMAGE_URI } from './sandbox/sandboxImage';// Skills: the ISkillMounter seam lets hosts plug in their own skill sourcesdiff --git a/packages/harness/src/core/sandbox/Sandbox.ts b/packages/harness/src/core/sandbox/Sandbox.tsindex 58b6a2941..35db68a21 100644--- a/packages/harness/src/core/sandbox/Sandbox.ts+++ b/packages/harness/src/core/sandbox/Sandbox.ts@@ -15,10 +15,11 @@ import {} from '../runtime/DeferredTool';import type { AgentTracing } from '../tracing/AgentTracing';import { extractErrorLogFields } from '../util/errorLogFields';-import { DEFAULT_SANDBOX_NATS_WS_PORT, SANDBOX_FILE_UPLOADS_DIR } from './constants';+import { CodeModeDispatcher } from './codeMode/CodeModeDispatcher';+import type { CodeModeTransport } from './codeMode/CodeModeTransport';+import { SANDBOX_FILE_UPLOADS_DIR } from './constants';import { ensureExecSuccess, shellEscape, type SandboxProvider } from './provider/Provider';import { validateNoPathTraversal, validateSandboxOwnedByTenant } from './SandboxErrors';-import { SandboxNatsBridge } from './SandboxNatsBridge';import { sandboxScripts } from './sandboxScripts.gen';// Import submodules, not the ./skills barrel, to avoid a cycle (the mounters import from Sandbox).import { SKILLS_DIR } from './skills/constants';@@ -133,18 +134,16 @@ function injectTraceContextEnv(): Record<string, string> {/*** Injects environment variables required for mcp_client.py into sandbox_exec arguments.- *- * `natsBridgeSubjectPrefix` MUST be the prefix the gateway-side bridge subscribed to; the- * sandbox script publishes to `<prefix>.mcp` (operation in the payload's `op` field) and only- * this bridge receives them. See SandboxNatsBridge.+ * Transport-specific vars (NATS URL/prefix/timeout) come from `codeModeEnv` via transport.start().*/function injectMCPClientEnv(params: {env?: Record<string, string> | undefined;mcpServers: Record<string, SandboxMcpServerConfig>;execExtraEnv?: Readonly<Record<string, string>> | undefined;- natsBridgeSubjectPrefix?: string | undefined;- natsRequestTimeoutSeconds: number;+ codeModeEnv?: Record<string, string> | undefined;}): Record<string, string> {+ const codeModeEnv = params.codeModeEnv ?? {};+ const hasCodeModeTransport = Object.keys(codeModeEnv).length > 0;return {...(params.execExtraEnv ?? {}),...(params.env ?? {}),@@ -152,13 +151,10 @@ function injectMCPClientEnv(params: {...(Object.keys(params.mcpServers).length > 0 && {TFY_MCP_SERVERS: Buffer.from(JSON.stringify(params.mcpServers)).toString('base64'),}),- ...(params.natsBridgeSubjectPrefix && {- TFY_NATS_URL: `ws://localhost:${String(DEFAULT_SANDBOX_NATS_WS_PORT)}`,- TFY_NATS_SUBJECT_PREFIX: params.natsBridgeSubjectPrefix,- TFY_NATS_REQUEST_TIMEOUT_SECONDS: String(params.natsRequestTimeoutSeconds),- // W3C trace context captured per-exec so each NATS request carries the originating- // Sandbox: exec span as parent. Without this, MCP spans dispatched via the bridge- // inherit whatever ALS context the NATS callback runs under (stale, shared across execs).+ ...codeModeEnv,+ ...(hasCodeModeTransport && {+ // W3C trace context captured per-exec so each Code Mode request carries the originating+ // Sandbox: exec span as parent....injectTraceContextEnv(),}),// Approvals are always enabled: destructive tools cannot run in code mode.@@ -206,7 +202,7 @@ export class Sandbox extends LocalToolMCP {private sandboxInitPromise?: Promise<void> | undefined;private codeExecToolSets: readonly IToolSet[] = [];private readonly fileDownloadEnabled: boolean;- private readonly natsRequestTimeoutSeconds: number;+ private readonly requestTimeoutSeconds: number;private readonly execExtraEnv?: Readonly<Record<string, string>> | undefined;private readonly skillMounter?: ISkillMounter | undefined;private cachedSkillsSection?: string | undefined;@@ -214,7 +210,8 @@ export class Sandbox extends LocalToolMCP {private readonly logger: Logger;// Pre-resolved credential-store file content (null = clear / no git auth).private readonly resolvedGitCredentialsContent: string | null;- private natsBridgePromise?: Promise<SandboxNatsBridge | undefined> | undefined;+ private codeModeDispatcher: CodeModeDispatcher | undefined;+ private codeModeTransport: CodeModeTransport | undefined;private tools = [defineTool({@@ -233,7 +230,7 @@ export class Sandbox extends LocalToolMCP {this.skillMounter = options.skillMounter;this.fileDownloadEnabled = options.fileDownloadEnabled ?? false;const mcpBoundTimeoutMs = options.mcpRequestTimeoutMs + options.mcpConnectTimeoutMs;- this.natsRequestTimeoutSeconds = Math.ceil(mcpBoundTimeoutMs / 1000) + NATS_REQUEST_TIMEOUT_BUFFER_SECONDS;+ this.requestTimeoutSeconds = Math.ceil(mcpBoundTimeoutMs / 1000) + NATS_REQUEST_TIMEOUT_BUFFER_SECONDS;this.execExtraEnv = options.execExtraEnv;// Scripts are internal to Sandbox: the upload paths, env contract, and prompt// text are all hardcoded here, so injecting different content was never a@@ -265,7 +262,12 @@ export class Sandbox extends LocalToolMCP {if (!servers.length) {return;}+ if (this.codeModeDispatcher !== undefined || this.codeModeTransport !== undefined) {+ throw new Error('Code Mode is already configured for this Sandbox');+ }this.codeExecToolSets = servers;+ this.codeModeDispatcher = new CodeModeDispatcher({ toolSets: servers, logger: this.logger });+ this.codeModeTransport = this.provider.createCodeModeTransport();}estimateSkillsTokens(): number {@@ -478,13 +480,12 @@ export class Sandbox extends LocalToolMCP {overrides: { sandboxCreated: sandboxCreatedFlag, sandboxInfo },});}- const bridge = await this.ensureNatsBridgeConnected(sandboxInfo.sandbox_id);+ const codeModeEnv = await this.ensureCodeModeStarted(sandboxInfo.sandbox_id);const mcpClientEnv = injectMCPClientEnv({env: input.env,mcpServers: this.buildMcpServersEnvelope(),execExtraEnv: this.execExtraEnv,- natsBridgeSubjectPrefix: bridge?.subjectPrefix,- natsRequestTimeoutSeconds: this.natsRequestTimeoutSeconds,+ codeModeEnv,});const gitAuthEnv =this.resolvedGitCredentialsContent !== null@@ -622,71 +623,45 @@ export class Sandbox extends LocalToolMCP {}/**- * Lazily connect the sandbox→gateway NATS bridge. Single-flight and idempotent.- * Skipped when there are no MCP servers exposed to code mode (nothing to bridge). Connect- * failures resolve to `undefined` (no NATS env for that exec); mcp_client then errors at call- * time — there is no HTTPS fallback.+ * Lazily start Code Mode transport. Single-flight and idempotent inside the transport.+ * Skipped when code mode was never configured. Connect failures resolve to `undefined`+ * (no Code Mode env for that exec); mcp_client then errors at call time — no HTTPS fallback.*/- private async ensureNatsBridgeConnected(sandboxId: string): Promise<SandboxNatsBridge | undefined> {- // No MCP servers means the bridge has nothing to dispatch to. Avoid the connect cost.- if (this.codeExecToolSets.length === 0) return undefined;- this.natsBridgePromise ??= this.connectNatsBridge(sandboxId).catch((e: unknown) => {- // Connect-level errors (network, timeout, broker not up) are not sticky: a later exec- // may succeed (e.g. after sandbox warmup). Wipe the cached promise so retries happen.- this.logger.error('Sandbox NATS bridge connect failed', {+ private async ensureCodeModeStarted(sandboxId: string): Promise<Record<string, string> | undefined> {+ const dispatcher = this.codeModeDispatcher;+ const transport = this.codeModeTransport;+ if (dispatcher === undefined || transport === undefined) {+ return undefined;+ }+ try {+ const { env } = await transport.start({+ codeModeDispatcher: dispatcher,+ sandboxId,+ requestTimeoutSeconds: this.requestTimeoutSeconds,+ });+ return env;+ } catch (e) {+ // Connect-level errors are not sticky: transport clears its session so a later exec may retry.+ this.logger.error('Code Mode transport start failed', {...extractErrorLogFields(e),sandboxId,});- this.natsBridgePromise = undefined;return undefined;- });- return this.natsBridgePromise;- }-- private async connectNatsBridge(sandboxId: string): Promise<SandboxNatsBridge> {- const wsUrl = await this.provider.getNatsBridgeUrl(sandboxId);- const toolSets = new Map<string, IToolSet>();- for (const server of this.codeExecToolSets) {- toolSets.set(server.name, server);}- const bridge = await SandboxNatsBridge.connect({ url: wsUrl, toolSets, logger: this.logger });- this.logger.info('Sandbox NATS bridge connected', {- sandboxId,- toolSetCount: toolSets.size,- });- this.attachBridgeInvalidationOnClose(bridge, sandboxId);- return bridge;}- private attachBridgeInvalidationOnClose(bridge: SandboxNatsBridge, sandboxId: string): void {- const cachedPromise = this.natsBridgePromise;- // fire and forget- void bridge.whenClosed().then(() => {- if (this.natsBridgePromise === cachedPromise) {- this.natsBridgePromise = undefined;- this.logger.info('Sandbox NATS bridge closed; cache invalidated, next exec will reconnect', { sandboxId });- }- });- }-- // Tears down per-Sandbox resources. Awaits the in-flight connect (if any) and explicitly- // closes the bridge — dropping the field alone would leak the WS socket and live- // subscriptions, and orphan a bridge that finishes connecting after close() returned.+ // Tears down per-Sandbox Code Mode resources. Dispatcher close first (in-flight requests get+ // source: transport), then transport.stop() — always safe whether start succeeded, failed, or never ran.async close(): Promise<void> {- const pendingPromise = this.natsBridgePromise;- this.natsBridgePromise = undefined;- if (!pendingPromise) return;- let bridge: SandboxNatsBridge | undefined;- try {- bridge = await pendingPromise;- } catch {- // Connect-error path already logged inside ensureNatsBridgeConnected's .catch.- }- if (!bridge) return;+ this.codeModeDispatcher?.close();+ this.codeModeDispatcher = undefined;+ const transport = this.codeModeTransport;+ this.codeModeTransport = undefined;+ if (transport === undefined) return;try {- await bridge.close();+ await transport.stop();} catch (e) {- this.logger.warn('Error closing sandbox NATS bridge', extractErrorLogFields(e));+ this.logger.warn('Error stopping Code Mode transport', extractErrorLogFields(e));}}}diff --git a/packages/harness/src/core/sandbox/SandboxNatsBridge.ts b/packages/harness/src/core/sandbox/SandboxNatsBridge.tsdeleted file mode 100644index 0125f5a09..000000000--- a/packages/harness/src/core/sandbox/SandboxNatsBridge.ts+++ /dev/null@@ -1,275 +0,0 @@-import { wsconnect, type Msg, type NatsConnection } from '@nats-io/nats-core';-import { context, defaultTextMapGetter } from '@opentelemetry/api';-import { suppressTracing, unsuppressTracing, W3CTraceContextPropagator } from '@opentelemetry/core';-import { randomUUID } from 'node:crypto';-import type { Logger } from 'winston';-import { WebSocket } from 'ws';-import { McpConnectionError } from '../errors';-import {- isAuthRequired,- isCallToolResponseCreateSubAgent,- isCallToolResponseResult,- type CallToolResolvedResponse,- type IToolSet,- type ListToolsResolvedResponse,-} from '../mcp/IMCPServer';-import { extractErrorLogFields } from '../util/errorLogFields';-import { withTimeout } from '../util/promiseUtils';--// `wsconnect` from @nats-io/nats-core relies on a global WebSocket constructor; in Node we-// provide it from `ws`. Same pattern as `src/services/NatsService.ts`.-Object.assign(global, { WebSocket });--const NATS_CONNECT_TIMEOUT_MS = 10_000;-const NATS_CONNECT_RETRIES = 3;-const NATS_CONNECT_BACKOFF_MS = 250;-// Bound on the graceful drain at teardown; on timeout we fall back to nc.close()-const NATS_DRAIN_TIMEOUT_MS = 5_000;--const SANDBOX_NATS_SUBJECT_ROOT = 'sandbox.bridge';-// Single request/reply subject leaf; the operation is carried in the payload's `op` field so the-// bridge maintains one subscription instead of one per operation.-const SANDBOX_NATS_MCP_LEAF = 'mcp';--type BridgeRequest =- | { op: 'list_tools'; server: string }- | { op: 'call_tool'; server: string; tool: string; arguments?: Record<string, unknown> };--// Attributes an application-level failure so the sandbox client can tell who is at fault:-// 'agent' (bad generated code: wrong server/tool/args or an unsupported path), 'gateway' (our-// handler failed), or 'bridge' (a NATS bridge lifecycle condition, e.g. the bridge was closed).-// Pure transport failures never produce an envelope, so they're inferred client-side instead.-type BridgeErrorSource = 'gateway' | 'agent' | 'bridge';--// Envelope returned on `msg.reply`. NATS itself always succeeds; the receiver branches on `ok`.-type BridgeReply<T> = { ok: true; result: T } | { ok: false; error: string; source: BridgeErrorSource };--// Caller-caused failure: retrying won't help, so it's attributed to the agent's code, not us.-class InvalidMCPUsageError extends Error {- override readonly name = 'InvalidMCPUsageError';-}--function isHttpClientError(error: unknown): error is { status: number } {- if (typeof error !== 'object' || error === null || !('status' in error)) {- return false;- }- const { status } = error;- return typeof status === 'number' && status >= 400 && status < 500;-}--// An InvalidMCPUsageError, a 4xx HTTP-style exception, or a 4xx-hinted McpConnectionError (e.g. a-// disallowed/unknown tool surfaced by an ToolSet) is caller-caused -> 'agent'; anything else is-// our bug -> 'gateway'.-function classifyErrorSource(e: unknown): BridgeErrorSource {- if (e instanceof InvalidMCPUsageError) return 'agent';- if (isHttpClientError(e)) return 'agent';- // ...remote servers with a 4xx McpConnectionError (has `statusCode`, not `status`). Same meaning.- if (e instanceof McpConnectionError && e.statusCode >= 400 && e.statusCode < 500) return 'agent';- return 'gateway';-}--// Direct W3C extractor, NOT the global `propagation` API. The gateway-wide propagator-// (SelectivePropagator in src/tracing.ts) refuses to restore traceparent unless the-// internal-secret headers are present — a deliberate guard against external requests-// forging trace parents. The NATS bridge is intra-process trusted (sender + receiver-// share the same Node process and span store), so we bypass that gate here and-// always honor the trace context the sandbox echoes back.-const _w3cExtractor = new W3CTraceContextPropagator();--function extractTraceCarrier(msg: Msg): Record<string, string> {- const carrier: Record<string, string> = {};- const traceparent = msg.headers?.get('traceparent');- const tracestate = msg.headers?.get('tracestate');- if (traceparent) carrier['traceparent'] = traceparent;- if (tracestate) carrier['tracestate'] = tracestate;- return carrier;-}--/**- * Per-sandbox NATS subscriber. Bridges sandbox-originated MCP tool calls (sent over wss to the- * sandbox's local nats-server) into the gateway pod's `IToolSet` registry for this agent.- * The pod that holds the preview URL is the only NATS subscriber, which gives sandbox→gateway- * traffic pod-affinity for free.- */-export class SandboxNatsBridge {- readonly subjectPrefix: string;-- private readonly nc: NatsConnection;- private readonly toolSets: Map<string, IToolSet>;- private readonly logger: Logger;- private closed = false;-- private constructor(nc: NatsConnection, toolSets: Map<string, IToolSet>, subjectPrefix: string, logger: Logger) {- this.nc = nc;- this.toolSets = toolSets;- this.subjectPrefix = subjectPrefix;- this.logger = logger;- }-- static async connect(params: {- url: string;- toolSets: Map<string, IToolSet>;- logger: Logger;- }): Promise<SandboxNatsBridge> {- const subjectPrefix = `${SANDBOX_NATS_SUBJECT_ROOT}.${randomUUID()}`;- const logger = params.logger.child({ module: 'SandboxNatsBridge' });- let lastErr: unknown;- for (let attempt = 1; attempt <= NATS_CONNECT_RETRIES; attempt++) {- try {- const nc = await context.with(suppressTracing(context.active()), () =>- wsconnect({ servers: [params.url], timeout: NATS_CONNECT_TIMEOUT_MS }),- );- logger.info(`Connected to sandbox NATS (attempt ${String(attempt)})`, { subjectPrefix });- const bridge = new SandboxNatsBridge(nc, params.toolSets, subjectPrefix, logger);- bridge.subscribe();- return bridge;- } catch (e) {- lastErr = e;- logger.warn(`Sandbox NATS connect attempt ${String(attempt)} failed`, extractErrorLogFields(e));- if (attempt < NATS_CONNECT_RETRIES) {- await new Promise(resolve => setTimeout(resolve, NATS_CONNECT_BACKOFF_MS));- }- }- }- throw lastErr instanceof Error ? lastErr : new Error('Sandbox NATS connect failed');- }-- async close(): Promise<void> {- if (this.closed) return;- this.closed = true;- try {- // drain() resolves once pending replies are flushed and the connection closes.- await withTimeout(this.nc.drain(), NATS_DRAIN_TIMEOUT_MS);- } catch (e) {- // drain rejected or timed out, nc.close() terminates all pending requests and subscriptions on the connection.- this.logger.warn('Sandbox NATS drain failed/timed out; forcing close', extractErrorLogFields(e));- await this.nc.close().catch(() => {- /* no-op */- });- }- }-- async whenClosed(): Promise<void> {- await this.nc.closed();- }-- private subscribe(): void {- this.nc.subscribe(`${this.subjectPrefix}.${SANDBOX_NATS_MCP_LEAF}`, {- callback: (err, msg) => {- this.handle(err, msg, m => this.route(m));- },- });- }-- private route(msg: Msg): Promise<unknown> {- const req = this.decode(msg);- switch (req.op) {- case 'list_tools':- return this.handleListTools(req);- case 'call_tool':- return this.handleCallTool(req);- default:- throw new InvalidMCPUsageError(`Unknown sandbox bridge operation`);- }- }-- private handle(err: Error | null, msg: Msg, handler: (msg: Msg) => Promise<unknown>): void {- if (err) {- this.logger.error('Sandbox NATS subscription error', extractErrorLogFields(err));- return;- }- if (!msg.reply) {- this.logger.warn(`Sandbox NATS request on '${msg.subject}' has no reply subject; dropping`);- return;- }-- // Resume the originating Sandbox: exec span from the per-request traceparent header so- // downstream MCP spans nest correctly (falls through to the current context if absent).- // unsuppressTracing is required: connect() runs under suppressTracing (to drop the- // WS-upgrade span) and nats-core's receive loop reuses that suppressed context, which would- // otherwise make propagation.inject no-op and leak a stale traceparent.- const ctx = _w3cExtractor.extract(- unsuppressTracing(context.active()),- extractTraceCarrier(msg),- defaultTextMapGetter,- );- context.with(ctx, () => void this.dispatch(msg, handler));- }-- private async dispatch(msg: Msg, handler: (msg: Msg) => Promise<unknown>): Promise<void> {- if (this.closed) {- this.logger.warn(`Sandbox NATS bridge is closed; rejecting request on '${msg.subject}'`);- try {- msg.respond(this.encode({ ok: false, error: 'Sandbox NATS bridge is closed', source: 'bridge' }));- } catch (e) {- this.logger.warn(`Failed to send bridge-closed reply on '${msg.subject}'`, extractErrorLogFields(e));- }- return;- }- let reply: BridgeReply<unknown>;- try {- reply = { ok: true, result: await handler(msg) };- } catch (e) {- const source = classifyErrorSource(e);- const errorMessage = e instanceof Error ? e.message : 'Unknown sandbox bridge error';- this.logger.error(- `Sandbox NATS dispatch failed on '${msg.subject}' (source=${source})`,- extractErrorLogFields(e),- );- reply = { ok: false, error: errorMessage, source };- }- try {- msg.respond(this.encode(reply));- } catch (e) {- this.logger.error('Failed to publish sandbox NATS reply', extractErrorLogFields(e));- }- }-- private encode(reply: BridgeReply<unknown>): Uint8Array {- return new TextEncoder().encode(JSON.stringify(reply));- }-- private decode(msg: Msg): BridgeRequest {- return JSON.parse(new TextDecoder().decode(msg.data)) as BridgeRequest;- }-- private getToolSet(serverName: string): IToolSet {- const server = this.toolSets.get(serverName);- if (!server) {- throw new InvalidMCPUsageError(`MCP server '${serverName}' is not available for this agent`);- }- return server;- }-- private async handleListTools(req: { server: string }): Promise<ListToolsResolvedResponse['result']> {- const { server } = req;- const mcp = this.getToolSet(server);- const response = await mcp.listTools();- if (isAuthRequired(response)) {- throw new InvalidMCPUsageError(`MCP server '${server}' requires OAuth; cannot list tools from sandbox`);- }- return response.result;- }-- private async handleCallTool(req: {- server: string;- tool: string;- arguments?: Record<string, unknown> | undefined;- }): Promise<CallToolResolvedResponse['result']> {- const { server, tool, arguments: args } = req;- const response = await this.getToolSet(server).callTool({ name: tool, arguments: args ?? {} });- if (isAuthRequired(response)) {- throw new InvalidMCPUsageError(`MCP server '${server}' requires OAuth; cannot call tool from sandbox`);- }- if (isCallToolResponseCreateSubAgent(response)) {- throw new InvalidMCPUsageError(`Tool '${server}/${tool}' creates a sub-agent and is not callable from sandbox`);- }- if (!isCallToolResponseResult(response)) {- // Approval / client-side-tool paths are intentionally out of scope currently.- throw new InvalidMCPUsageError(- `Tool '${server}/${tool}' requires interactive handling and is not callable from sandbox`,- );- }- return response.result;- }-}diff --git a/packages/harness/src/core/sandbox/codeMode/CodeModeDispatcher.ts b/packages/harness/src/core/sandbox/codeMode/CodeModeDispatcher.tsnew file mode 100644index 000000000..06e21b0e4--- /dev/null+++ b/packages/harness/src/core/sandbox/codeMode/CodeModeDispatcher.ts@@ -0,0 +1,138 @@+import { context, defaultTextMapGetter } from '@opentelemetry/api';+import { unsuppressTracing, W3CTraceContextPropagator } from '@opentelemetry/core';+import { McpConnectionError } from '../../errors';+import {+ isAuthRequired,+ isCallToolResponseCreateSubAgent,+ isCallToolResponseResult,+ type IToolSet,+} from '../../mcp/IMCPServer';+import { extractErrorLogFields } from '../../util/errorLogFields';+import type { CodeModeErrorSource, CodeModeReply, CodeModeRequest } from './types';++/** Minimal logger surface used by Code Mode (avoids a hard winston dep for PoC binders). */+export interface CodeModeLogger {+ child(bindings: Record<string, unknown>): CodeModeLogger;+ error(message: string, meta?: unknown): void;+}++// Caller-caused failure: retrying won't help.+class InvalidMCPUsageError extends Error {+ override readonly name = 'InvalidMCPUsageError';+}++function isHttpClientError(error: unknown): error is { status: number } {+ if (typeof error !== 'object' || error === null || !('status' in error)) {+ return false;+ }+ const { status } = error;+ return typeof status === 'number' && status >= 400 && status < 500;+}++function classifyErrorSource(e: unknown): CodeModeErrorSource {+ if (e instanceof InvalidMCPUsageError) return 'caller';+ if (isHttpClientError(e)) return 'caller';+ if (e instanceof McpConnectionError && e.statusCode >= 400 && e.statusCode < 500) return 'caller';+ return 'internal';+}++// Direct W3C extractor, NOT the global `propagation` API. The gateway-wide propagator+// refuses to restore traceparent unless internal-secret headers are present. Code Mode+// is intra-process trusted, so we bypass that gate and honor the sandbox carrier.+const _w3cExtractor = new W3CTraceContextPropagator();++/**+ * Shared Code Mode policy leaf: tool routing, authz, error `source`. No NATS/UDS.+ */+export class CodeModeDispatcher {+ private readonly toolSets: Map<string, IToolSet>;+ private readonly logger: CodeModeLogger;+ private closed = false;++ constructor(params: { toolSets: readonly IToolSet[]; logger: CodeModeLogger }) {+ this.toolSets = new Map();+ for (const server of params.toolSets) {+ this.toolSets.set(server.name, server);+ }+ this.logger = params.logger.child({ module: 'CodeModeDispatcher' });+ }++ close(): void {+ this.closed = true;+ }++ async dispatch(params: {+ request: CodeModeRequest;+ traceCarrier: Readonly<Record<string, string>>;+ }): Promise<CodeModeReply> {+ if (this.closed) {+ return { ok: false, error: 'Code Mode dispatcher is closed', source: 'transport' };+ }++ const ctx = _w3cExtractor.extract(+ unsuppressTracing(context.active()),+ { ...params.traceCarrier },+ defaultTextMapGetter,+ );++ try {+ const result = await context.with(ctx, () => this.route(params.request));+ return { ok: true, result };+ } catch (e) {+ const source = classifyErrorSource(e);+ const errorMessage = e instanceof Error ? e.message : 'Unknown Code Mode dispatch error';+ this.logger.error(`Code Mode dispatch failed (source=${source})`, extractErrorLogFields(e));+ return { ok: false, error: errorMessage, source };+ }+ }++ private route(request: CodeModeRequest): Promise<unknown> {+ switch (request.op) {+ case 'list_tools':+ return this.handleListTools(request);+ case 'call_tool':+ return this.handleCallTool(request);+ default:+ throw new InvalidMCPUsageError(`Unknown Code Mode operation`);+ }+ }++ private getToolSet(serverName: string): IToolSet {+ const server = this.toolSets.get(serverName);+ if (!server) {+ throw new InvalidMCPUsageError(`MCP server '${serverName}' is not available for this agent`);+ }+ return server;+ }++ private async handleListTools(req: { server: string }): Promise<unknown> {+ const { server } = req;+ const mcp = this.getToolSet(server);+ const response = await mcp.listTools();+ if (isAuthRequired(response)) {+ throw new InvalidMCPUsageError(`MCP server '${server}' requires OAuth; cannot list tools from sandbox`);+ }+ return response.result;+ }++ private async handleCallTool(req: {+ server: string;+ tool: string;+ arguments?: Record<string, unknown> | undefined;+ }): Promise<unknown> {+ const { server, tool, arguments: args } = req;+ const response = await this.getToolSet(server).callTool({ name: tool, arguments: args ?? {} });+ if (isAuthRequired(response)) {+ throw new InvalidMCPUsageError(`MCP server '${server}' requires OAuth; cannot call tool from sandbox`);+ }+ if (isCallToolResponseCreateSubAgent(response)) {+ throw new InvalidMCPUsageError(`Tool '${server}/${tool}' creates a sub-agent and is not callable from sandbox`);+ }+ if (!isCallToolResponseResult(response)) {+ throw new InvalidMCPUsageError(+ `Tool '${server}/${tool}' requires interactive handling and is not callable from sandbox`,+ );+ }+ return response.result;+ }+}diff --git a/packages/harness/src/core/sandbox/codeMode/CodeModeTransport.ts b/packages/harness/src/core/sandbox/codeMode/CodeModeTransport.tsnew file mode 100644index 000000000..3a144b7b9--- /dev/null+++ b/packages/harness/src/core/sandbox/codeMode/CodeModeTransport.ts@@ -0,0 +1,17 @@+import type { CodeModeDispatcher } from './CodeModeDispatcher';++/**+ * Code Mode channel. Construct eagerly with the dispatcher; connect/listen in `start`.+ * `start` may be called again after failure; `stop` is always valid after construct.+ */+export interface CodeModeTransport {+ /**+ * Lazy connect/listen; may be called again after a failed attempt (non-sticky).+ * Idempotent once successfully started.+ */+ start(params: { codeModeDispatcher: CodeModeDispatcher; sandboxId: string; requestTimeoutSeconds: number }): Promise<{+ env: Record<string, string>;+ }>;+ /** Best-effort teardown whether start succeeded, failed, or never ran. */+ stop(): Promise<void>;+}diff --git a/packages/harness/src/core/sandbox/codeMode/nats/CodeModeNatsTransport.ts b/packages/harness/src/core/sandbox/codeMode/nats/CodeModeNatsTransport.tsnew file mode 100644index 000000000..f57f69f6e--- /dev/null+++ b/packages/harness/src/core/sandbox/codeMode/nats/CodeModeNatsTransport.ts@@ -0,0 +1,198 @@+import { wsconnect, type Msg, type NatsConnection } from '@nats-io/nats-core';+import { context } from '@opentelemetry/api';+import { suppressTracing } from '@opentelemetry/core';+import { randomUUID } from 'node:crypto';+import type { Logger } from 'winston';+import { WebSocket } from 'ws';+import { extractErrorLogFields } from '../../../util/errorLogFields';+import { withTimeout } from '../../../util/promiseUtils';+import { DEFAULT_SANDBOX_NATS_WS_PORT } from '../../constants';+import type { CodeModeDispatcher } from '../CodeModeDispatcher';+import type { CodeModeTransport } from '../CodeModeTransport';+import { CodeModeRequestSchema, type CodeModeReply, type CodeModeRequest } from '../types';++// `wsconnect` from @nats-io/nats-core relies on a global WebSocket constructor; in Node we+// provide it from `ws`. Same pattern as `src/services/NatsService.ts`.+Object.assign(global, { WebSocket });++const NATS_CONNECT_TIMEOUT_MS = 10_000;+const NATS_CONNECT_RETRIES = 3;+const NATS_CONNECT_BACKOFF_MS = 250;+const NATS_DRAIN_TIMEOUT_MS = 5_000;++const SANDBOX_NATS_SUBJECT_ROOT = 'sandbox.bridge';+const SANDBOX_NATS_MCP_LEAF = 'mcp';++/**+ * NATS Code Mode transport. Session cache + connection-drop invalidate live here+ * (no `whenClosed` on the public interface).+ */+export class CodeModeNatsTransport implements CodeModeTransport {+ private readonly resolveHostUrl: (sandboxId: string) => Promise<string>;+ private readonly sandboxClientNatsUrl: string;+ private readonly logger: Logger;++ private sessionPromise: Promise<{ env: Record<string, string> }> | undefined;+ private nc: NatsConnection | undefined;+ private dispatcher: CodeModeDispatcher | undefined;++ constructor(params: {+ resolveHostUrl: (sandboxId: string) => Promise<string>;+ sandboxClientNatsUrl?: string;+ logger: Logger;+ }) {+ this.resolveHostUrl = params.resolveHostUrl;+ this.sandboxClientNatsUrl = params.sandboxClientNatsUrl ?? `ws://localhost:${String(DEFAULT_SANDBOX_NATS_WS_PORT)}`;+ this.logger = params.logger.child({ module: 'CodeModeNatsTransport' });+ }++ start(params: {+ codeModeDispatcher: CodeModeDispatcher;+ sandboxId: string;+ requestTimeoutSeconds: number;+ }): Promise<{ env: Record<string, string> }> {+ this.dispatcher = params.codeModeDispatcher;+ this.sessionPromise ??= this.connectSession(params).catch((e: unknown) => {+ this.sessionPromise = undefined;+ throw e;+ });+ return this.sessionPromise;+ }++ async stop(): Promise<void> {+ const pending = this.sessionPromise;+ this.sessionPromise = undefined;+ if (pending !== undefined) {+ try {+ await pending;+ } catch {+ // Connect failed; nothing to drain.+ }+ }+ const nc = this.nc;+ this.nc = undefined;+ if (nc === undefined) return;+ try {+ await withTimeout(nc.drain(), NATS_DRAIN_TIMEOUT_MS);+ } catch (e) {+ this.logger.warn('Code Mode NATS drain failed/timed out; forcing close', extractErrorLogFields(e));+ await nc.close().catch(() => {+ /* no-op */+ });+ }+ }++ private async connectSession(params: {+ sandboxId: string;+ requestTimeoutSeconds: number;+ }): Promise<{ env: Record<string, string> }> {+ const url = await this.resolveHostUrl(params.sandboxId);+ const subjectPrefix = `${SANDBOX_NATS_SUBJECT_ROOT}.${randomUUID()}`;+ let lastErr: unknown;+ let nc: NatsConnection | undefined;+ for (let attempt = 1; attempt <= NATS_CONNECT_RETRIES; attempt++) {+ try {+ nc = await context.with(suppressTracing(context.active()), () =>+ wsconnect({ servers: [url], timeout: NATS_CONNECT_TIMEOUT_MS }),+ );+ this.logger.info(`Connected to sandbox NATS (attempt ${String(attempt)})`, { subjectPrefix });+ break;+ } catch (e) {+ lastErr = e;+ this.logger.warn(`Code Mode NATS connect attempt ${String(attempt)} failed`, extractErrorLogFields(e));+ if (attempt < NATS_CONNECT_RETRIES) {+ await new Promise(resolve => setTimeout(resolve, NATS_CONNECT_BACKOFF_MS));+ }+ }+ }+ if (nc === undefined) {+ throw lastErr instanceof Error ? lastErr : new Error('Code Mode NATS connect failed');+ }++ this.nc = nc;+ this.subscribe(nc, subjectPrefix);++ const cachedPromise = this.sessionPromise;+ void nc.closed().then(() => {+ if (this.sessionPromise === cachedPromise) {+ this.sessionPromise = undefined;+ this.nc = undefined;+ this.logger.info('Code Mode NATS connection closed; session invalidated', {+ sandboxId: params.sandboxId,+ });+ }+ });++ return {+ env: {+ TFY_NATS_URL: this.sandboxClientNatsUrl,+ TFY_NATS_SUBJECT_PREFIX: subjectPrefix,+ TFY_CM_REQUEST_TIMEOUT_SECONDS: String(params.requestTimeoutSeconds),+ },+ };+ }++ private subscribe(nc: NatsConnection, subjectPrefix: string): void {+ nc.subscribe(`${subjectPrefix}.${SANDBOX_NATS_MCP_LEAF}`, {+ callback: (err, msg) => {+ void this.handleMessage(err, msg);+ },+ });+ }++ private async handleMessage(err: Error | null, msg: Msg): Promise<void> {+ if (err) {+ this.logger.error('Code Mode NATS subscription error', extractErrorLogFields(err));+ return;+ }+ if (!msg.reply) {+ this.logger.warn(`Code Mode NATS request on '${msg.subject}' has no reply subject; dropping`);+ return;+ }++ const dispatcher = this.dispatcher;+ if (dispatcher === undefined) {+ try {+ msg.respond(this.encode({ ok: false, error: 'Code Mode dispatcher is not configured', source: 'internal' }));+ } catch (e) {+ this.logger.warn(`Failed to send dispatcher-missing reply on '${msg.subject}'`, extractErrorLogFields(e));+ }+ return;+ }++ const carrier: Record<string, string> = {};+ const traceparent = msg.headers?.get('traceparent');+ const tracestate = msg.headers?.get('tracestate');+ if (traceparent) carrier['traceparent'] = traceparent;+ if (tracestate) carrier['tracestate'] = tracestate;++ let request: CodeModeRequest;+ try {+ request = this.decode(msg);+ } catch (e) {+ this.logger.error(`Failed to decode Code Mode NATS request on '${msg.subject}'`, extractErrorLogFields(e));+ try {+ msg.respond(this.encode({ ok: false, error: 'Malformed Code Mode request', source: 'caller' }));+ } catch (respondErr) {+ this.logger.warn(`Failed to send decode-error reply on '${msg.subject}'`, extractErrorLogFields(respondErr));+ }+ return;+ }++ const reply = await dispatcher.dispatch({ request, traceCarrier: carrier });+ try {+ msg.respond(this.encode(reply));+ } catch (e) {+ this.logger.error('Failed to publish Code Mode NATS reply', extractErrorLogFields(e));+ }+ }++ private encode(reply: CodeModeReply): Uint8Array {+ return new TextEncoder().encode(JSON.stringify(reply));+ }++ private decode(msg: Msg): CodeModeRequest {+ const raw: unknown = JSON.parse(new TextDecoder().decode(msg.data));+ return CodeModeRequestSchema.parse(raw);+ }+}diff --git a/packages/harness/src/core/sandbox/codeMode/types.ts b/packages/harness/src/core/sandbox/codeMode/types.tsnew file mode 100644index 000000000..b64a23ba7--- /dev/null+++ b/packages/harness/src/core/sandbox/codeMode/types.ts@@ -0,0 +1,34 @@+/**+ * Shared Code Mode request/reply wire shapes (NATS body and UDS JSON).+ */+import { z } from 'zod';++export const CodeModeRequestSchema = z.discriminatedUnion('op', [+ z.object({+ op: z.literal('list_tools'),+ server: z.string().min(1),+ }),+ z.object({+ op: z.literal('call_tool'),+ server: z.string().min(1),+ tool: z.string().min(1),+ arguments: z.record(z.string(), z.unknown()).optional(),+ }),+]);+export type CodeModeRequest = z.infer<typeof CodeModeRequestSchema>;++export const CodeModeErrorSourceSchema = z.enum(['internal', 'caller', 'transport']);+export type CodeModeErrorSource = z.infer<typeof CodeModeErrorSourceSchema>;++export const CodeModeReplySchema = z.discriminatedUnion('ok', [+ z.object({+ ok: z.literal(true),+ result: z.unknown(),+ }),+ z.object({+ ok: z.literal(false),+ error: z.string(),+ source: CodeModeErrorSourceSchema,+ }),+]);+export type CodeModeReply = z.infer<typeof CodeModeReplySchema>;diff --git a/packages/harness/src/core/sandbox/provider/DaytonaProvider.ts b/packages/harness/src/core/sandbox/provider/DaytonaProvider.tsindex 20ce7cdf5..014d3ad81 100644--- a/packages/harness/src/core/sandbox/provider/DaytonaProvider.ts+++ b/packages/harness/src/core/sandbox/provider/DaytonaProvider.ts@@ -11,6 +11,8 @@ import {SandboxNotAvailableError,SandboxPathIsDirectoryError,} from '../SandboxErrors';+import type { CodeModeTransport } from '../codeMode/CodeModeTransport';+import { CodeModeNatsTransport } from '../codeMode/nats/CodeModeNatsTransport';import { DEFAULT_PREVIEW_URL_EXPIRY_SECONDS, DEFAULT_SANDBOX_NATS_WS_PORT } from '../constants';import type { ExecResult, SandboxBuild, SandboxExecParams, SandboxFileInfo, SandboxProvider } from './Provider';@@ -384,14 +386,19 @@ export class DaytonaSandboxProvider implements SandboxProvider {});}- async getNatsBridgeUrl(sandboxId: string): Promise<string> {- // Daytona hands us a signed https preview URL; convert http(s) -> ws(s) for the NATS client.- const previewUrl = await this.getPreviewUrl({- sandboxId,- port: this.natsBridgePort,- expiresInSeconds: this.previewUrlExpirySeconds,+ createCodeModeTransport(): CodeModeTransport {+ return new CodeModeNatsTransport({+ resolveHostUrl: async (sandboxId: string) => {+ const previewUrl = await this.getPreviewUrl({+ sandboxId,+ port: this.natsBridgePort,+ expiresInSeconds: this.previewUrlExpirySeconds,+ });+ return httpUrlToWsUrl(previewUrl);+ },+ sandboxClientNatsUrl: `ws://localhost:${String(this.natsBridgePort)}`,+ logger: this.logger,});- return httpUrlToWsUrl(previewUrl);}getAdditionalInstructions(): string | undefined {diff --git a/packages/harness/src/core/sandbox/provider/Provider.ts b/packages/harness/src/core/sandbox/provider/Provider.tsindex 43f8733b8..b2325359c 100644--- a/packages/harness/src/core/sandbox/provider/Provider.ts+++ b/packages/harness/src/core/sandbox/provider/Provider.ts@@ -1,3 +1,5 @@+import type { CodeModeTransport } from '../codeMode/CodeModeTransport';+/** Command executed in sandbox — exitCode may be non-zero but the infra call succeeded. */export interface ExecSuccessResult {success: true;@@ -85,8 +87,8 @@ export interface SandboxProvider {uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void>;/**- * Returns a ready-to-use `ws(s)://` URL for this sandbox's pod-local NATS broker, which the- * gateway connects to as the MCP responder. Throws on failure (caller retries on a later exec).+ * Construct a Code Mode transport for this provider (no connect/listen yet).+ * Throws if the provider does not support Code Mode.*/- getNatsBridgeUrl(sandboxId: string): Promise<string>;+ createCodeModeTransport(): CodeModeTransport;}diff --git a/packages/harness/src/core/sandbox/provider/TFYSandboxProvider.ts b/packages/harness/src/core/sandbox/provider/TFYSandboxProvider.tsindex 2636f344d..ae66992bf 100644--- a/packages/harness/src/core/sandbox/provider/TFYSandboxProvider.ts+++ b/packages/harness/src/core/sandbox/provider/TFYSandboxProvider.ts@@ -4,6 +4,9 @@ import { randomUUID } from 'crypto';import dedent from 'dedent';import type { Logger } from 'winston';import { extractErrorLogFields } from '../../util/errorLogFields';+import type { CodeModeTransport } from '../codeMode/CodeModeTransport';+import { CodeModeNatsTransport } from '../codeMode/nats/CodeModeNatsTransport';+import { DEFAULT_SANDBOX_NATS_WS_PORT } from '../constants';import { SandboxFileNotFoundError, SandboxFileTooLargeError, SandboxPathIsDirectoryError } from '../SandboxErrors';import {ensureExecSuccess,@@ -170,8 +173,12 @@ export class TFYSandboxProvider implements SandboxProvider {}// The TFY sandbox exposes a static, cluster-internal NATS WebSocket URL (no signed URLs).- getNatsBridgeUrl(): Promise<string> {- return Promise.resolve(this.natsBridgeUrl);+ createCodeModeTransport(): CodeModeTransport {+ return new CodeModeNatsTransport({+ resolveHostUrl: () => Promise.resolve(this.natsBridgeUrl),+ sandboxClientNatsUrl: `ws://localhost:${String(DEFAULT_SANDBOX_NATS_WS_PORT)}`,+ logger: this.logger,+ });}getAdditionalInstructions(): string {diff --git a/packages/harness/src/core/sandbox/scripts/mcp_client.py b/packages/harness/src/core/sandbox/scripts/mcp_client.pyindex 3a7c01334..4ed6c0673 100644--- a/packages/harness/src/core/sandbox/scripts/mcp_client.py+++ b/packages/harness/src/core/sandbox/scripts/mcp_client.py@@ -53,7 +53,7 @@ class _BridgeReply(BaseModel):ok: boolresult: Any = Noneerror: str = "unknown error"- source: str = "gateway"+ source: str = "internal"class _ServerConfig(TypedDict):@@ -142,7 +142,7 @@ async def _nats_request(subject: str, payload: dict[str, Any]) -> Any:from nats.errors import NoRespondersErrordata = json.dumps(payload).encode()- request_timeout = float(os.environ["TFY_NATS_REQUEST_TIMEOUT_SECONDS"])+ request_timeout = float(os.environ["TFY_CM_REQUEST_TIMEOUT_SECONDS"])# Phase 1: establish a connection, retrying only connect failures.nc = None@@ -185,12 +185,12 @@ async def _nats_request(subject: str, payload: dict[str, Any]) -> Any:except ValidationError as e:raise RuntimeError(f"NATS reply on '{subject}' is malformed: {e}") from Noneif not reply.ok:- # A well-formed reply means the bridge/transport worked; `source` says who's at fault.- if reply.source == "agent":+ # A well-formed reply means the transport worked; `source` says who's at fault.+ if reply.source == "caller":raise RuntimeError(f"Invalid MCP request on '{subject}': {reply.error}") from None- if reply.source == "bridge":- raise RuntimeError(f"NATS bridge error on '{subject}': {reply.error}") from None- raise RuntimeError(f"Gateway MCP error on '{subject}': {reply.error}") from None+ if reply.source == "transport":+ raise RuntimeError(f"Code Mode transport error on '{subject}': {reply.error}") from None+ raise RuntimeError(f"Internal MCP error on '{subject}': {reply.error}") from Nonereturn reply.resultraise RuntimeError(f"NATS bridge has no responder for '{subject}' after {_NATS_REQUEST_MAX_ATTEMPTS} attempts: {last_transport_error}"diff --git a/packages/harness/tests/core/harnessMocks.ts b/packages/harness/tests/core/harnessMocks.tsindex a5db52e82..bcda141b0 100644--- a/packages/harness/tests/core/harnessMocks.ts+++ b/packages/harness/tests/core/harnessMocks.ts@@ -66,7 +66,7 @@ export function makeStubPublicSandbox(tenantName = 'test-tenant'): Sandbox {getGitCredentialsPath: () => '/tmp/.git-credentials',downloadFile: jest.fn(),uploadFile: jest.fn(),- getNatsBridgeUrl: jest.fn(),+ createCodeModeTransport: jest.fn(),};return new Sandbox({provider,diff --git a/packages/harness/tests/core/sandbox/codeMode/CodeModeDispatcher.test.ts b/packages/harness/tests/core/sandbox/codeMode/CodeModeDispatcher.test.tsnew file mode 100644index 000000000..1d96b5f80--- /dev/null+++ b/packages/harness/tests/core/sandbox/codeMode/CodeModeDispatcher.test.ts@@ -0,0 +1,146 @@+import { McpConnectionError } from '../../../../src/core/errors';+import type { CallToolResponse, IToolSet, ListToolsResponse } from '../../../../src/core/mcp/IMCPServer';+import { CodeModeDispatcher } from '../../../../src/core/sandbox/codeMode/CodeModeDispatcher';+import { makeMockIMCPServer, makeSilentLogger, OBJECT_INPUT_SCHEMA } from '../../harnessMocks';++function makeDispatcher(toolSets: readonly IToolSet[]): CodeModeDispatcher {+ return new CodeModeDispatcher({ toolSets, logger: makeSilentLogger() });+}++describe('CodeModeDispatcher', () => {+ it('list_tools returns the tool list', async () => {+ const server = makeMockIMCPServer({ name: 'github', preload: true });+ const dispatcher = makeDispatcher([server]);++ const reply = await dispatcher.dispatch({+ request: { op: 'list_tools', server: 'github' },+ traceCarrier: {},+ });++ expect(reply).toEqual({+ ok: true,+ result: {+ tools: [{ name: 'tool_a', description: 'A', inputSchema: OBJECT_INPUT_SCHEMA, preload: true }],+ },+ });+ });++ it('call_tool returns the tool result', async () => {+ const server = makeMockIMCPServer({ name: 'github', preload: true });+ jest.mocked(server.callTool).mockResolvedValue({+ result: { content: [{ type: 'text', text: 'ok' }], isError: false },+ wasInitialized: undefined,+ } satisfies CallToolResponse);++ const dispatcher = makeDispatcher([server]);+ const reply = await dispatcher.dispatch({+ request: { op: 'call_tool', server: 'github', tool: 'tool_a', arguments: { x: 1 } },+ traceCarrier: {},+ });++ expect(reply).toEqual({+ ok: true,+ result: { content: [{ type: 'text', text: 'ok' }], isError: false },+ });+ expect(server.callTool).toHaveBeenCalledWith({ name: 'tool_a', arguments: { x: 1 } });+ });++ it('unknown server is caller fault', async () => {+ const dispatcher = makeDispatcher([makeMockIMCPServer({ name: 'github', preload: true })]);++ const reply = await dispatcher.dispatch({+ request: { op: 'list_tools', server: 'missing' },+ traceCarrier: {},+ });++ expect(reply.ok).toBe(false);+ if (reply.ok) throw new Error('unreachable');+ expect(reply.source).toBe('caller');+ expect(reply.error).toContain('missing');+ });++ it('OAuth list_tools is caller fault', async () => {+ const server = makeMockIMCPServer({ name: 'github', preload: true });+ jest.mocked(server.listTools).mockResolvedValue({+ authRequired: { servers: [{ id: 'github', name: 'github', auth_url: 'https://example.com/oauth' }] },+ } satisfies ListToolsResponse);++ const dispatcher = makeDispatcher([server]);+ const reply = await dispatcher.dispatch({+ request: { op: 'list_tools', server: 'github' },+ traceCarrier: {},+ });++ expect(reply.ok).toBe(false);+ if (reply.ok) throw new Error('unreachable');+ expect(reply.source).toBe('caller');+ expect(reply.error).toMatch(/OAuth/);+ });++ it('sub-agent tool is caller fault', async () => {+ const server = makeMockIMCPServer({ name: 'github', preload: true });+ jest.mocked(server.callTool).mockResolvedValue({+ createSubAgent: { type: 'dynamic', name: 'Sub', input: 'do work' },+ } satisfies CallToolResponse);++ const dispatcher = makeDispatcher([server]);+ const reply = await dispatcher.dispatch({+ request: { op: 'call_tool', server: 'github', tool: 'spawn' },+ traceCarrier: {},+ });++ expect(reply.ok).toBe(false);+ if (reply.ok) throw new Error('unreachable');+ expect(reply.source).toBe('caller');+ expect(reply.error).toMatch(/sub-agent/);+ });++ it('4xx McpConnectionError is caller fault', async () => {+ const server = makeMockIMCPServer({ name: 'github', preload: true });+ jest.mocked(server.callTool).mockRejectedValue(new McpConnectionError('bad request', 400));++ const dispatcher = makeDispatcher([server]);+ const reply = await dispatcher.dispatch({+ request: { op: 'call_tool', server: 'github', tool: 'tool_a' },+ traceCarrier: {},+ });++ expect(reply.ok).toBe(false);+ if (reply.ok) throw new Error('unreachable');+ expect(reply.source).toBe('caller');+ });++ it('unexpected errors are internal fault', async () => {+ const server = makeMockIMCPServer({ name: 'github', preload: true });+ jest.mocked(server.callTool).mockRejectedValue(new Error('boom'));++ const dispatcher = makeDispatcher([server]);+ const reply = await dispatcher.dispatch({+ request: { op: 'call_tool', server: 'github', tool: 'tool_a' },+ traceCarrier: {},+ });++ expect(reply.ok).toBe(false);+ if (reply.ok) throw new Error('unreachable');+ expect(reply.source).toBe('internal');+ expect(reply.error).toBe('boom');+ });++ it('closed dispatcher returns transport source without calling tools', async () => {+ const server = makeMockIMCPServer({ name: 'github', preload: true });+ const dispatcher = makeDispatcher([server]);+ dispatcher.close();++ const reply = await dispatcher.dispatch({+ request: { op: 'list_tools', server: 'github' },+ traceCarrier: {},+ });++ expect(reply).toEqual({+ ok: false,+ error: 'Code Mode dispatcher is closed',+ source: 'transport',+ });+ expect(server.listTools).not.toHaveBeenCalled();+ });+});diff --git a/packages/harness/tests/core/sandbox/codeMode/codeModeTransportContractSuite.ts b/packages/harness/tests/core/sandbox/codeMode/codeModeTransportContractSuite.tsnew file mode 100644index 000000000..729928268--- /dev/null+++ b/packages/harness/tests/core/sandbox/codeMode/codeModeTransportContractSuite.ts@@ -0,0 +1,114 @@+import type { CodeModeDispatcher } from '../../../../src/core/sandbox/codeMode/CodeModeDispatcher';+import type { CodeModeTransport } from '../../../../src/core/sandbox/codeMode/CodeModeTransport';+import type { CodeModeReply, CodeModeRequest } from '../../../../src/core/sandbox/codeMode/types';++export interface CodeModeTransportContractFixture {+ transport: CodeModeTransport;+ dispatcher: CodeModeDispatcher;+ sandboxId: string;+ requestTimeoutSeconds: number;+ /**+ * Binder-owned client: given env from `start()`, send one Code Mode request and+ * return the decoded reply. Suite never opens UDS/NATS itself.+ */+ sendRequest: (params: { env: Record<string, string>; request: CodeModeRequest }) => Promise<CodeModeReply>;+ dispose: () => Promise<void>;+}++/**+ * Code Mode transport contract suite — factory-injected so UDS (and future) binders can reuse it.+ * Transport-agnostic: does not assert sock paths, NATS subjects, or other channel-specific keys.+ */+export function runCodeModeTransportContractSuite(+ createFixture: () => CodeModeTransportContractFixture | Promise<CodeModeTransportContractFixture>,+): void {+ describe('CodeModeTransport contract', () => {+ let fixture: CodeModeTransportContractFixture;++ beforeEach(async () => {+ fixture = await createFixture();+ });++ afterEach(async () => {+ await fixture.dispose();+ });++ it('start succeeds and is idempotent', async () => {+ const first = await fixture.transport.start({+ codeModeDispatcher: fixture.dispatcher,+ sandboxId: fixture.sandboxId,+ requestTimeoutSeconds: fixture.requestTimeoutSeconds,+ });+ expect(typeof first.env).toBe('object');+ expect(first.env).not.toBeNull();++ const second = await fixture.transport.start({+ codeModeDispatcher: fixture.dispatcher,+ sandboxId: fixture.sandboxId,+ requestTimeoutSeconds: fixture.requestTimeoutSeconds,+ });+ expect(typeof second.env).toBe('object');+ expect(second.env).not.toBeNull();+ });++ it('round-trips a list_tools request', async () => {+ const { env } = await fixture.transport.start({+ codeModeDispatcher: fixture.dispatcher,+ sandboxId: fixture.sandboxId,+ requestTimeoutSeconds: fixture.requestTimeoutSeconds,+ });++ const reply = await fixture.sendRequest({+ env,+ request: { op: 'list_tools', server: 'demo' },+ });++ expect(reply.ok).toBe(true);+ if (!reply.ok) throw new Error('unreachable');+ expect(reply.result).toBeDefined();+ });++ it('closed dispatcher returns source transport', async () => {+ const { env } = await fixture.transport.start({+ codeModeDispatcher: fixture.dispatcher,+ sandboxId: fixture.sandboxId,+ requestTimeoutSeconds: fixture.requestTimeoutSeconds,+ });+ fixture.dispatcher.close();++ const reply = await fixture.sendRequest({+ env,+ request: { op: 'list_tools', server: 'demo' },+ });++ expect(reply).toEqual({+ ok: false,+ error: 'Code Mode dispatcher is closed',+ source: 'transport',+ });+ });++ it('stop is safe after start and before start; start after stop still round-trips', async () => {+ await fixture.transport.stop();++ await fixture.transport.start({+ codeModeDispatcher: fixture.dispatcher,+ sandboxId: fixture.sandboxId,+ requestTimeoutSeconds: fixture.requestTimeoutSeconds,+ });+ await fixture.transport.stop();++ const restarted = await fixture.transport.start({+ codeModeDispatcher: fixture.dispatcher,+ sandboxId: fixture.sandboxId,+ requestTimeoutSeconds: fixture.requestTimeoutSeconds,+ });++ const reply = await fixture.sendRequest({+ env: restarted.env,+ request: { op: 'list_tools', server: 'demo' },+ });+ expect(reply.ok).toBe(true);+ });+ });+}diff --git a/packages/harness/tests/core/sandbox/provider/sandboxProviderContractSuite.ts b/packages/harness/tests/core/sandbox/provider/sandboxProviderContractSuite.tsnew file mode 100644index 000000000..e4ff9809d--- /dev/null+++ b/packages/harness/tests/core/sandbox/provider/sandboxProviderContractSuite.ts@@ -0,0 +1,126 @@+import { basename, isAbsolute, join } from 'node:path';+import type { SandboxProvider } from '../../../../src/core/sandbox/provider/Provider';+import { ensureExecSuccess } from '../../../../src/core/sandbox/provider/Provider';++export interface SandboxProviderContractFixture {+ provider: SandboxProvider;+ dispose: () => Promise<void>;+}++/**+ * SandboxProvider contract suite — factory-injected so backends can reuse it.+ * Does not exercise `createCodeModeTransport` (NATS vs UDS is covered by the Code Mode transport suite).+ */+export function runSandboxProviderContractSuite(+ createFixture: () => SandboxProviderContractFixture | Promise<SandboxProviderContractFixture>,+): void {+ describe('SandboxProvider contract', () => {+ let fixture: SandboxProviderContractFixture;++ beforeEach(async () => {+ fixture = await createFixture();+ }, 120_000);++ afterEach(async () => {+ await fixture.dispose();+ }, 60_000);++ it('exec is stateful across calls in the same sandbox', async () => {+ const { sandboxId } = await fixture.provider.createSandbox();+ const write = await fixture.provider.exec({+ sandboxId,+ command: "printf 'persist-ok\\n' > persist.txt",+ });+ ensureExecSuccess(write);+ const read = await fixture.provider.exec({+ sandboxId,+ command: 'cat persist.txt',+ });+ ensureExecSuccess(read);+ if (!read.success) throw new Error('unreachable');+ expect(read.response.result).toBe('persist-ok\n');+ });++ it('sandboxes are isolated from each other', async () => {+ const a = await fixture.provider.createSandbox();+ const b = await fixture.provider.createSandbox();+ expect(a.sandboxId).not.toBe(b.sandboxId);++ const write = await fixture.provider.exec({+ sandboxId: a.sandboxId,+ command: "printf 'only-in-a\\n' > secret.txt",+ });+ ensureExecSuccess(write);++ const readRelative = await fixture.provider.exec({+ sandboxId: b.sandboxId,+ command: 'cat secret.txt',+ });+ expect(readRelative.success).toBe(true);+ if (!readRelative.success) throw new Error('unreachable');+ expect(readRelative.response.exitCode).not.toBe(0);+ expect(readRelative.response.result).not.toMatch(/only-in-a/);++ // Path-id backends (Local): deny sibling escape via ../ and absolute paths.+ if (isAbsolute(a.sandboxId) && isAbsolute(b.sandboxId)) {+ const siblingRelative = join('..', basename(a.sandboxId), 'secret.txt');+ const readSiblingRelative = await fixture.provider.exec({+ sandboxId: b.sandboxId,+ command: `cat ${JSON.stringify(siblingRelative)}`,+ });+ expect(readSiblingRelative.success).toBe(true);+ if (!readSiblingRelative.success) throw new Error('unreachable');+ expect(readSiblingRelative.response.exitCode).not.toBe(0);+ expect(readSiblingRelative.response.result).not.toMatch(/only-in-a/);++ const readAbsolute = await fixture.provider.exec({+ sandboxId: b.sandboxId,+ command: `cat ${JSON.stringify(join(a.sandboxId, 'secret.txt'))}`,+ });+ expect(readAbsolute.success).toBe(true);+ if (!readAbsolute.success) throw new Error('unreachable');+ expect(readAbsolute.response.exitCode).not.toBe(0);+ expect(readAbsolute.response.result).not.toMatch(/only-in-a/);++ const writeAbsolute = await fixture.provider.exec({+ sandboxId: b.sandboxId,+ command: `printf 'cross-write\\n' > ${JSON.stringify(join(a.sandboxId, 'cross-write.txt'))}`,+ });+ expect(writeAbsolute.success).toBe(true);+ if (!writeAbsolute.success) throw new Error('unreachable');+ expect(writeAbsolute.response.exitCode).not.toBe(0);++ const writeSiblingRelative = await fixture.provider.exec({+ sandboxId: b.sandboxId,+ command: `printf 'cross-write\\n' > ${JSON.stringify(join('..', basename(a.sandboxId), 'cross-write.txt'))}`,+ });+ expect(writeSiblingRelative.success).toBe(true);+ if (!writeSiblingRelative.success) throw new Error('unreachable');+ expect(writeSiblingRelative.response.exitCode).not.toBe(0);++ const leaked = await fixture.provider.exec({+ sandboxId: a.sandboxId,+ command: 'test -e cross-write.txt',+ });+ expect(leaked.success).toBe(true);+ if (!leaked.success) throw new Error('unreachable');+ expect(leaked.response.exitCode).not.toBe(0);+ }+ });++ it('upload then download round-trips bytes', async () => {+ const { sandboxId } = await fixture.provider.createSandbox();+ const payload = Buffer.from('upload-download-contract\n', 'utf8');+ await fixture.provider.uploadFile({+ sandboxId,+ remotePath: 'roundtrip.bin',+ content: payload,+ });+ const downloaded = await fixture.provider.downloadFile({+ sandboxId,+ path: 'roundtrip.bin',+ });+ expect(Buffer.compare(downloaded, payload)).toBe(0);+ });+ });+}diff --git a/packages/harness/tests/core/sandbox/sandboxBridgeTimeout.test.ts b/packages/harness/tests/core/sandbox/sandboxBridgeTimeout.test.tsindex c8b7c8ef7..94209fcee 100644--- a/packages/harness/tests/core/sandbox/sandboxBridgeTimeout.test.ts+++ b/packages/harness/tests/core/sandbox/sandboxBridgeTimeout.test.ts@@ -1,25 +1,21 @@-jest.mock('../../../src/core/sandbox/SandboxNatsBridge', () => {- const actual = jest.requireActual('../../../src/core/sandbox/SandboxNatsBridge');- return {- ...actual,- SandboxNatsBridge: { connect: jest.fn() },- };-});-+import type { CodeModeTransport } from '../../../src/core/sandbox/codeMode/CodeModeTransport';import type { ExecResult, SandboxExecParams, SandboxProvider } from '../../../src/core/sandbox/provider/Provider';import { Sandbox, SANDBOX_EXEC_TOOL_NAME } from '../../../src/core/sandbox/Sandbox';-import { SandboxNatsBridge } from '../../../src/core/sandbox/SandboxNatsBridge';import { NOOP_AGENT_TRACING } from '../../../src/core/tracing/NoopAgentTracing';import { makeMockIMCPServer, makeSilentLogger } from '../harnessMocks';-const mockBridgeConnect = SandboxNatsBridge.connect as jest.Mock;const AGENT_COMMAND = 'echo hello';-function makeSandbox(options: { mcpRequestTimeoutMs: number; mcpConnectTimeoutMs: number }): {+function makeSandbox(options: {+ mcpRequestTimeoutMs: number;+ mcpConnectTimeoutMs: number;+ transport?: CodeModeTransport;+}): {sandbox: Sandbox;execCalls: SandboxExecParams[];} {const execCalls: SandboxExecParams[] = [];+ const transport = options.transport;const provider: SandboxProvider = {buildImage: () => Promise.resolve({ status: 'ready', reason: null, metadata: null }),getImageBuildStatus: () => Promise.resolve({ status: 'ready', reason: null, metadata: null }),@@ -33,13 +29,19 @@ function makeSandbox(options: { mcpRequestTimeoutMs: number; mcpConnectTimeoutMsgetGitCredentialsPath: () => '/tmp/.git-credentials',downloadFile: jest.fn(),uploadFile: jest.fn(),- getNatsBridgeUrl: () => Promise.resolve('ws://localhost:4444'),+ createCodeModeTransport: () => {+ if (transport === undefined) {+ throw new Error('createCodeModeTransport should not be called without a mock transport');+ }+ return transport;+ },};return {sandbox: new Sandbox({provider,blockDestructiveToolsInCodeMode: true,- ...options,+ mcpRequestTimeoutMs: options.mcpRequestTimeoutMs,+ mcpConnectTimeoutMs: options.mcpConnectTimeoutMs,execExtraEnv: { TFY_TENANT_NAME: 'test-tenant' },logger: makeSilentLogger(),tracing: NOOP_AGENT_TRACING,@@ -59,25 +61,32 @@ async function execAgentCommand(sandbox: Sandbox, execCalls: SandboxExecParams[]}describe('Code Mode timeouts', () => {- beforeEach(() => {- mockBridgeConnect.mockReset();- mockBridgeConnect.mockResolvedValue({- subjectPrefix: 'sandbox.bridge.test',- whenClosed: () => new Promise<void>(() => {}),- close: () => Promise.resolve(),- });- });-- it('derives the NATS wait from MCP request + connect plus a buffer', async () => {+ it('derives the Code Mode wait from MCP request + connect plus a buffer', async () => {+ let capturedTimeoutSeconds: number | undefined;+ const transport: CodeModeTransport = {+ start: params => {+ capturedTimeoutSeconds = params.requestTimeoutSeconds;+ return Promise.resolve({+ env: {+ TFY_NATS_URL: 'ws://localhost:4223',+ TFY_NATS_SUBJECT_PREFIX: 'sandbox.bridge.test',+ TFY_CM_REQUEST_TIMEOUT_SECONDS: String(params.requestTimeoutSeconds),+ },+ });+ },+ stop: () => Promise.resolve(),+ };const { sandbox, execCalls } = makeSandbox({mcpRequestTimeoutMs: 90_000,mcpConnectTimeoutMs: 30_000,+ transport,});sandbox.configureCodeMode([makeMockIMCPServer({ name: 'github', preload: true })]);const call = await execAgentCommand(sandbox, execCalls);- expect(call.env?.['TFY_NATS_REQUEST_TIMEOUT_SECONDS']).toBe('150');+ expect(capturedTimeoutSeconds).toBe(150);+ expect(call.env?.['TFY_CM_REQUEST_TIMEOUT_SECONDS']).toBe('150');});it('leaves the exec timeout to the provider default', async () => {@@ -88,7 +97,7 @@ describe('Code Mode timeouts', () => {const call = await execAgentCommand(sandbox, execCalls);- expect(call.env?.['TFY_NATS_REQUEST_TIMEOUT_SECONDS']).toBeUndefined();+ expect(call.env?.['TFY_CM_REQUEST_TIMEOUT_SECONDS']).toBeUndefined();expect(call.timeoutSeconds).toBeUndefined();});});diff --git a/packages/local-sandbox/.gitignore b/packages/local-sandbox/.gitignorenew file mode 100644index 000000000..16fc3238e--- /dev/null+++ b/packages/local-sandbox/.gitignore@@ -0,0 +1,5 @@+node_modules/+dist/+sandboxes/+*.log+coverage/diff --git a/packages/local-sandbox/fixtures/mcp_pipe_client.py b/packages/local-sandbox/fixtures/mcp_pipe_client.pynew file mode 100644index 000000000..8c55b77ef--- /dev/null+++ b/packages/local-sandbox/fixtures/mcp_pipe_client.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""Code Mode UDS client: connect to host socket, one JSON request/response per call."""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import socket+import sys+import time+from typing import Any++MAX_MESSAGE_BYTES = 64 * 1024 * 1024+++def _sock_path() -> str:+ path = os.environ.get("TFY_MCP_SOCK")+ if not path:+ raise RuntimeError("TFY_MCP_SOCK is not set")+ return path+++def _request_timeout() -> float:+ return float(os.environ.get("TFY_CM_REQUEST_TIMEOUT_SECONDS", "60"))+++def _read_message(sock: socket.socket) -> Any:+ body = b""+ while True:+ chunk = sock.recv(65536)+ if not chunk:+ break+ body += chunk+ if len(body) > MAX_MESSAGE_BYTES:+ raise RuntimeError(f"message exceeds max {MAX_MESSAGE_BYTES} bytes")+ return json.loads(body.decode("utf-8"))+++def _write_message(sock: socket.socket, value: Any) -> None:+ sock.sendall(json.dumps(value).encode("utf-8"))+++def _request_sync(payload: dict[str, Any]) -> Any:+ """Connect → JSON request → write-close → JSON reply → close (no request_id)."""+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ try:+ sock.settimeout(_request_timeout())+ sock.connect(_sock_path())+ _write_message(sock, payload)+ sock.shutdown(socket.SHUT_WR)+ reply = _read_message(sock)+ finally:+ sock.close()+ if not isinstance(reply, dict):+ raise RuntimeError(f"Code Mode reply is not an object: {reply!r}")+ if not reply.get("ok"):+ source = reply.get("source", "internal")+ error = reply.get("error", "unknown error")+ if source == "caller":+ raise RuntimeError(f"Invalid MCP request: {error}")+ if source == "transport":+ raise RuntimeError(f"Code Mode transport error: {error}")+ raise RuntimeError(f"Internal MCP error: {error}")+ return reply.get("result")+++async def list_tools(server: str) -> Any:+ return await asyncio.to_thread(+ _request_sync,+ {"op": "list_tools", "server": server},+ )+++async def call_tool(server: str, tool: str, body: dict[str, Any]) -> Any:+ return await asyncio.to_thread(+ _request_sync,+ {+ "op": "call_tool",+ "server": server,+ "tool": tool,+ "arguments": body,+ },+ )+++async def _cmd_list_tools(server: str) -> None:+ await list_tools(server)+ print("list-tools-ok")+++async def _cmd_call_tool(server: str, tool: str, args: dict[str, Any]) -> None:+ result = await call_tool(server, tool, args)+ print("call-tool-ok", json.dumps(result, default=str))+++async def _cmd_multiplex(server: str, count: int) -> None:+ coros = [+ call_tool(server, "ping", {"message": f"m{i}", "delay_ms": 150})+ for i in range(count)+ ]+ started = time.monotonic()+ results = await asyncio.gather(*coros)+ elapsed_ms = int((time.monotonic() - started) * 1000)+ print("multiplex-ok", elapsed_ms, json.dumps(results, default=str))+++async def _async_main() -> None:+ parser = argparse.ArgumentParser(prog="mcp_pipe_client.py")+ sub = parser.add_subparsers(dest="cmd", required=True)++ list_p = sub.add_parser("list-tools", help="Invoke list_tools()")+ list_p.add_argument("--server", default="demo")++ call_p = sub.add_parser("call-tool", help="Invoke call_tool()")+ call_p.add_argument("--server", default="demo")+ call_p.add_argument("--tool", default="ping")+ call_p.add_argument("--args-json", default='{"message":"poc"}', type=json.loads)++ multi_p = sub.add_parser("multiplex", help="Concurrent call_tool via parallel UDS connects")+ multi_p.add_argument("--server", default="demo")+ multi_p.add_argument("--count", type=int, default=2)++ args = parser.parse_args()+ try:+ if args.cmd == "list-tools":+ await _cmd_list_tools(args.server)+ return+ if args.cmd == "multiplex":+ await _cmd_multiplex(args.server, args.count)+ return+ await _cmd_call_tool(args.server, args.tool, args.args_json)+ except RuntimeError as e:+ print(str(e), file=sys.stderr)+ raise SystemExit(2) from e+++def main() -> None:+ asyncio.run(_async_main())+++if __name__ == "__main__":+ main()diff --git a/packages/local-sandbox/jest.config.cjs b/packages/local-sandbox/jest.config.cjsnew file mode 100644index 000000000..ef6ec35cf--- /dev/null+++ b/packages/local-sandbox/jest.config.cjs@@ -0,0 +1,38 @@+/** @type {import('jest').Config} */+module.exports = {+ testEnvironment: 'node',+ transform: {+ '^.+\\.tsx?$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'typescript', decorators: true },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ // Dependencies that ship as ESM — compile them to CJS for Jest (same as trueforge-core).+ '^.+\\.js$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'ecmascript' },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ },+ transformIgnorePatterns: [],+ moduleNameMapper: {+ '^(\\.{1,2}/.*)\\.js$': '$1',+ '^@truefoundry/trueforge-core/core/(.*)$': '<rootDir>/../harness/src/core/$1',+ '^@truefoundry/trueforge-core/core$': '<rootDir>/../harness/src/core/index.ts',+ '^@truefoundry/trueforge-core$': '<rootDir>/../harness/src/index.ts',+ },+ testTimeout: 120_000,+ maxWorkers: '50%',+ roots: ['<rootDir>/test'],+ testMatch: ['**/test/**/*.test.ts'],+};diff --git a/packages/local-sandbox/lima/local-sandbox.yaml b/packages/local-sandbox/lima/local-sandbox.yamlnew file mode 100644index 000000000..109f495b4--- /dev/null+++ b/packages/local-sandbox/lima/local-sandbox.yaml@@ -0,0 +1,50 @@+# Minimal Lima guest for local-sandbox Linux SRT smoke.+# Mounts the package root at the same absolute host path.+cpus: 1+memory: '2GiB'+disk: '20GiB'++images:+ - location: 'https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-arm64.img'+ arch: 'aarch64'+ - location: 'https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-amd64.img'+ arch: 'x86_64'++# `location` is rewritten to an absolute host path by scripts/smoke-lima.sh+mounts:+ - location: '__LOCAL_SANDBOX_ROOT__'+ writable: true++containerd:+ system: false+ user: false++provision:+ - mode: system+ script: |+ #!/bin/bash+ set -euxo pipefail+ export DEBIAN_FRONTEND=noninteractive+ # Ubuntu 24.04 blocks capability-bearing user namespaces by default; SRT/bwrap needs them.+ if [[ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]]; then+ sysctl -w kernel.apparmor_restrict_unprivileged_userns=0+ printf '%s\n' 'kernel.apparmor_restrict_unprivileged_userns=0' \+ >/etc/sysctl.d/99-local-sandbox-userns.conf+ fi+ apt-get update -y+ apt-get install -y --no-install-recommends \+ bubblewrap \+ socat \+ ripgrep \+ python3 \+ python3-pip \+ python3-setuptools \+ ca-certificates \+ curl \+ gnupg+ if ! command -v node >/dev/null 2>&1; then+ curl -fsSL https://deb.nodesource.com/setup_22.x | bash -+ apt-get install -y --no-install-recommends nodejs+ fi+ corepack enable+ corepack prepare [email protected] --activatediff --git a/packages/local-sandbox/package.json b/packages/local-sandbox/package.jsonnew file mode 100644index 000000000..df7d426a2--- /dev/null+++ b/packages/local-sandbox/package.json@@ -0,0 +1,49 @@+{+ "name": "@truefoundry/local-sandbox",+ "version": "0.0.0",+ "description": "Local SRT SandboxProvider. Private package — not published to npm.",+ "author": "TrueFoundry",+ "license": "MIT",+ "private": true,+ "type": "module",+ "main": "./dist/src/index.js",+ "types": "./dist/src/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/src/index.d.ts",+ "default": "./dist/src/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "dist",+ "fixtures"+ ],+ "engines": {+ "node": ">=22.13.0"+ },+ "scripts": {+ "build": "tsc -p tsconfig.build.json",+ "build:smoke": "tsc -p tsconfig.smoke.json",+ "typecheck": "tsc -p tsconfig.json --noEmit",+ "lint": "eslint src scripts --max-warnings 0 --config ../../eslint.config.mjs",+ "test": "NODE_OPTIONS='--conditions=trueforge-dev' jest --config jest.config.cjs --testPathIgnorePatterns=smoke\\.test\\.ts$",+ "smoke": "NODE_OPTIONS='--conditions=trueforge-dev' jest --config jest.config.cjs --runInBand --forceExit test/smoke.test.ts",+ "smoke:lima": "bash scripts/smoke-lima.sh",+ "probe:loopback": "pnpm build:smoke && node dist/scripts/probe-loopback.js"+ },+ "dependencies": {+ "@anthropic-ai/sandbox-runtime": "0.0.71",+ "@truefoundry/trueforge-core": "workspace:*",+ "ulid": "^3.0.2",+ "zod": "^4.4.3"+ },+ "devDependencies": {+ "@swc/core": "^1.11.0",+ "@swc/jest": "^0.2.37",+ "@types/jest": "^29.5.14",+ "@types/node": "^24.12.0",+ "jest": "^29.7.0",+ "typescript": "^7.0.2"+ }+}diff --git a/packages/local-sandbox/scripts/probe-loopback.ts b/packages/local-sandbox/scripts/probe-loopback.tsnew file mode 100644index 000000000..c79199012--- /dev/null+++ b/packages/local-sandbox/scripts/probe-loopback.ts@@ -0,0 +1,227 @@+/**+ * Probe: can an SRT-sandboxed command reach a host-owned 127.0.0.1 listener?+ * allowLocalBinding is session-scoped (initialize), not per-exec.+ */+import { getDefaultWritePaths, SandboxManager } from '@anthropic-ai/sandbox-runtime';+import { spawn } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdir } from 'node:fs/promises';+import { createServer } from 'node:http';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = join(fileURLToPath(import.meta.url), '..', '..');+const sandboxRootPath = join(ROOT, 'sandboxes', `probe-loopback-${randomUUID()}`);+const SRT_VENDOR = join(+ dirname(fileURLToPath(import.meta.resolve('@anthropic-ai/sandbox-runtime/package.json'))),+ 'vendor',+);++function denySharedDefaultWritePaths(): string[] {+ return getDefaultWritePaths().filter(path => !path.startsWith('/dev/'));+}++function platformAllowRead(): string[] {+ const common = [sandboxRootPath, '/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/lib', '/dev', SRT_VENDOR];+ if (process.platform === 'darwin') {+ return [+ ...common,+ '/System/Library',+ '/Library',+ '/opt/homebrew',+ '/opt/homebrew/bin',+ '/private/var/db/dyld',+ '/private/var/select',+ ];+ }+ return [...common, '/lib', '/lib64', '/usr/lib64', '/usr/local', '/etc', '/proc', '/sys'];+}++async function listenHost(): Promise<{ port: number; close: () => Promise<void> }> {+ const server = createServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'text/plain' });+ res.end('host-loopback-ok\n');+ });+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', () => {+ resolve();+ });+ });+ const addr = server.address();+ if (addr === null || typeof addr === 'string') {+ throw new Error('expected TCP address');+ }+ return {+ port: addr.port,+ close: () =>+ new Promise((resolve, reject) => {+ server.close(err => {+ if (err) reject(err);+ else resolve();+ });+ }),+ };+}++async function runSandboxed(params: { label: string; command: string; allowedDomains: string[] }): Promise<void> {+ const wrap = await SandboxManager.wrapWithSandboxArgv(+ params.command,+ '/bin/bash',+ {+ filesystem: {+ allowWrite: [sandboxRootPath],+ denyWrite: denySharedDefaultWritePaths(),+ denyRead: ['/'],+ allowRead: platformAllowRead(),+ },+ network: {+ allowedDomains: params.allowedDomains,+ deniedDomains: [],+ },+ },+ undefined,+ sandboxRootPath,+ { commandId: randomUUID(), commandText: params.command },+ );+ const [argv0, ...argvRest] = wrap.argv;+ if (argv0 === undefined) throw new Error('empty argv');++ const result = await new Promise<{ code: number | null; out: string }>((resolve, reject) => {+ const child = spawn(argv0, argvRest, {+ cwd: sandboxRootPath,+ env: {+ HOME: join(sandboxRootPath, '.home'),+ TMPDIR: join(sandboxRootPath, '.tmp'),+ PATH: process.platform === 'darwin' ? '/opt/homebrew/bin:/usr/bin:/bin' : '/usr/bin:/bin',+ ...wrap.env,+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let out = '';+ child.stdout.on('data', (c: Buffer) => {+ out += c.toString('utf8');+ });+ child.stderr.on('data', (c: Buffer) => {+ out += c.toString('utf8');+ });+ child.on('error', reject);+ child.on('close', code => {+ resolve({ code, out });+ });+ });++ const preview = result.out.replace(/\s+/g, ' ').trim().slice(0, 280);+ console.log(`[${process.platform}] ${params.label}: exit=${String(result.code)} out=${JSON.stringify(preview)}`);+}++async function runSuite(params: { allowLocalBinding: boolean; hostPort: number }): Promise<void> {+ await SandboxManager.reset().catch(() => undefined);+ await SandboxManager.initialize({+ network: {+ allowedDomains: [],+ deniedDomains: [],+ allowLocalBinding: params.allowLocalBinding,+ },+ filesystem: {+ allowWrite: [],+ denyWrite: denySharedDefaultWritePaths(),+ denyRead: ['/'],+ allowRead: platformAllowRead(),+ },+ });++ console.log(`\n=== ${process.platform} session allowLocalBinding=${String(params.allowLocalBinding)} ===`);++ const connectCmd = [+ "python3 - <<'PY'",+ 'import socket,sys',+ `port=${String(params.hostPort)}`,+ 'try:',+ ' s=socket.create_connection(("127.0.0.1", port), timeout=2)',+ ' s.sendall(b"GET / HTTP/1.0\\r\\nHost: 127.0.0.1\\r\\n\\r\\n")',+ ' data=s.recv(200).decode("utf-8","replace")',+ ' s.close()',+ ' print("CONNECT_OK", "host-loopback-ok" in data, repr(data[:80]))',+ ' sys.exit(0 if "host-loopback-ok" in data else 1)',+ 'except OSError as e:',+ ' print("CONNECT_FAIL", type(e).__name__, e)',+ ' sys.exit(2)',+ 'PY',+ ].join('\n');++ const bindCmd = [+ "python3 - <<'PY'",+ 'import socket,sys',+ 'try:',+ ' s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)',+ ' s.bind(("127.0.0.1", 0))',+ ' print("BIND_OK", s.getsockname())',+ ' s.close()',+ ' sys.exit(0)',+ 'except OSError as e:',+ ' print("BIND_FAIL", type(e).__name__, e)',+ ' sys.exit(2)',+ 'PY',+ ].join('\n');++ const ifacesCmd = [+ "python3 - <<'PY'",+ 'import socket,sys',+ 'print("hostname", socket.gethostname())',+ 'try:',+ ' print("primary", socket.gethostbyname(socket.gethostname()))',+ 'except OSError as e:',+ ' print("primary_fail", e)',+ 'try:',+ ' s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)',+ ' s.connect(("8.8.8.8", 80))',+ ' print("udp_route_ip", s.getsockname()[0])',+ ' s.close()',+ 'except OSError as e:',+ ' print("udp_route_fail", e)',+ 'PY',+ ].join('\n');++ await runSandboxed({+ label: 'ifaces/route probe',+ command: ifacesCmd,+ allowedDomains: [],+ });+ await runSandboxed({+ label: 'connect host port (allowedDomains=[])',+ command: connectCmd,+ allowedDomains: [],+ });+ await runSandboxed({+ label: `connect host port (allowedDomains=127.0.0.1:${String(params.hostPort)})`,+ command: connectCmd,+ allowedDomains: [`127.0.0.1:${String(params.hostPort)}`],+ });+ await runSandboxed({+ label: 'bind sandbox 127.0.0.1:0',+ command: bindCmd,+ allowedDomains: [],+ });+}++async function main(): Promise<void> {+ await mkdir(join(sandboxRootPath, '.tmp'), { recursive: true, mode: 0o700 });+ await mkdir(join(sandboxRootPath, '.home'), { recursive: true, mode: 0o700 });++ const host = await listenHost();+ console.log(`[${process.platform}] host listener 127.0.0.1:${String(host.port)}`);++ try {+ await runSuite({ allowLocalBinding: false, hostPort: host.port });+ await runSuite({ allowLocalBinding: true, hostPort: host.port });+ } finally {+ await host.close();+ await SandboxManager.reset().catch(() => undefined);+ }+}++main().catch((error: unknown) => {+ console.error(error);+ process.exit(1);+});diff --git a/packages/local-sandbox/scripts/smoke-lima.sh b/packages/local-sandbox/scripts/smoke-lima.shnew file mode 100755index 000000000..a0a57b96d--- /dev/null+++ b/packages/local-sandbox/scripts/smoke-lima.sh@@ -0,0 +1,36 @@+#!/usr/bin/env bash+# Create/start a minimal Lima VM and run `pnpm smoke` for Linux SRT coverage.+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+INSTANCE="${LIMA_INSTANCE:-local-sandbox-poc}"+YAML_TEMPLATE="${ROOT}/lima/local-sandbox.yaml"++if ! command -v limactl >/dev/null 2>&1; then+ echo "limactl not found; install Lima first (e.g. brew install lima)" >&2+ exit 1+fi++if ! limactl list -f '{{.Name}}' 2>/dev/null | grep -qx "${INSTANCE}"; then+ echo "creating Lima instance ${INSTANCE} (minimal: 1 CPU / 2GiB)..."+ YAML="$(mktemp -t local-sandbox-lima.XXXXXX.yaml)"+ trap 'rm -f "${YAML}"' EXIT+ # Lima requires absolute mount locations.+ sed "s|__LOCAL_SANDBOX_ROOT__|${ROOT}|g" "${YAML_TEMPLATE}" >"${YAML}"+ limactl create --name="${INSTANCE}" --yes "${YAML}"+fi++status="$(limactl list -f '{{.Name}} {{.Status}}' | awk -v n="${INSTANCE}" '$1==n { print $2; exit }')"+if [[ "${status}" != "Running" ]]; then+ echo "starting Lima instance ${INSTANCE}..."+ limactl start "${INSTANCE}"+fi++echo "running Linux smoke inside ${INSTANCE}..."+# Mount mirrors the host absolute path. Guest deps/sysctl come from lima provision.+limactl shell "${INSTANCE}" -- bash -lc "+ set -euo pipefail+ cd $(printf '%q' "${ROOT}")+ CI=true pnpm install --ignore-workspace --no-frozen-lockfile+ pnpm smoke+"diff --git a/packages/local-sandbox/src/core/CodeModeUdsTransport.ts b/packages/local-sandbox/src/core/CodeModeUdsTransport.tsnew file mode 100644index 000000000..90ae51cfc--- /dev/null+++ b/packages/local-sandbox/src/core/CodeModeUdsTransport.ts@@ -0,0 +1,242 @@+/**+ * Handle-scoped Code Mode UDS transport. Listen/accept live for the Sandbox handle lifetime;+ * one UTF-8 JSON request/reply per connection (peer write-close); no request_id.+ *+ * Sockets live under {@link CodeModeUdsTransportOptions.codeModeSocketParentPath} as ULID names.+ * Parent must be mode 0700 (enforced) so other accounts cannot replace the sock inode before+ * connect; after listen the sock is chmod 0600. Same-UID isolation is still SRT path policy.+ * The caller owns that parent directory's lifetime; this transport unlinks the sock it creates.+ */+import type {+ CodeModeDispatcher,+ CodeModeReply,+ CodeModeRequest,+ CodeModeTransport,+} from '@truefoundry/trueforge-core/core';+import { CodeModeRequestSchema, validateNoPathTraversal } from '@truefoundry/trueforge-core/core';+import { chmodSync, existsSync, realpathSync, statSync } from 'node:fs';+import { chmod, unlink } from 'node:fs/promises';+import { createServer, type Server, type Socket } from 'node:net';+import { isAbsolute, join, resolve } from 'node:path';+import { ulid } from 'ulid';+import { encodeJsonMessage, JsonMessageReader, MAX_MESSAGE_BYTES } from './frame.js';+import { registerCodeModeSocketPath, unregisterCodeModeSocketPath } from './hostRun.js';++const MAX_CODE_MODE_SOCKET_PARENT_BYTES = 60;+const CODE_MODE_SOCKET_PARENT_MODE = 0o700;+const CODE_MODE_SOCKET_MODE = 0o600;++export interface CodeModeUdsTransportOptions {+ /**+ * Absolute existing directory for Code Mode UDS files (≤60 bytes, mode 0700).+ * Socket path is `join(parent, ulid)`; sock is chmod 0600 after listen.+ */+ codeModeSocketParentPath: string;+ maxMessageBytes?: number | undefined;+ /** Optional: observe inbound protocol failures (oversized / malformed). */+ onProtocolError?: ((message: string) => void) | undefined;+}++/** Validate and normalize parent dir for Code Mode socks; enforce mode 0700. */+export function assertCodeModeSocketParentPath(path: string): string {+ if (!isAbsolute(path)) {+ throw new Error('codeModeSocketParentPath must be an absolute path');+ }+ validateNoPathTraversal(path);+ const resolved = resolve(path);+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {+ throw new Error('codeModeSocketParentPath must be an existing directory');+ }+ // Seatbelt / allowUnixSockets match real paths (/private/var/... on macOS).+ const real = realpathSync(resolved);+ const bytes = Buffer.byteLength(real);+ if (bytes > MAX_CODE_MODE_SOCKET_PARENT_BYTES) {+ throw new Error(+ `codeModeSocketParentPath must be at most ${String(MAX_CODE_MODE_SOCKET_PARENT_BYTES)} bytes (got ${String(bytes)})`,+ );+ }+ // Owner-only parent: other accounts cannot rename/replace socks under this dir.+ chmodSync(real, CODE_MODE_SOCKET_PARENT_MODE);+ const mode = statSync(real).mode & 0o777;+ if (mode !== CODE_MODE_SOCKET_PARENT_MODE) {+ throw new Error(`codeModeSocketParentPath must be mode 0700 after chmod (got 0o${mode.toString(8)})`);+ }+ return real;+}++export class CodeModeUdsTransport implements CodeModeTransport {+ private readonly codeModeSocketParentPath: string;+ private readonly maxMessageBytes: number;+ private readonly onProtocolError: ((message: string) => void) | undefined;++ private sessionPromise: Promise<{ env: Record<string, string> }> | undefined;+ private server: Server | undefined;+ private sockPath: string | undefined;+ private dispatcher: CodeModeDispatcher | undefined;+ private cachedEnv: Record<string, string> | undefined;++ constructor(options: CodeModeUdsTransportOptions) {+ this.codeModeSocketParentPath = assertCodeModeSocketParentPath(options.codeModeSocketParentPath);+ this.maxMessageBytes = options.maxMessageBytes ?? MAX_MESSAGE_BYTES;+ this.onProtocolError = options.onProtocolError;+ }++ start(params: {+ codeModeDispatcher: CodeModeDispatcher;+ sandboxId: string;+ requestTimeoutSeconds: number;+ }): Promise<{ env: Record<string, string> }> {+ this.dispatcher = params.codeModeDispatcher;+ this.sessionPromise ??= this.listenSession(params).catch((e: unknown) => {+ this.sessionPromise = undefined;+ this.cachedEnv = undefined;+ throw e;+ });+ return this.sessionPromise;+ }++ async stop(): Promise<void> {+ const pending = this.sessionPromise;+ this.sessionPromise = undefined;+ this.cachedEnv = undefined;+ if (pending !== undefined) {+ try {+ await pending;+ } catch {+ // Listen failed; nothing to close.+ }+ }+ const server = this.server;+ const sockPath = this.sockPath;+ this.server = undefined;+ this.sockPath = undefined;+ if (server !== undefined) {+ await new Promise<void>(resolveClose => {+ server.close(() => {+ resolveClose();+ });+ });+ }+ if (sockPath !== undefined) {+ unregisterCodeModeSocketPath(sockPath);+ await unlink(sockPath).catch(() => undefined);+ }+ }++ private async listenSession(params: { requestTimeoutSeconds: number }): Promise<{ env: Record<string, string> }> {+ if (this.server !== undefined && this.cachedEnv !== undefined) {+ return { env: this.cachedEnv };+ }++ // Re-check: caller owns the parent dir and may have removed it after construct.+ assertCodeModeSocketParentPath(this.codeModeSocketParentPath);++ const sockPath = join(this.codeModeSocketParentPath, ulid().toLowerCase());+ await unlink(sockPath).catch(() => undefined);+ registerCodeModeSocketPath(sockPath);+ const server = createServer({ allowHalfOpen: true });+ try {+ await new Promise<void>((resolveListen, reject) => {+ server.once('error', reject);+ server.listen(sockPath, () => {+ server.off('error', reject);+ resolveListen();+ });+ });+ // Narrow the listen→chmod window; 0700 parent already blocks other accounts from replace.+ await chmod(sockPath, CODE_MODE_SOCKET_MODE);+ } catch (error) {+ unregisterCodeModeSocketPath(sockPath);+ server.close();+ await unlink(sockPath).catch(() => undefined);+ throw error;+ }++ this.server = server;+ this.sockPath = sockPath;+ server.on('connection', socket => {+ this.handleConnection(socket);+ });++ const env = {+ TFY_MCP_SOCK: sockPath,+ TFY_CM_REQUEST_TIMEOUT_SECONDS: String(params.requestTimeoutSeconds),+ };+ this.cachedEnv = env;+ return { env };+ }++ private handleConnection(socket: Socket): void {+ const reader = new JsonMessageReader({ maxBytes: this.maxMessageBytes });+ let settled = false;++ socket.on('error', () => undefined);++ // Oversized / malformed frames only tear down this connection (and notify+ // onProtocolError). Transport is handle-scoped and does not kill the process group.+ const fail = (message: string): void => {+ if (settled) return;+ settled = true;+ this.onProtocolError?.(message);+ socket.destroy();+ };++ socket.on('data', (chunk: Buffer) => {+ try {+ reader.push(chunk);+ } catch (error) {+ fail(error instanceof Error ? error.message : String(error));+ }+ });++ socket.on('end', () => {+ if (settled) return;+ settled = true;+ void this.dispatchConnection(socket, reader).catch((error: unknown) => {+ this.onProtocolError?.(error instanceof Error ? error.message : String(error));+ socket.destroy();+ });+ });+ }++ private async dispatchConnection(socket: Socket, reader: JsonMessageReader): Promise<void> {+ let request: CodeModeRequest;+ try {+ const parsed = CodeModeRequestSchema.safeParse(reader.finish());+ if (!parsed.success) {+ const reply: CodeModeReply = {+ ok: false,+ error: 'Malformed Code Mode request',+ source: 'caller',+ };+ socket.write(encodeJsonMessage(reply));+ socket.end();+ return;+ }+ request = parsed.data;+ } catch (error) {+ this.onProtocolError?.(error instanceof Error ? error.message : String(error));+ socket.destroy();+ return;+ }++ const dispatcher = this.dispatcher;+ if (dispatcher === undefined) {+ const reply: CodeModeReply = {+ ok: false,+ error: 'Code Mode dispatcher is not configured',+ source: 'internal',+ };+ socket.write(encodeJsonMessage(reply));+ socket.end();+ return;+ }++ const reply = await dispatcher.dispatch({ request, traceCarrier: {} });+ try {+ socket.write(encodeJsonMessage(reply));+ } finally {+ socket.end();+ }+ }+}diff --git a/packages/local-sandbox/src/core/frame.ts b/packages/local-sandbox/src/core/frame.tsnew file mode 100644index 000000000..e56e8b89f--- /dev/null+++ b/packages/local-sandbox/src/core/frame.ts@@ -0,0 +1,36 @@+/**+ * Code Mode UDS payload: one UTF-8 JSON value per connection.+ * Peer write-close (EOF) delimits the message; no length prefix.+ */+import { JsonMessageValueSchema } from '../schemas/jsonMessage.js';++export const MAX_MESSAGE_BYTES = 64 * 1024 * 1024;++export function encodeJsonMessage(value: unknown): Buffer {+ return Buffer.from(JSON.stringify(value), 'utf8');+}++/** Accumulates inbound socket bytes until EOF, then parses JSON. */+export class JsonMessageReader {+ #buffer = Buffer.alloc(0);+ readonly #maxBytes: number;++ constructor(options: { maxBytes?: number } = {}) {+ this.#maxBytes = options.maxBytes ?? MAX_MESSAGE_BYTES;+ }++ push(chunk: Buffer): void {+ if (this.#buffer.length + chunk.length > this.#maxBytes) {+ throw new Error(`message exceeds max ${String(this.#maxBytes)} bytes`);+ }+ this.#buffer = Buffer.concat([this.#buffer, chunk]);+ }++ finish(): unknown {+ try {+ return JsonMessageValueSchema.parse(JSON.parse(this.#buffer.toString('utf8')));+ } catch (error) {+ throw new Error('invalid JSON message', { cause: error });+ }+ }+}diff --git a/packages/local-sandbox/src/core/hostRun.ts b/packages/local-sandbox/src/core/hostRun.tsnew file mode 100644index 000000000..7197e3c78--- /dev/null+++ b/packages/local-sandbox/src/core/hostRun.ts@@ -0,0 +1,505 @@+/**+ * Host-side sandboxed exec (in-process supervisor).+ * Only the untrusted command argv is SRT-wrapped. Code Mode UDS is owned by+ * {@link CodeModeUdsTransport} (handle-scoped); pass TFY_MCP_SOCK via `env` when needed.+ *+ * Platform policy (allowRead / AF_UNIX / PATH) uses {@link LocalSandboxPlatform} from+ * {@link initSrt} — the same platform captured by LocalSandboxProvider.isSupported.+ */+import { getDefaultWritePaths, SandboxManager } from '@anthropic-ai/sandbox-runtime';+import { execFile, spawn, type ChildProcess } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { existsSync } from 'node:fs';+import { copyFile, mkdir, rm } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { dirname, isAbsolute, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);++const HERE = dirname(fileURLToPath(import.meta.url));+/** Package root from src/ or dist/src/ (Jest runs TypeScript source). */+function packageRoot(startDir: string): string {+ let dir = startDir;+ for (;;) {+ if (existsSync(join(dir, 'package.json')) && existsSync(join(dir, 'fixtures'))) {+ return dir;+ }+ const parent = dirname(dir);+ if (parent === dir) {+ throw new Error(`local-sandbox package root not found from ${startDir}`);+ }+ dir = parent;+ }+}+const ROOT = packageRoot(HERE);+const FIXTURES = join(ROOT, 'fixtures');+/** SRT ships Linux helpers (e.g. apply-seccomp) under vendor/; the wrapped command must read them. */+// Package-root resolve (not app-module loading): Jest's CJS transform breaks import.meta.resolve.+const SRT_VENDOR = join(+ dirname(createRequire(import.meta.url).resolve('@anthropic-ai/sandbox-runtime/package.json')),+ 'vendor',+);++/**+ * Cap for buffered stdout+stderr per exec.+ * Sized for base64 of a max-sized download (10 MiB → ~13.3 MiB) plus headroom.+ */+export const MAX_OUTPUT_BYTES = 14 * 1024 * 1024;++/** Platforms LocalSandboxProvider / hostRun can run on. */+export type LocalSandboxPlatform = 'darwin' | 'linux';++/** Cached from {@link initSrt}; cleared by {@link resetSrt}. Used by session policy helpers after init. */+let activePlatform: LocalSandboxPlatform | undefined;++function requireActivePlatform(): LocalSandboxPlatform {+ if (activePlatform === undefined) {+ throw new Error('SRT platform is not set; call initSrt({ platform }) first');+ }+ return activePlatform;+}++/** PATH for sandboxed commands — must stay aligned with allowRead exec roots. */+const COMMAND_PATH_BY_PLATFORM = {+ // On macOS, prefer Homebrew ahead of `/usr/bin` shims (those need Xcode select+ // paths that we intentionally do not allow-read).+ darwin: '/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin',+ linux: '/usr/bin:/bin:/usr/sbin:/sbin',+} as const satisfies Record<LocalSandboxPlatform, string>;++export function commandPath(platform: LocalSandboxPlatform): string {+ return COMMAND_PATH_BY_PLATFORM[platform];+}++/**+ * Resolve a command name to an absolute path on the host using the sandbox PATH.+ * Uses `/bin/sh` only as a host bootstrap for `command -v` (not the sandboxed wrap shell).+ */+export async function resolveCommandOnHost(params: {+ platform: LocalSandboxPlatform;+ name: string;+}): Promise<string | undefined> {+ if (!/^[A-Za-z0-9._+-]+$/.test(params.name)) {+ throw new Error(`invalid command name for resolveCommandOnHost: ${params.name}`);+ }+ const pathEnv = commandPath(params.platform);+ try {+ const { stdout } = await execFileAsync('/bin/sh', ['-c', `command -v -- ${params.name}`], {+ env: { PATH: pathEnv },+ encoding: 'utf8',+ });+ const resolved = stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);+ if (resolved === undefined || resolved.length === 0 || !isAbsolute(resolved)) {+ return undefined;+ }+ return resolved;+ } catch {+ return undefined;+ }+}++export interface SessionResult {+ stdoutText: string;+ stderrText: string;+ exitCode: number;+ protocolError: string | undefined;+ timedOut: boolean;+ /** Process-group leader pid of the sandboxed command (Unix). */+ childPid: number | undefined;+}++/**+ * SRT always unions getDefaultWritePaths() into allowWrite. There is no config+ * flag to disable that. Deny the shared/host defaults (not /dev/*) so they are+ * not usable as cross-sandbox writable storage. denyWrite wins over allowWrite.+ */+function denySharedDefaultWritePaths(): string[] {+ return getDefaultWritePaths().filter(path => !path.startsWith('/dev/'));+}++const ALLOW_READ_BY_PLATFORM = {+ darwin: [+ '/opt/homebrew/bin',+ '/usr/bin',+ '/bin',+ '/usr/sbin',+ '/sbin',+ '/usr/lib',+ '/System/Library',+ '/Library',+ '/private/var/db/dyld',+ '/private/var/select',+ '/opt/homebrew',+ '/dev',+ ],+ linux: [+ '/usr/bin',+ '/bin',+ '/usr/sbin',+ '/sbin',+ '/lib',+ '/lib64',+ '/usr/lib',+ '/usr/lib64',+ '/usr/local',+ '/etc',+ '/dev',+ '/proc',+ '/sys',+ '/tmp',+ SRT_VENDOR,+ ],+} as const satisfies Record<LocalSandboxPlatform, readonly string[]>;++export function platformAllowRead(platform: LocalSandboxPlatform): string[] {+ return [...ALLOW_READ_BY_PLATFORM[platform]];+}++/**+ * Policy for the untrusted command only (deny-by-default reads).+ * The host (in-process supervisor) is never placed under this policy.+ */+function filesystemPolicy(params: { sandboxRootPath: string; platform: LocalSandboxPlatform }): {+ allowWrite: string[];+ denyWrite: string[];+ denyRead: string[];+ allowRead: string[];+} {+ return {+ allowWrite: [params.sandboxRootPath],+ denyWrite: denySharedDefaultWritePaths(),+ denyRead: ['/'],+ allowRead: [params.sandboxRootPath, ...codeModeSocketPaths, ...platformAllowRead(params.platform)],+ };+}++/** Curated env for the sandboxed command — never the full host process.env. */+function commandEnv(params: {+ sandboxRootPath: string;+ platform: LocalSandboxPlatform;+ extra?: Record<string, string>;+}): Record<string, string> {+ const tmp = join(params.sandboxRootPath, '.tmp');+ const home = join(params.sandboxRootPath, '.home');+ const locked = {+ HOME: home,+ TMPDIR: tmp,+ TMP: tmp,+ TEMP: tmp,+ PATH: commandPath(params.platform),+ };+ return {+ ...params.extra,+ ...locked,+ };+}++/** Session filesystem floor (per-exec customConfig still tightens allowWrite/allowRead). */+function sessionFilesystem(platform: LocalSandboxPlatform): {+ allowWrite: string[];+ denyWrite: string[];+ denyRead: string[];+ allowRead: string[];+} {+ const allowWrite: string[] = [];+ return {+ allowWrite,+ denyWrite: denySharedDefaultWritePaths(),+ denyRead: ['/'],+ allowRead: platformAllowRead(platform),+ };+}++/**+ * AF_UNIX policy is session-scoped only (wrap customConfig cannot set it).+ * - Linux: allowAllUnixSockets; pathname connect still needs FS allowRead (bwrap).+ * - macOS: allowAllUnixSockets does NOT consult allowRead for connect — use+ * allowUnixSockets subpath, synced at sandbox create/remove.+ */+function sessionNetwork(params: { platform: LocalSandboxPlatform; unixSockets?: string[] }):+ | {+ allowedDomains: string[];+ deniedDomains: string[];+ allowAllUnixSockets: true;+ }+ | {+ allowedDomains: string[];+ deniedDomains: string[];+ allowAllUnixSockets: false;+ allowUnixSockets: string[];+ } {+ const allowedDomains: string[] = [];+ const deniedDomains: string[] = [];+ if (params.platform === 'linux') {+ return {+ allowedDomains,+ deniedDomains,+ allowAllUnixSockets: true,+ };+ }+ return {+ allowedDomains,+ deniedDomains,+ allowAllUnixSockets: false,+ allowUnixSockets: params.unixSockets ?? [],+ };+}++/** Active sandbox roots allowed for macOS pathname UDS (seatbelt subpath). */+const darwinUnixSocketSandboxRoots = new Set<string>();+/** Exact Code Mode UDS paths — macOS allowUnixSockets + Linux allowRead. */+const codeModeSocketPaths = new Set<string>();++function darwinUnixSocketPaths(): string[] {+ return [...darwinUnixSocketSandboxRoots, ...codeModeSocketPaths];+}++function syncDarwinUnixSockets(): void {+ // No-op until initSrt: register/unregister may run from transport-only tests.+ if (SandboxManager.getConfig() === undefined) return;+ const platform = requireActivePlatform();+ if (platform !== 'darwin') return;+ SandboxManager.updateConfig(buildSessionConfig(platform));+}++/** Single source for process-scoped SRT session config (init + sock register/unregister). */+function buildSessionConfig(platform: LocalSandboxPlatform): {+ network: ReturnType<typeof sessionNetwork>;+ filesystem: ReturnType<typeof sessionFilesystem>;+} {+ return {+ network: sessionNetwork({ platform, unixSockets: darwinUnixSocketPaths() }),+ filesystem: sessionFilesystem(platform),+ };+}++/** Allow sandboxed clients to connect to this exact Code Mode sock path. */+export function registerCodeModeSocketPath(sockPath: string): void {+ codeModeSocketPaths.add(sockPath);+ syncDarwinUnixSockets();+}++export function unregisterCodeModeSocketPath(sockPath: string): void {+ codeModeSocketPaths.delete(sockPath);+ syncDarwinUnixSockets();+}++/** Create a sandbox directory at `sandboxRootPath` (also the sandbox id). */+export async function createSandbox(sandboxRootPath: string): Promise<string> {+ await mkdir(sandboxRootPath, { recursive: true, mode: 0o700 });+ await mkdir(join(sandboxRootPath, '.tmp'), { recursive: true, mode: 0o700 });+ await mkdir(join(sandboxRootPath, '.home'), { recursive: true, mode: 0o700 });+ darwinUnixSocketSandboxRoots.add(sandboxRootPath);+ syncDarwinUnixSockets();+ return sandboxRootPath;+}++export async function removeSandbox(sandboxRootPath: string): Promise<void> {+ darwinUnixSocketSandboxRoots.delete(sandboxRootPath);+ syncDarwinUnixSockets();+ await rm(sandboxRootPath, { recursive: true, force: true });+}++/**+ * Process-scoped SRT init. Per-exec filesystem policy is applied in+ * {@link runSupervisorSession} via wrapWithSandboxArgv customConfig.+ */+export async function initSrt(params: { platform: LocalSandboxPlatform }): Promise<void> {+ activePlatform = params.platform;+ await SandboxManager.initialize(buildSessionConfig(params.platform));+}++export async function resetSrt(): Promise<void> {+ codeModeSocketPaths.clear();+ activePlatform = undefined;+ await SandboxManager.reset();+}++/** Whether process-scoped SRT session config is already initialized. */+export function isSrtInitialized(): boolean {+ return activePlatform !== undefined && SandboxManager.getConfig() !== undefined;+}++/**+ * Tear down the sandboxed exec and every process in its group.+ * Child is spawned as a process-group leader (`detached: true` on Unix).+ */+export function killExecTree(child: ChildProcess | undefined): void {+ if (!child) return;+ const pid = child.pid;+ if (pid !== undefined && process.platform !== 'win32') {+ try {+ process.kill(-pid, 'SIGKILL');+ return;+ } catch {+ // ESRCH if the group is already gone — fall through.+ }+ }+ if (!child.killed) {+ child.kill('SIGKILL');+ }+}++/**+ * Run one SRT-wrapped command. Code Mode UDS (if any) is supplied via `env.TFY_MCP_SOCK`+ * from {@link CodeModeUdsTransport.start}.+ */+export async function runSupervisorSession(params: {+ sandboxRootPath: string;+ command: string;+ /** Absolute shell path used to wrap the command string (from isSupported). */+ shell: string;+ /** Platform policy for allowRead / PATH (from isSupported). */+ platform: LocalSandboxPlatform;+ cwd?: string;+ env?: Record<string, string>;+ /** Optional stdin bytes for the sandboxed command (e.g. upload payload). */+ stdin?: Buffer;+ /** Host-visible pid of the sandboxed process-group leader (after spawn). */+ onChildSpawn?: (pid: number) => void;+ /** Hard wall-clock limit for the sandboxed command; caller must choose deliberately. */+ timeoutMs: number;+}): Promise<SessionResult> {+ const {+ sandboxRootPath,+ command,+ shell,+ platform,+ cwd = sandboxRootPath,+ env,+ stdin,+ onChildSpawn,+ timeoutMs,+ } = params;++ const wrap = await SandboxManager.wrapWithSandboxArgv(+ command,+ shell,+ {+ filesystem: filesystemPolicy({ sandboxRootPath, platform }),+ network: {+ allowedDomains: [],+ deniedDomains: [],+ },+ },+ undefined,+ sandboxRootPath,+ { commandId: randomUUID(), commandText: command },+ );++ const [argv0, ...argvRest] = wrap.argv;+ if (argv0 === undefined) {+ throw new Error('wrapWithSandboxArgv returned empty argv');+ }++ // Curated env only — do not spread wrap.env (it can carry ambient host secrets).+ // Code Mode sock path (TFY_MCP_SOCK) is expected in `env` when the caller starts a transport.+ const childEnv: NodeJS.ProcessEnv = {+ ...commandEnv({ sandboxRootPath, platform, ...(env === undefined ? {} : { extra: env }) }),+ };++ const child = spawn(argv0, argvRest, {+ cwd,+ env: childEnv,+ shell: false,+ // Detached process groups break stdin forwarding for upload (`cat` via pipe) under Jest.+ detached: stdin === undefined && process.platform !== 'win32',+ stdio: [stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],+ });+ if (child.pid !== undefined) {+ onChildSpawn?.(child.pid);+ }+ if (stdin !== undefined) {+ const stdinStream = child.stdin;+ if (stdinStream === null) {+ killExecTree(child);+ SandboxManager.cleanupAfterCommand();+ throw new Error('stdin unavailable for sandboxed command');+ }+ stdinStream.on('error', () => undefined);+ await new Promise<void>((resolve, reject) => {+ stdinStream.end(stdin, (error?: Error | null) => {+ if (error) reject(error);+ else resolve();+ });+ });+ }++ let stdoutText = '';+ let stderrText = '';+ let bufferedOutput = 0;+ let protocolError: string | undefined;+ let timedOut = false;+ let closed = false;++ const ignoreStreamError = (+ stream:+ | {+ on: (event: 'error', cb: (err: Error) => void) => void;+ }+ | null+ | undefined,+ ): void => {+ stream?.on('error', () => undefined);+ };++ const appendOutput = (stream: 'stdout' | 'stderr', chunk: Buffer): void => {+ bufferedOutput += chunk.length;+ if (bufferedOutput > MAX_OUTPUT_BYTES) {+ protocolError = `buffered output exceeded ${String(MAX_OUTPUT_BYTES)} bytes`;+ killExecTree(child);+ return;+ }+ const text = chunk.toString('utf8');+ if (stream === 'stdout') stdoutText += text;+ else stderrText += text;+ };++ ignoreStreamError(child.stdout);+ ignoreStreamError(child.stderr);+ child.stdout?.on('data', (chunk: Buffer) => {+ appendOutput('stdout', chunk);+ });+ child.stderr?.on('data', (chunk: Buffer) => {+ appendOutput('stderr', chunk);+ });++ return await new Promise<SessionResult>((resolve, reject) => {+ const timer = setTimeout(() => {+ timedOut = true;+ killExecTree(child);+ }, timeoutMs);++ child.on('error', error => {+ if (closed) return;+ closed = true;+ clearTimeout(timer);+ SandboxManager.cleanupAfterCommand();+ reject(error);+ });++ child.on('close', code => {+ if (closed) return;+ closed = true;+ clearTimeout(timer);+ SandboxManager.cleanupAfterCommand();+ resolve({+ stdoutText,+ stderrText,+ exitCode: typeof code === 'number' ? code : timedOut ? 1 : 0,+ protocolError,+ timedOut,+ childPid: child.pid,+ });+ });+ });+}++/** Copy the MCP client fixture into the sandbox (isolation: only sandbox root is writable). */+export async function installMcpFixture(sandboxRootPath: string): Promise<string> {+ const dest = join(sandboxRootPath, 'mcp_pipe_client.py');+ await copyFile(join(FIXTURES, 'mcp_pipe_client.py'), dest);+ return dest;+}diff --git a/packages/local-sandbox/src/index.ts b/packages/local-sandbox/src/index.tsnew file mode 100644index 000000000..6837f1448--- /dev/null+++ b/packages/local-sandbox/src/index.ts@@ -0,0 +1,5 @@+export { CodeModeUdsTransport } from './core/CodeModeUdsTransport.js';+export type { CodeModeUdsTransportOptions } from './core/CodeModeUdsTransport.js';+export type { LocalSandboxPlatform } from './core/hostRun.js';+export { LocalSandboxProvider } from './provider/LocalSandboxProvider.js';+export type { LocalSandboxProviderOptions, LocalSandboxSupportResult } from './provider/LocalSandboxProvider.js';diff --git a/packages/local-sandbox/src/provider/LocalSandboxProvider.ts b/packages/local-sandbox/src/provider/LocalSandboxProvider.tsnew file mode 100644index 000000000..d2596a928--- /dev/null+++ b/packages/local-sandbox/src/provider/LocalSandboxProvider.ts@@ -0,0 +1,394 @@+/**+ * Local SRT SandboxProvider. Code Mode UDS is handle-scoped via {@link CodeModeUdsTransport}.+ */+import type {+ CodeModeTransport,+ ExecResult,+ SandboxBuild,+ SandboxExecParams,+ SandboxProvider,+} from '@truefoundry/trueforge-core/core';+import {+ SandboxFileNotFoundError,+ SandboxFileTooLargeError,+ SandboxPathIsDirectoryError,+ shellEscape,+ validateNoPathTraversal,+} from '@truefoundry/trueforge-core/core';+import { mkdir, mkdtemp } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, isAbsolute, join, resolve, sep } from 'node:path';+import { ulid } from 'ulid';+import { CodeModeUdsTransport, assertCodeModeSocketParentPath } from '../core/CodeModeUdsTransport.js';+import {+ createSandbox,+ initSrt,+ isSrtInitialized,+ removeSandbox,+ resetSrt,+ resolveCommandOnHost,+ runSupervisorSession,+ type LocalSandboxPlatform,+} from '../core/hostRun.js';+import { XferFileInfoSchema, type XferFileInfo } from '../schemas/xferFileInfo.js';++const DEFAULT_EXEC_TIMEOUT_SECONDS = 60;+const DEFAULT_FILE_MAX_BYTES = 10 * 1024 * 1024;+/** Cap for isSupported shell/Python probes (not general exec). */+const SUPPORT_PROBE_TIMEOUT_MS = 5_000;++/** Command names resolved via `command -v` (PATH from sandbox policy). */+const SHELL_CANDIDATES = ['bash', 'sh'] as const;+const PYTHON_CANDIDATES = ['python3', 'python'] as const;++export type { LocalSandboxPlatform };++export type LocalSandboxSupportResult =+ | { supported: true; platform: LocalSandboxPlatform; shell: string; python: string }+ | { supported: false; reason: string };++type LocalSandboxSupported = Extract<LocalSandboxSupportResult, { supported: true }>;++export interface LocalSandboxProviderOptions {+ /** Absolute parent directory under which each createSandbox makes a ULID child root. */+ sandboxRootPathParent: string;+ /**+ * Absolute existing directory for Code Mode UDS (≤60 bytes, mode 0700). Caller owns its lifetime.+ * Transport chmod's the parent to 0700 and each sock to 0600 after listen.+ */+ codeModeSocketParentPath: string;+ /** Result of {@link LocalSandboxProvider.isSupported}; must be `{ supported: true }`. */+ support: LocalSandboxSupportResult;+ fileMaxBytesForDownload?: number | undefined;+ defaultExecTimeoutSeconds?: number | undefined;+}++/** Sandbox-relative path for sandboxed commands (avoids /var vs /private/var seatbelt mismatches). */+function sandboxRelativePath(userPath: string): string {+ return userPath.replace(/^\.\/+/, '');+}++export class LocalSandboxProvider implements SandboxProvider {+ private readonly sandboxRootPathParent: string;+ private readonly codeModeSocketParentPath: string;+ private readonly support: LocalSandboxSupported;+ private readonly fileMaxBytesForDownload: number;+ private readonly defaultExecTimeoutSeconds: number;+ private srtInitialized = false;++ /** Local SRT has no image build step — always ready. */+ private static readonly readyBuild: SandboxBuild = {+ status: 'ready',+ reason: null,+ metadata: null,+ };++ /**+ * Probe whether this host can run LocalSandboxProvider (OS + in-sandbox shell + Python 3).+ * On success, returns platform/shell/python to pass into the constructor as `support`.+ */+ static async isSupported(): Promise<LocalSandboxSupportResult> {+ if (process.platform !== 'darwin' && process.platform !== 'linux') {+ return {+ supported: false,+ reason: `LocalSandboxProvider supports macOS and Linux only (got ${process.platform})`,+ };+ }+ const platform: LocalSandboxPlatform = process.platform;++ const alreadyInitialized = isSrtInitialized();+ let probeRoot: string | undefined;++ try {+ if (!alreadyInitialized) {+ await initSrt({ platform });+ }++ probeRoot = await createSandbox(await mkdtemp(join(tmpdir(), 'tfy-local-sandbox-support-')));++ let shell: string | undefined;+ for (const name of SHELL_CANDIDATES) {+ const resolved = await resolveCommandOnHost({ platform, name });+ if (resolved === undefined) continue;+ const probe = await runSupervisorSession({+ sandboxRootPath: probeRoot,+ platform,+ shell: resolved,+ command: 'echo shell-ok',+ timeoutMs: SUPPORT_PROBE_TIMEOUT_MS,+ });+ if (probe.protocolError === undefined && probe.exitCode === 0 && probe.stdoutText.includes('shell-ok')) {+ shell = resolved;+ break;+ }+ }+ if (shell === undefined) {+ return {+ supported: false,+ reason: 'No usable shell in sandbox (bash or sh via command -v)',+ };+ }++ let python: string | undefined;+ for (const name of PYTHON_CANDIDATES) {+ const resolved = await resolveCommandOnHost({ platform, name });+ if (resolved === undefined) continue;+ const probe = await runSupervisorSession({+ sandboxRootPath: probeRoot,+ platform,+ shell,+ command: `${shellEscape(resolved)} -c ${shellEscape(+ 'import sys; raise SystemExit(0 if sys.version_info[0] == 3 else 1)',+ )}`,+ timeoutMs: SUPPORT_PROBE_TIMEOUT_MS,+ });+ if (probe.protocolError === undefined && probe.exitCode === 0) {+ python = resolved;+ break;+ }+ }+ if (python === undefined) {+ return {+ supported: false,+ reason: 'No usable Python 3 interpreter in sandbox (python3 or python via command -v)',+ };+ }++ return { supported: true, platform, shell, python };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return { supported: false, reason: message };+ } finally {+ if (probeRoot !== undefined) {+ await removeSandbox(probeRoot);+ }+ if (!alreadyInitialized) {+ await resetSrt();+ }+ }+ }++ constructor(options: LocalSandboxProviderOptions) {+ if (!options.support.supported) {+ throw new Error(`LocalSandboxProvider is not supported: ${options.support.reason}`);+ }+ if (!isAbsolute(options.sandboxRootPathParent)) {+ throw new Error('sandboxRootPathParent must be an absolute path');+ }+ validateNoPathTraversal(options.sandboxRootPathParent);+ this.sandboxRootPathParent = resolve(options.sandboxRootPathParent);+ // Same validation as CodeModeUdsTransport (absolute, exists, ≤60 bytes, realpath).+ this.codeModeSocketParentPath = assertCodeModeSocketParentPath(options.codeModeSocketParentPath);+ this.support = options.support;+ this.fileMaxBytesForDownload = options.fileMaxBytesForDownload ?? DEFAULT_FILE_MAX_BYTES;+ this.defaultExecTimeoutSeconds = options.defaultExecTimeoutSeconds ?? DEFAULT_EXEC_TIMEOUT_SECONDS;+ }++ private pythonC(code: string, relPath: string): string {+ return `${this.support.python} -c ${shellEscape(code)} ${shellEscape(relPath)}`;+ }++ private statCommand(relPath: string): string {+ const code = [+ 'import json, os, sys',+ 'p = sys.argv[1]',+ 'st = os.stat(p)',+ 'print(json.dumps({"size": st.st_size, "isDir": os.path.isdir(p)}))',+ ].join('\n');+ return this.pythonC(code, relPath);+ }++ private base64EncodeCommand(relPath: string): string {+ const code = [+ 'import base64, sys',+ 'p = sys.argv[1]',+ 'sys.stdout.write(base64.b64encode(open(p, "rb").read()).decode("ascii"))',+ ].join('\n');+ return this.pythonC(code, relPath);+ }++ buildImage(): Promise<SandboxBuild> {+ return Promise.resolve(LocalSandboxProvider.readyBuild);+ }++ getImageBuildStatus(): Promise<SandboxBuild> {+ return Promise.resolve(LocalSandboxProvider.readyBuild);+ }++ private async ensureSrt(): Promise<void> {+ if (this.srtInitialized) return;+ await initSrt({ platform: this.support.platform });+ this.srtInitialized = true;+ }++ private resolveInSandboxRoot(sandboxRootPath: string, userPath: string): string {+ validateNoPathTraversal(userPath);+ const resolved = userPath.startsWith('/') ? resolve(userPath) : resolve(sandboxRootPath, userPath);+ const root = resolve(sandboxRootPath);+ if (resolved !== root && !resolved.startsWith(root + sep)) {+ throw new SandboxFileNotFoundError(userPath);+ }+ return resolved;+ }++ private async runSandboxCommand(params: {+ sandboxRootPath: string;+ command: string;+ stdin?: Buffer;+ }): Promise<{ exitCode: number; stdoutText: string; stderrText: string }> {+ const session = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ platform: this.support.platform,+ shell: this.support.shell,+ command: params.command,+ ...(params.stdin === undefined ? {} : { stdin: params.stdin }),+ timeoutMs: this.defaultExecTimeoutSeconds * 1000,+ });+ if (session.protocolError !== undefined) {+ throw new Error(session.protocolError);+ }+ return {+ exitCode: session.exitCode,+ stdoutText: session.stdoutText,+ stderrText: session.stderrText,+ };+ }++ private async getFileInfo(params: {+ sandboxRootPath: string;+ relPath: string;+ userPath: string;+ }): Promise<XferFileInfo> {+ const result = await this.runSandboxCommand({+ sandboxRootPath: params.sandboxRootPath,+ command: this.statCommand(params.relPath),+ });+ if (result.exitCode !== 0) {+ throw new SandboxFileNotFoundError(params.userPath);+ }+ return XferFileInfoSchema.parse(JSON.parse(result.stdoutText.trim()));+ }++ async createSandbox(): Promise<{ sandboxId: string }> {+ await this.ensureSrt();+ const sandboxId = await createSandbox(join(this.sandboxRootPathParent, ulid().toLowerCase()));+ await mkdir(join(sandboxId, 'tool-results'), { recursive: true, mode: 0o700 });+ await mkdir(join(sandboxId, 'uploads'), { recursive: true, mode: 0o700 });+ return { sandboxId };+ }++ async exec(params: SandboxExecParams): Promise<ExecResult> {+ try {+ await this.ensureSrt();+ const sandboxRootPath = params.sandboxId;+ const cwd =+ params.cwd === undefined || params.cwd === ''+ ? sandboxRootPath+ : this.resolveInSandboxRoot(sandboxRootPath, params.cwd);+ const timeoutSeconds = params.timeoutSeconds ?? this.defaultExecTimeoutSeconds;+ const session = await runSupervisorSession({+ sandboxRootPath,+ platform: this.support.platform,+ shell: this.support.shell,+ command: params.command,+ cwd,+ ...(params.env === undefined ? {} : { env: params.env }),+ timeoutMs: timeoutSeconds * 1000,+ });+ if (session.protocolError !== undefined) {+ return { success: false, error: session.protocolError };+ }+ const result = session.stdoutText + (session.stderrText ? session.stderrText : '');+ return {+ success: true,+ response: { exitCode: session.exitCode, result },+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return { success: false, error: message };+ }+ }++ getAdditionalInstructions(): string {+ return [+ 'SANDBOX RULES:',+ `- Platform: ${this.support.platform}.`,+ `- Commands run under the sandbox shell: ${this.support.shell}.`,+ `- Python 3 is available as: ${this.support.python}. Prefer this binary for Python scripts.`,+ "- The Agent's first sandbox command should be `pwd` to discover the working directory.",+ '- ALL file creation and writes MUST stay within that working directory.',+ '- The Agent must NOT write outside the working directory (including host home and /tmp).',+ ].join('\n');+ }++ getToolResultDumpDir(sandboxId: string): string {+ return join(sandboxId, 'tool-results');+ }++ getGitCredentialsPath(sandboxId: string): string {+ return join(sandboxId, '.git-credentials');+ }++ async downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer> {+ await this.ensureSrt();+ const sandboxRootPath = params.sandboxId;+ this.resolveInSandboxRoot(sandboxRootPath, params.path);+ const relPath = sandboxRelativePath(params.path);+ const info = await this.getFileInfo({ sandboxRootPath, relPath, userPath: params.path });+ if (info.isDir) {+ throw new SandboxPathIsDirectoryError(params.path);+ }+ if (info.size > this.fileMaxBytesForDownload) {+ throw new SandboxFileTooLargeError(params.path, info.size, this.fileMaxBytesForDownload);+ }+ const result = await this.runSandboxCommand({+ sandboxRootPath,+ command: this.base64EncodeCommand(relPath),+ });+ if (result.exitCode !== 0) {+ throw new SandboxFileNotFoundError(params.path);+ }+ const buf = Buffer.from(result.stdoutText.trim(), 'base64');+ if (buf.length > this.fileMaxBytesForDownload) {+ throw new SandboxFileTooLargeError(params.path, buf.length, this.fileMaxBytesForDownload);+ }+ return buf;+ }++ /** Payload on stdin so large uploads stay off argv. */+ async uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void> {+ await this.ensureSrt();+ if (params.content.length > this.fileMaxBytesForDownload) {+ throw new SandboxFileTooLargeError(params.remotePath, params.content.length, this.fileMaxBytesForDownload);+ }+ const sandboxRootPath = params.sandboxId;+ // Resolve for traversal checks, but pass sandbox-relative paths to the shell.+ // Absolute /var/folders/... paths lose quoting under SRT and become mkdir /var.+ this.resolveInSandboxRoot(sandboxRootPath, params.remotePath);+ const remotePath = sandboxRelativePath(params.remotePath);+ const parent = dirname(remotePath);+ const mkdirPart = parent === '.' ? '' : `mkdir -p ${shellEscape(parent)} && `;+ const result = await this.runSandboxCommand({+ sandboxRootPath,+ command: `${mkdirPart}cat > ${shellEscape(remotePath)}`,+ stdin: params.content,+ });+ if (result.exitCode !== 0) {+ throw new SandboxFileNotFoundError(params.remotePath);+ }+ }++ createCodeModeTransport(): CodeModeTransport {+ return new CodeModeUdsTransport({+ codeModeSocketParentPath: this.codeModeSocketParentPath,+ });+ }++ /** Reset process-scoped SRT for this provider. */+ async dispose(): Promise<void> {+ if (this.srtInitialized) {+ await resetSrt();+ this.srtInitialized = false;+ }+ }+}diff --git a/packages/local-sandbox/src/schemas/jsonMessage.ts b/packages/local-sandbox/src/schemas/jsonMessage.tsnew file mode 100644index 000000000..5d95b9e6d--- /dev/null+++ b/packages/local-sandbox/src/schemas/jsonMessage.ts@@ -0,0 +1,4 @@+/** Code Mode UDS JSON payload after JSON.parse (any JSON value). */+import { z } from 'zod';++export const JsonMessageValueSchema = z.json();diff --git a/packages/local-sandbox/src/schemas/xferFileInfo.ts b/packages/local-sandbox/src/schemas/xferFileInfo.tsnew file mode 100644index 000000000..18e50d463--- /dev/null+++ b/packages/local-sandbox/src/schemas/xferFileInfo.ts@@ -0,0 +1,8 @@+/** `stat` / xfer probe output from sandboxed python. */+import { z } from 'zod';++export const XferFileInfoSchema = z.object({+ size: z.number(),+ isDir: z.boolean(),+});+export type XferFileInfo = z.infer<typeof XferFileInfoSchema>;diff --git a/packages/local-sandbox/test/codeModeUdsTransport.contract.test.ts b/packages/local-sandbox/test/codeModeUdsTransport.contract.test.tsnew file mode 100644index 000000000..c67d47946--- /dev/null+++ b/packages/local-sandbox/test/codeModeUdsTransport.contract.test.ts@@ -0,0 +1,149 @@+/**+ * Node UDS binder for the harness Code Mode transport contract suite.+ * Lives in local-sandbox only — no product/server import of this package.+ */+import {+ CodeModeDispatcher,+ CodeModeReplySchema,+ type CodeModeReply,+ type CodeModeRequest,+ type IToolSet,+} from '@truefoundry/trueforge-core/core';+import { mkdir } from 'node:fs/promises';+import { createConnection } from 'node:net';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ runCodeModeTransportContractSuite,+ type CodeModeTransportContractFixture,+} from '../../harness/tests/core/sandbox/codeMode/codeModeTransportContractSuite';+import { CodeModeUdsTransport } from '../src/core/CodeModeUdsTransport.js';+import { encodeJsonMessage, JsonMessageReader, MAX_MESSAGE_BYTES } from '../src/core/frame.js';++function makeSilentLogger() {+ const logger = {+ error: () => undefined,+ child: () => logger,+ };+ return logger;+}++function makeDemoToolSet(): IToolSet {+ return {+ name: 'demo',+ id: 'demo',+ preload: true,+ hasPreloadedTools: true,+ listTools: () =>+ Promise.resolve({+ result: {+ tools: [+ {+ name: 'ping',+ description: 'ping',+ inputSchema: { type: 'object' as const, properties: {} },+ preload: true,+ },+ ],+ },+ wasInitialized: undefined,+ }),+ callTool: () =>+ Promise.resolve({+ result: { content: [{ type: 'text' as const, text: 'ok' }], isError: false },+ wasInitialized: undefined,+ }),+ toolCallInfo: () => undefined,+ };+}++function resolveSockPath(env: Record<string, string>): string {+ const sock = env['TFY_MCP_SOCK'];+ if (sock === undefined || sock === '') {+ throw new Error('TFY_MCP_SOCK missing from transport env');+ }+ return sock;+}++function sendUdsRequest(params: { env: Record<string, string>; request: CodeModeRequest }): Promise<CodeModeReply> {+ const path = resolveSockPath(params.env);+ const timeoutSeconds = Number(params.env['TFY_CM_REQUEST_TIMEOUT_SECONDS'] ?? '30');+ const timeoutMs = Number.isFinite(timeoutSeconds) ? timeoutSeconds * 1000 : 30_000;++ return new Promise((resolve, reject) => {+ const socket = createConnection({ path, allowHalfOpen: true });+ const reader = new JsonMessageReader({ maxBytes: MAX_MESSAGE_BYTES });+ let settled = false;++ const finish = (error: Error | undefined, reply?: CodeModeReply): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ socket.destroy();+ if (error) reject(error);+ else if (reply !== undefined) resolve(reply);+ else reject(new Error('missing reply'));+ };++ const timer = setTimeout(() => {+ finish(new Error(`UDS request timed out after ${String(timeoutMs)}ms`));+ }, timeoutMs);++ socket.on('error', error => {+ finish(error);+ });+ socket.on('data', (chunk: Buffer) => {+ try {+ reader.push(chunk);+ } catch (error) {+ finish(error instanceof Error ? error : new Error(String(error)));+ }+ });+ socket.on('end', () => {+ try {+ const parsed = CodeModeReplySchema.safeParse(reader.finish());+ if (!parsed.success) {+ finish(new Error('malformed Code Mode reply'));+ return;+ }+ finish(undefined, parsed.data);+ } catch (error) {+ finish(error instanceof Error ? error : new Error(String(error)));+ }+ });+ socket.on('connect', () => {+ const body = encodeJsonMessage(params.request);+ socket.write(body, writeErr => {+ if (writeErr) {+ finish(writeErr);+ return;+ }+ socket.end();+ });+ });+ });+}++runCodeModeTransportContractSuite(async (): Promise<CodeModeTransportContractFixture> => {+ const codeModeSocketParentPath = join(tmpdir(), 'cm');+ await mkdir(codeModeSocketParentPath, { recursive: true, mode: 0o700 });+ const transport = new CodeModeUdsTransport({+ codeModeSocketParentPath,+ });+ const dispatcher = new CodeModeDispatcher({+ toolSets: [makeDemoToolSet()],+ logger: makeSilentLogger(),+ });++ return {+ transport,+ dispatcher,+ sandboxId: 'contract-sandbox',+ requestTimeoutSeconds: 30,+ sendRequest: ({ env, request }) => sendUdsRequest({ env, request }),+ dispose: async () => {+ dispatcher.close();+ await transport.stop();+ },+ };+});diff --git a/packages/local-sandbox/test/provider/contract.test.ts b/packages/local-sandbox/test/provider/contract.test.tsnew file mode 100644index 000000000..051a399b0--- /dev/null+++ b/packages/local-sandbox/test/provider/contract.test.ts@@ -0,0 +1,30 @@+import { mkdir, mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runSandboxProviderContractSuite } from '../../../harness/tests/core/sandbox/provider/sandboxProviderContractSuite';+import { LocalSandboxProvider } from '../../src/provider/LocalSandboxProvider';++describe('LocalSandboxProvider (SandboxProvider contract)', () => {+ runSandboxProviderContractSuite(async () => {+ const support = await LocalSandboxProvider.isSupported();+ if (!support.supported) {+ throw new Error(support.reason);+ }+ const sandboxRootPathParent = await mkdtemp(join(tmpdir(), 'tfy-local-sandbox-contract-'));+ // Short path: macOS tmpdir ~48 bytes; keep parent ≤60 for Code Mode UDS.+ const codeModeSocketParentPath = join(tmpdir(), 'cm');+ await mkdir(codeModeSocketParentPath, { recursive: true, mode: 0o700 });+ const provider = new LocalSandboxProvider({+ sandboxRootPathParent,+ codeModeSocketParentPath,+ support,+ });+ return {+ provider,+ dispose: async () => {+ await provider.dispose();+ await rm(sandboxRootPathParent, { recursive: true, force: true });+ },+ };+ });+});diff --git a/packages/local-sandbox/test/smoke.test.ts b/packages/local-sandbox/test/smoke.test.tsnew file mode 100644index 000000000..eeab2a57e--- /dev/null+++ b/packages/local-sandbox/test/smoke.test.ts@@ -0,0 +1,1944 @@+/**+ * LocalSandboxProvider smoke (macOS host or Linux via Lima)+ * plus Code Mode UDS and security probes. Run via `pnpm smoke`.+ */+import { getDefaultWritePaths, SandboxManager } from '@anthropic-ai/sandbox-runtime';+import { CodeModeDispatcher, type IToolSet } from '@truefoundry/trueforge-core/core';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { access, mkdir, mkdtemp, readFile, realpath, rm, stat, unlink, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { createServer } from 'node:net';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { ulid } from 'ulid';+import { CodeModeUdsTransport } from '../src/core/CodeModeUdsTransport.js';+import {+ commandPath,+ createSandbox,+ installMcpFixture,+ MAX_OUTPUT_BYTES,+ platformAllowRead,+ registerCodeModeSocketPath,+ removeSandbox,+ runSupervisorSession,+ unregisterCodeModeSocketPath,+} from '../src/core/hostRun.js';+import { LocalSandboxProvider } from '../src/provider/LocalSandboxProvider.js';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const SANDBOXES = join(ROOT, 'sandboxes');+const DENY_READ_SECRET = join(SANDBOXES, '.poc-deny-read-secret');+const DEFAULT_TMP_CLAUDE = '/tmp/claude';+const DELETE_TARGET = join(DEFAULT_TMP_CLAUDE, 'poc-delete-target.txt');+const SECRET_CONTENTS = 'host-secret-should-not-leak\n';+const HOST_HOME = process.env['HOME'];+const ENV_LEAK_MARKER = 'TFY_SMOKE_HOST_SECRET';+const ENV_LEAK_VALUE = 'host-env-must-not-reach-sandbox';+const ENV_INHERIT_MARKER = 'TFY_SMOKE_INHERIT';+const ENV_INHERIT_VALUE = `inherit-${randomUUID()}`;+const ENV_PEER_MARKER = 'TFY_SMOKE_PEER_ENV';+const ENV_PEER_VALUE = `peer-secret-${randomUUID()}`;+// Package-root resolve: Jest's CJS transform breaks import.meta.resolve.+const SRT_VENDOR = join(+ dirname(createRequire(import.meta.url).resolve('@anthropic-ai/sandbox-runtime/package.json')),+ 'vendor',+);+async function prepareHostProbeFiles(): Promise<void> {+ await mkdir(DEFAULT_TMP_CLAUDE, { recursive: true, mode: 0o700 });+ await mkdir(SANDBOXES, { recursive: true, mode: 0o700 });+ await writeFile(DELETE_TARGET, 'delete-me\n', { mode: 0o600 });+ await writeFile(DENY_READ_SECRET, SECRET_CONTENTS, { mode: 0o600 });+}++async function cleanupHostProbeFiles(): Promise<void> {+ await rm(DELETE_TARGET, { force: true });+ await rm(DENY_READ_SECRET, { force: true });+}++function sleep(ms: number): Promise<void> {+ return new Promise(resolve => {+ setTimeout(resolve, ms);+ });+}++/**+ * Direct check: after initSrt, registerCodeModeSocketPath → updateConfig must+ * allow a sandboxed client to connect to that exact sock (and unregister revoke it).+ */+async function smokeLiveSrtUnixSocketAllowlistUpdate(params: {+ sandboxRootPath: string;+ codeModeSocketParentPath: string;+ shell: string;+ platform: 'darwin' | 'linux';+}): Promise<void> {+ const parent = await realpath(params.codeModeSocketParentPath);+ const sockPath = join(parent, ulid().toLowerCase());+ await unlink(sockPath).catch(() => undefined);++ const server = createServer();+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(sockPath, () => {+ server.off('error', reject);+ resolve();+ });+ });+ server.on('connection', socket => {+ socket.end();+ });++ const connectCmd = [+ "python3 - <<'PY'",+ 'import socket, sys',+ `path = ${JSON.stringify(sockPath)}`,+ 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ 'try:',+ ' s.connect(path)',+ ' print("connected")',+ 'except OSError as e:',+ ' print(type(e).__name__, e, file=sys.stderr)',+ ' sys.exit(1)',+ 'finally:',+ ' s.close()',+ 'PY',+ ].join('\n');++ try {+ const before = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: connectCmd,+ timeoutMs: 10_000,+ });+ assert.notEqual(before.exitCode, 0, 'connect must fail before register/updateConfig');+ assert.ok(!before.stdoutText.includes('connected'));++ registerCodeModeSocketPath(sockPath);++ const afterRegister = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: connectCmd,+ timeoutMs: 10_000,+ });+ assert.equal(afterRegister.exitCode, 0, afterRegister.stderrText);+ assert.match(afterRegister.stdoutText, /connected/);++ unregisterCodeModeSocketPath(sockPath);++ const afterUnregister = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: connectCmd,+ timeoutMs: 10_000,+ });+ assert.notEqual(afterUnregister.exitCode, 0, 'connect must fail after unregister/updateConfig');+ assert.ok(!afterUnregister.stdoutText.includes('connected'));++ console.log('ok: live SRT updateConfig allowlists exact Code Mode sock (register/unregister)');+ } finally {+ unregisterCodeModeSocketPath(sockPath);+ await new Promise<void>(resolve => {+ server.close(() => {+ resolve();+ });+ });+ await unlink(sockPath).catch(() => undefined);+ }+}++function pidAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+}++function makeSilentCodeModeLogger() {+ const logger = {+ error: () => undefined,+ child: () => logger,+ };+ return logger;+}++function makeDemoToolSet(params: { onRequest?: () => void }): IToolSet {+ return {+ name: 'demo',+ id: 'demo',+ preload: true,+ hasPreloadedTools: true,+ listTools: () => {+ params.onRequest?.();+ return Promise.resolve({+ result: {+ tools: [+ {+ name: 'ping',+ description: 'ping',+ inputSchema: { type: 'object' as const, properties: {} },+ preload: true,+ },+ ],+ },+ wasInitialized: undefined,+ });+ },+ callTool: async request => {+ params.onRequest?.();+ const args = request.arguments ?? {};+ const delayRaw = args['delay_ms'];+ const delayMs = typeof delayRaw === 'number' && Number.isFinite(delayRaw) ? delayRaw : 0;+ if (delayMs > 0) await sleep(delayMs);+ return {+ result: {+ content: [{ type: 'text' as const, text: JSON.stringify({ echo: args }) }],+ isError: false,+ },+ wasInitialized: undefined,+ };+ },+ toolCallInfo: () => undefined,+ };+}++async function withCodeModeTransport(params: {+ codeModeSocketParentPath: string;+ maxMessageBytes?: number;+ onProtocolError?: (message: string) => void;+ onRequest?: () => void;+ run: (env: Record<string, string>) => Promise<void>;+}): Promise<void> {+ const transport = new CodeModeUdsTransport({+ codeModeSocketParentPath: params.codeModeSocketParentPath,+ ...(params.maxMessageBytes === undefined ? {} : { maxMessageBytes: params.maxMessageBytes }),+ ...(params.onProtocolError === undefined ? {} : { onProtocolError: params.onProtocolError }),+ });+ const dispatcher = new CodeModeDispatcher({+ toolSets: [makeDemoToolSet({ onRequest: params.onRequest })],+ logger: makeSilentCodeModeLogger(),+ });+ try {+ const { env } = await transport.start({+ codeModeDispatcher: dispatcher,+ sandboxId: 'smoke',+ requestTimeoutSeconds: 60,+ });+ await params.run(env);+ } finally {+ dispatcher.close();+ await transport.stop();+ }+}++async function smokeCodeMode(params: {+ sandboxRootPath: string;+ codeModeSocketParentPath: string;+ shell: string;+ platform: 'darwin' | 'linux';+}): Promise<void> {+ await installMcpFixture(params.sandboxRootPath);+ let toolRequests = 0;++ await withCodeModeTransport({+ codeModeSocketParentPath: params.codeModeSocketParentPath,+ onRequest: () => {+ toolRequests += 1;+ },+ run: async env => {+ const sockPath = env['TFY_MCP_SOCK'];+ assert.ok(sockPath !== undefined && sockPath.length > 0);+ const sockStat = await stat(sockPath);+ assert.equal(sockStat.mode & 0o777, 0o600, `Code Mode sock must be 0600: ${sockPath}`);+ const parentStat = await stat(params.codeModeSocketParentPath);+ assert.equal(+ parentStat.mode & 0o777,+ 0o700,+ `Code Mode sock parent must be 0700: ${params.codeModeSocketParentPath}`,+ );+ console.log('ok: Code Mode UDS parent 0700 + sock 0600');++ const list = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: 'python3 mcp_pipe_client.py list-tools --server demo',+ env,+ timeoutMs: 15_000,+ });+ assert.equal(list.protocolError, undefined, list.protocolError);+ assert.equal(list.exitCode, 0, list.stderrText);+ assert.match(list.stdoutText, /list-tools-ok/);+ console.log('ok: Code Mode list-tools (UDS)');+ },+ });++ const oversizeCap = 1024;+ let oversizeError: string | undefined;+ await withCodeModeTransport({+ codeModeSocketParentPath: params.codeModeSocketParentPath,+ maxMessageBytes: oversizeCap,+ onProtocolError: message => {+ oversizeError = message;+ },+ run: async env => {+ const oversize = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: [+ "python3 - <<'PY'",+ 'import os, socket, time',+ 'path = os.environ["TFY_MCP_SOCK"]',+ 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ 's.connect(path)',+ `s.sendall(b"x" * ${String(oversizeCap + 1)})`,+ 's.shutdown(socket.SHUT_WR)',+ 'time.sleep(1)',+ 'PY',+ ].join('\n'),+ env,+ timeoutMs: 10_000,+ });+ assert.equal(oversize.exitCode, 0, oversize.stderrText);+ assert.match(String(oversizeError), /exceeds max/);+ console.log('ok: Code Mode oversized message is terminal');+ },+ });++ let badJsonError: string | undefined;+ await withCodeModeTransport({+ codeModeSocketParentPath: params.codeModeSocketParentPath,+ onProtocolError: message => {+ badJsonError = message;+ },+ run: async env => {+ const badJson = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: [+ "python3 - <<'PY'",+ 'import os, socket, time',+ 'path = os.environ["TFY_MCP_SOCK"]',+ 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ 's.connect(path)',+ 's.sendall(b"not")',+ 's.shutdown(socket.SHUT_WR)',+ 'time.sleep(1)',+ 'PY',+ ].join('\n'),+ env,+ timeoutMs: 10_000,+ });+ assert.equal(badJson.exitCode, 0, badJson.stderrText);+ assert.match(String(badJsonError), /invalid JSON message/);+ console.log('ok: Code Mode malformed JSON message is terminal');+ },+ });++ await withCodeModeTransport({+ codeModeSocketParentPath: params.codeModeSocketParentPath,+ onRequest: () => {+ toolRequests += 1;+ },+ run: async env => {+ const multiplex = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: 'python3 mcp_pipe_client.py multiplex --server demo --count 2',+ env,+ timeoutMs: 15_000,+ });+ assert.equal(multiplex.protocolError, undefined, multiplex.protocolError);+ assert.equal(multiplex.exitCode, 0, multiplex.stderrText);+ const multiplexMatch = /multiplex-ok (\d+)/.exec(multiplex.stdoutText);+ assert.ok(multiplexMatch, multiplex.stdoutText);+ const multiplexMs = Number(multiplexMatch[1]);+ assert.ok(multiplexMs < 280, `multiplex looked serial: gather ${String(multiplexMs)}ms (expected < 280ms)`);+ console.log('ok: Code Mode concurrent UDS multiplex', `${String(multiplexMs)}ms`);+ },+ });++ const beforeMissing = toolRequests;+ await withCodeModeTransport({+ codeModeSocketParentPath: params.codeModeSocketParentPath,+ onRequest: () => {+ toolRequests += 1;+ },+ run: async env => {+ const missingSock = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: [+ 'set -euo pipefail',+ 'unset TFY_MCP_SOCK',+ 'if python3 mcp_pipe_client.py list-tools --server demo; then',+ ' echo "expected missing-sock failure" >&2',+ ' exit 1',+ 'fi',+ 'echo ok-missing-sock',+ ].join('\n'),+ env,+ timeoutMs: 10_000,+ });+ assert.equal(missingSock.exitCode, 0, missingSock.stderrText);+ assert.match(missingSock.stdoutText, /ok-missing-sock/);+ assert.equal(toolRequests, beforeMissing, 'missing sock must not deliver tool requests');+ console.log('ok: Code Mode requires TFY_MCP_SOCK');+ },+ });++ let hostInjected = 0;+ let holdPid: number | undefined;+ await withCodeModeTransport({+ codeModeSocketParentPath: params.codeModeSocketParentPath,+ onRequest: () => {+ hostInjected += 1;+ },+ run: async env => {+ const holdSession = runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: [+ 'set -euo pipefail',+ "python3 - <<'PY'",+ 'import os, time',+ 'open(".uds-ready", "w").write(os.environ["TFY_MCP_SOCK"] + "\\n")',+ 'time.sleep(60)',+ 'PY',+ ].join('\n'),+ env,+ onChildSpawn: pid => {+ holdPid = pid;+ },+ timeoutMs: 15_000,+ });+ let sockFromSandbox = '';+ for (let i = 0; i < 80 && sockFromSandbox === ''; i++) {+ try {+ sockFromSandbox = (await readFile(join(params.sandboxRootPath, '.uds-ready'), 'utf8')).trim();+ } catch {+ await sleep(50);+ }+ }+ assert.match(sockFromSandbox, /^\//, 'sandbox never published absolute TFY_MCP_SOCK');+ const hostSockPath = sockFromSandbox.startsWith('/')+ ? sockFromSandbox+ : join(params.sandboxRootPath, sockFromSandbox);+ const hostConnect = await new Promise<{ code: number | null; err: string }>((resolve, reject) => {+ const child = spawn(+ 'python3',+ [+ '-c',+ [+ 'import os, socket, sys, json',+ 'path = sys.argv[1]',+ 'req = {"op":"list_tools","server":"demo"}',+ 'body = json.dumps(req).encode()',+ 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ 'if len(path.encode()) >= 104:',+ ' os.chdir(os.path.dirname(path))',+ ' path = os.path.basename(path)',+ 's.connect(path)',+ 's.sendall(body)',+ 's.shutdown(socket.SHUT_WR)',+ 'chunks = []',+ 'while True:',+ ' c = s.recv(65536)',+ ' if not c: break',+ ' chunks.append(c)',+ 'print(b"".join(chunks).decode())',+ ].join('\n'),+ hostSockPath,+ ],+ { stdio: ['ignore', 'pipe', 'pipe'] },+ );+ let err = '';+ child.stderr?.on('data', (c: Buffer) => {+ err += c.toString('utf8');+ });+ child.on('error', reject);+ child.on('close', code => resolve({ code, err }));+ });+ assert.equal(hostConnect.code, 0, hostConnect.err);+ for (let i = 0; i < 50 && hostInjected === 0; i++) {+ await sleep(50);+ }+ assert.equal(hostInjected, 1, 'same-UID host connect to Code Mode UDS must work');+ console.log('ok: same-UID host can connect to Code Mode UDS (expected for path UDS)');+ if (holdPid !== undefined) {+ try {+ process.kill(-holdPid, 'SIGKILL');+ } catch {+ try {+ process.kill(holdPid, 'SIGKILL');+ } catch {+ // already gone+ }+ }+ }+ await holdSession;+ },+ });+}++/**+ * Prove Unix env inheritance with no explicit env= copying:+ * 1) curated exec env → python child → python grandchild+ * 2) bash `cmd1 & cmd2` — both jobs are shell children and must see the marker+ */+async function smokeEnvInheritance(provider: LocalSandboxProvider, sandboxId: string): Promise<void> {+ const pyResult = await provider.exec({+ sandboxId,+ env: { [ENV_INHERIT_MARKER]: ENV_INHERIT_VALUE },+ command: [+ "python3 - <<'PY'",+ 'import os, subprocess, sys',+ `marker = ${JSON.stringify(ENV_INHERIT_MARKER)}`,+ `expected = ${JSON.stringify(ENV_INHERIT_VALUE)}`,+ 'child_val = os.environ.get(marker)',+ 'if child_val != expected:',+ ' print(f"child-missing:{child_val!r}", file=sys.stderr)',+ ' raise SystemExit(1)',+ '# Grandchild: subprocess with default env inheritance (no env= override).',+ 'grand = subprocess.run(',+ ' [sys.executable, "-c", f"import os; print(os.environ[{marker!r}])"],',+ ' check=True,',+ ' capture_output=True,',+ ' text=True,',+ ')',+ 'got = grand.stdout.strip()',+ 'if got != expected:',+ ' print(f"grandchild-missing:{got!r}", file=sys.stderr)',+ ' raise SystemExit(1)',+ 'print("env-inherit-ok", expected)',+ 'PY',+ ].join('\n'),+ });+ assert.equal(pyResult.success, true, JSON.stringify(pyResult));+ if (!pyResult.success) throw new Error('unreachable');+ assert.equal(pyResult.response.exitCode, 0, pyResult.response.result);+ assert.match(pyResult.response.result, new RegExp(`env-inherit-ok ${ENV_INHERIT_VALUE}`));+ console.log('ok: env auto-inherits parent → child → grandchild (no extra code)');++ // Background job + foreground job are both subprocesses of the exec shell.+ const marker = ENV_INHERIT_MARKER;+ const expected = ENV_INHERIT_VALUE;+ const bashResult = await provider.exec({+ sandboxId,+ env: { [marker]: expected },+ command: [+ // sandbox-local file (mktemp may target a denied host TMPDIR)+ 'bg_out="./.tfy-smoke-env-bg"',+ // command 1: background — writes marker value then exits+ `( printenv ${marker} > "$bg_out" ) &`,+ 'bg_pid=$!',+ // command 2: foreground — must see the same env+ `fg_val="$(printenv ${marker})"`,+ 'wait "$bg_pid"',+ 'bg_val="$(cat "$bg_out")"',+ 'rm -f "$bg_out"',+ `test "$fg_val" = ${JSON.stringify(expected)} || { echo "fg-missing:$fg_val" >&2; exit 1; }`,+ `test "$bg_val" = ${JSON.stringify(expected)} || { echo "bg-missing:$bg_val" >&2; exit 1; }`,+ `echo "env-bg-ok ${expected}"`,+ ].join('\n'),+ });+ assert.equal(bashResult.success, true, JSON.stringify(bashResult));+ if (!bashResult.success) throw new Error('unreachable');+ assert.equal(bashResult.response.exitCode, 0, bashResult.response.result);+ assert.match(bashResult.response.result, new RegExp(`env-bg-ok ${expected}`));+ console.log('ok: env auto-inherits to bash background + foreground jobs (cmd1 & cmd2)');+}++function runCapture(command: string, args: string[]): Promise<{ code: number | null; out: string }> {+ return new Promise((resolve, reject) => {+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });+ let out = '';+ child.stdout?.on('data', (c: Buffer) => {+ out += c.toString('utf8');+ });+ child.stderr?.on('data', (c: Buffer) => {+ out += c.toString('utf8');+ });+ child.on('error', reject);+ child.on('close', code => resolve({ code, out }));+ });+}++function assertPeerSecretAbsent(label: string, sample: string): void {+ assert.ok(+ !sample.includes(ENV_PEER_VALUE),+ `${label} unexpectedly exposed peer env secret:\n${sample.slice(0, 2000)}`,+ );+}++function assertPeerSecretPresent(label: string, sample: string): void {+ assert.ok(+ sample.includes(ENV_PEER_VALUE),+ `${label} did not expose peer env secret (expected same-UID visibility):\n${sample.slice(0, 2000)}`,+ );+}++/**+ * Prove kernel UDS peer credentials on accept:+ * - Linux: SO_PEERCRED → peer pid/uid/gid+ * - macOS: LOCAL_PEERPID + getpeereid → peer pid/uid/gid+ * Identity comes from the kernel, not from client-supplied fields.+ */+async function smokeUdsPeerCredentials(): Promise<void> {+ const sockPath = join(tmpdir(), `cm-pc-${ulid().toLowerCase().slice(0, 10)}`);+ await unlink(sockPath).catch(() => undefined);++ const script = [+ 'import ctypes, json, os, platform, socket, struct',+ `path = ${JSON.stringify(sockPath)}`,+ 'srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ 'try:',+ ' try: os.unlink(path)',+ ' except FileNotFoundError: pass',+ ' srv.bind(path)',+ ' srv.listen(1)',+ ' child = os.fork()',+ ' if child == 0:',+ ' c = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ ' c.connect(path)',+ ' c.sendall(b"hi")',+ ' try: c.recv(1)',+ ' except OSError: pass',+ ' c.close()',+ ' os._exit(0)',+ ' conn, _ = srv.accept()',+ ' _ = conn.recv(16)',+ ' if platform.system() == "Linux":',+ ' SO_PEERCRED = 17',+ " raw = conn.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, struct.calcsize('iii'))",+ " peer_pid, peer_uid, peer_gid = struct.unpack('iii', raw)",+ ' method = "SO_PEERCRED"',+ ' else:',+ ' SOL_LOCAL, LOCAL_PEERPID = 0, 2',+ ' raw = conn.getsockopt(SOL_LOCAL, LOCAL_PEERPID, 4)',+ " peer_pid = struct.unpack('I', raw)[0]",+ ' libc = ctypes.CDLL(None)',+ ' uid = ctypes.c_uint()',+ ' gid = ctypes.c_uint()',+ ' rc = libc.getpeereid(ctypes.c_int(conn.fileno()), ctypes.byref(uid), ctypes.byref(gid))',+ ' if rc != 0:',+ ' raise SystemExit(f"getpeereid failed rc={rc} errno={ctypes.get_errno()}")',+ ' peer_uid, peer_gid = uid.value, gid.value',+ ' method = "LOCAL_PEERPID+getpeereid"',+ ' conn.close()',+ ' os.waitpid(child, 0)',+ ' print(json.dumps({',+ ' "method": method,',+ ' "peer_pid": peer_pid,',+ ' "peer_uid": peer_uid,',+ ' "peer_gid": peer_gid,',+ ' "child_pid": child,',+ ' "self_uid": os.getuid(),',+ ' "self_gid": os.getgid(),',+ ' }))',+ 'finally:',+ ' srv.close()',+ ' try: os.unlink(path)',+ ' except FileNotFoundError: pass',+ ].join('\n');++ try {+ const probe = await runCapture('python3', ['-c', script]);+ assert.equal(probe.code, 0, probe.out);+ const line = probe.out.trim().split(/\r?\n/).filter(Boolean).at(-1);+ assert.ok(line !== undefined && line.length > 0, `empty peercred probe output: ${probe.out}`);+ const parsed: unknown = JSON.parse(line);+ assert.ok(parsed !== null && typeof parsed === 'object');+ assert.ok('method' in parsed && typeof parsed.method === 'string');+ assert.ok('peer_pid' in parsed && typeof parsed.peer_pid === 'number');+ assert.ok('peer_uid' in parsed && typeof parsed.peer_uid === 'number');+ assert.ok('peer_gid' in parsed && typeof parsed.peer_gid === 'number');+ assert.ok('child_pid' in parsed && typeof parsed.child_pid === 'number');+ assert.ok('self_uid' in parsed && typeof parsed.self_uid === 'number');+ assert.ok('self_gid' in parsed && typeof parsed.self_gid === 'number');+ assert.equal(parsed.peer_pid, parsed.child_pid, 'peer pid must match connecting child');+ assert.equal(parsed.peer_uid, parsed.self_uid, 'peer uid must match listener uid (same-UID connect)');+ assert.equal(parsed.peer_gid, parsed.self_gid, 'peer gid must match listener gid (same-UID connect)');+ if (process.platform === 'linux') {+ assert.equal(parsed.method, 'SO_PEERCRED');+ } else {+ assert.equal(parsed.method, 'LOCAL_PEERPID+getpeereid');+ }+ console.log(+ `ok: proved UDS peer credentials via ${parsed.method} (pid=${String(parsed.peer_pid)} uid=${String(parsed.peer_uid)} gid=${String(parsed.peer_gid)})`,+ );+ } finally {+ await unlink(sockPath).catch(() => undefined);+ }+}++/**+ * Same-UID peer env visibility (host processes, not sandbox policy).+ * Proves the easy leak path on each OS — not that env is protected.+ * - Linux: `/proc/<pid>/environ` contains the peer secret+ * - macOS: `ps -E -p <pid>` contains the peer secret; plain `ps -o command=` does not+ */+async function smokeSameUidEnvironRead(): Promise<void> {+ const holder = spawn(+ 'python3',+ ['-c', ['import os, time', 'print(os.getpid(), flush=True)', 'time.sleep(30)'].join('\n')],+ {+ env: {+ PATH: process.env['PATH'] ?? '/usr/bin:/bin',+ [ENV_PEER_MARKER]: ENV_PEER_VALUE,+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ );++ let pidLine = '';+ holder.stdout?.on('data', (chunk: Buffer) => {+ pidLine += chunk.toString('utf8');+ });++ try {+ for (let i = 0; i < 50 && !/^\d+/m.test(pidLine); i++) {+ await sleep(50);+ }+ const peerPid = Number(pidLine.trim().split(/\s+/)[0]);+ assert.ok(Number.isInteger(peerPid) && peerPid > 0, `holder pid missing: ${pidLine}`);++ if (process.platform === 'linux') {+ const environ = await readFile(`/proc/${String(peerPid)}/environ`);+ const decoded = environ.toString('utf8').replaceAll('\0', '\n');+ assertPeerSecretPresent('/proc/<pid>/environ', decoded);+ console.log('ok: proved Linux same-UID env leak via /proc/<pid>/environ');+ return;+ }++ // Prove macOS same-UID env is easy to read via the common `ps -E` path.+ const psPlain = await runCapture('ps', ['-p', String(peerPid), '-ww', '-o', 'command=']);+ assert.equal(psPlain.code, 0, `ps -o command= failed: ${psPlain.out}`);+ assertPeerSecretAbsent('ps -o command=', psPlain.out);++ const psE = await runCapture('ps', ['-E', '-p', String(peerPid), '-ww']);+ assert.equal(psE.code, 0, `ps -E failed: ${psE.out}`);+ assertPeerSecretPresent('ps -E -p', psE.out);+ assert.match(psE.out, new RegExp(`${ENV_PEER_MARKER}=${ENV_PEER_VALUE}`));+ console.log('ok: proved macOS same-UID env leak via ps -E (plain ps hid it)');+ } finally {+ holder.kill('SIGKILL');+ await new Promise<void>(resolve => {+ holder.on('close', () => resolve());+ setTimeout(resolve, 1000);+ });+ }+}++/**+ * Same-UID access to another process's pipe / socketpair ends (host, not SRT).+ * - Linux pipe: `open(/proc/<pid>/fd/N)` duplicates the fd+ * - Linux socketpair: `open(/proc/...)` fails (ENXIO); `pidfd_getfd` steals it+ * - macOS: no `/proc/<pid>/fd` (ENOENT)+ */+async function smokeSameUidInheritedFdAccess(): Promise<void> {+ const PIPE_SECRET = 'pipe-secret-marker';+ const SOCK_SECRET = 'sock-secret-marker';+ const script = [+ 'import ctypes, json, os, platform, socket, subprocess, sys',+ `PIPE_SECRET = ${JSON.stringify(PIPE_SECRET)}.encode()`,+ `SOCK_SECRET = ${JSON.stringify(SOCK_SECRET)}.encode()`,+ 'holder = subprocess.Popen(',+ ' [sys.executable, "-c",',+ ' "import os, socket, time\\n"',+ ' "r, w = os.pipe()\\n"',+ ' "os.write(w, " + repr(PIPE_SECRET) + ")\\n"',+ ' "a, b = socket.socketpair()\\n"',+ ' "b.sendall(" + repr(SOCK_SECRET) + ")\\n"',+ ' "print(os.getpid(), r, a.fileno(), flush=True)\\n"',+ ' "time.sleep(60)\\n"],',+ ' stdout=subprocess.PIPE, text=True,',+ ')',+ 'try:',+ ' line = holder.stdout.readline().strip()',+ ' parts = line.split()',+ ' if len(parts) != 3:',+ ' raise SystemExit(f"bad holder line: {line!r}")',+ ' pid, pipe_fd, sock_fd = map(int, parts)',+ ' if platform.system() != "Linux":',+ ' path = f"/proc/{pid}/fd/{pipe_fd}"',+ ' try:',+ ' open(path, "rb").close()',+ ' raise SystemExit(f"unexpected open ok: {path}")',+ ' except FileNotFoundError:',+ ' print(json.dumps({"platform": "darwin", "proc_fd": "ENOENT"}))',+ ' raise SystemExit(0)',+ ' pipe_path = f"/proc/{pid}/fd/{pipe_fd}"',+ ' with open(pipe_path, "rb", buffering=0) as f:',+ ' pipe_data = f.read(64)',+ ' if pipe_data != PIPE_SECRET:',+ ' raise SystemExit(f"pipe steal mismatch: {pipe_data!r}")',+ ' sock_path = f"/proc/{pid}/fd/{sock_fd}"',+ ' sock_open_err = None',+ ' try:',+ ' open(sock_path, "rb", buffering=0).close()',+ ' raise SystemExit("socketpair open(/proc) unexpectedly succeeded")',+ ' except OSError as e:',+ ' sock_open_err = e.errno',+ ' libc = ctypes.CDLL(None, use_errno=True)',+ ' libc.pidfd_open.argtypes = [ctypes.c_int, ctypes.c_uint]',+ ' libc.pidfd_open.restype = ctypes.c_int',+ ' libc.pidfd_getfd.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint]',+ ' libc.pidfd_getfd.restype = ctypes.c_int',+ ' pidfd = libc.pidfd_open(pid, 0)',+ ' if pidfd < 0:',+ ' raise SystemExit(f"pidfd_open failed errno={ctypes.get_errno()}")',+ ' stolen = libc.pidfd_getfd(pidfd, sock_fd, 0)',+ ' if stolen < 0:',+ ' raise SystemExit(f"pidfd_getfd failed errno={ctypes.get_errno()}")',+ ' sock_data = os.read(stolen, 64)',+ ' os.close(stolen)',+ ' os.close(pidfd)',+ ' if sock_data != SOCK_SECRET:',+ ' raise SystemExit(f"socketpair steal mismatch: {sock_data!r}")',+ ' print(json.dumps({',+ ' "platform": "linux",',+ ' "pipe_via": "open(/proc/pid/fd)",',+ ' "socketpair_open_errno": sock_open_err,',+ ' "socketpair_via": "pidfd_getfd",',+ ' "holder_pid": pid,',+ ' }))',+ 'finally:',+ ' holder.kill()',+ ' try: holder.wait(timeout=2)',+ ' except Exception: pass',+ ].join('\n');++ const probe = await runCapture('python3', ['-c', script]);+ assert.equal(probe.code, 0, probe.out);+ const line = probe.out.trim().split(/\r?\n/).filter(Boolean).at(-1);+ assert.ok(line !== undefined && line.length > 0, `empty inherited-fd probe output: ${probe.out}`);+ const parsed: unknown = JSON.parse(line);+ assert.ok(parsed !== null && typeof parsed === 'object');+ assert.ok('platform' in parsed && typeof parsed.platform === 'string');+ if (process.platform === 'linux') {+ assert.equal(parsed.platform, 'linux');+ assert.ok('pipe_via' in parsed && parsed.pipe_via === 'open(/proc/pid/fd)');+ assert.ok('socketpair_via' in parsed && parsed.socketpair_via === 'pidfd_getfd');+ console.log(+ `ok: proved Linux same-UID fd steal (pipe via /proc/pid/fd; socketpair via pidfd_getfd) pid=${String(+ 'holder_pid' in parsed ? parsed.holder_pid : '?',+ )}`,+ );+ return;+ }+ assert.equal(parsed.platform, 'darwin');+ assert.ok('proc_fd' in parsed && parsed.proc_fd === 'ENOENT');+ console.log('ok: macOS has no /proc/<pid>/fd same-UID steal path (ENOENT)');+}++/**+ * Exec timeout must SIGKILL the process group — not only the direct child —+ * so a forked `while True` grandchild dies too.+ */+async function smokeProcessGroupTimeout(params: {+ sandboxRootPath: string;+ shell: string;+ platform: 'darwin' | 'linux';+}): Promise<void> {+ const session = await runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: [+ "python3 - <<'PY'",+ 'import os, time',+ 'open("leader.pid","w").write(str(os.getpid()))',+ 'child = os.fork()',+ 'if child == 0:',+ ' while True:',+ ' time.sleep(1)',+ 'open("grandchild.pid","w").write(str(child))',+ 'time.sleep(3600)',+ 'PY',+ ].join('\n'),+ timeoutMs: 1500,+ });+ assert.equal(session.timedOut, true, 'session should time out');+ const leaderPid = Number((await readFile(join(params.sandboxRootPath, 'leader.pid'), 'utf8')).trim());+ const grandchildPid = Number((await readFile(join(params.sandboxRootPath, 'grandchild.pid'), 'utf8')).trim());+ assert.ok(leaderPid > 0 && grandchildPid > 0);+ // Give the kernel a moment after SIGKILL.+ await sleep(200);+ assert.equal(pidAlive(leaderPid), false, `leader ${String(leaderPid)} still alive`);+ assert.equal(pidAlive(grandchildPid), false, `grandchild ${String(grandchildPid)} still alive`);+ console.log('ok: exec timeout kills process group (leader + while-True grandchild)');+}++async function assertExecFails(+ provider: LocalSandboxProvider,+ sandboxId: string,+ command: string,+ label: string,+ options?: {+ timeoutSeconds?: number;+ /** Reject these exits as "wrong reason" (e.g. 127 = command missing). */+ forbidExitCodes?: number[];+ /** Require output evidence of policy/IO denial, not just any failure. */+ outputMustMatch?: RegExp;+ },+): Promise<{ exitCode: number; result: string }> {+ const result = await provider.exec({+ sandboxId,+ command,+ ...(options?.timeoutSeconds === undefined ? {} : { timeoutSeconds: options.timeoutSeconds }),+ });+ assert.equal(result.success, true, `${label}: provider error ${JSON.stringify(result)}`);+ if (!result.success) throw new Error('unreachable');+ assert.notEqual(result.response.exitCode, 0, `${label}: expected non-zero exit\n${result.response.result}`);+ if (options?.forbidExitCodes?.includes(result.response.exitCode)) {+ assert.fail(`${label}: exit ${String(result.response.exitCode)} is not a policy denial\n${result.response.result}`);+ }+ if (options?.outputMustMatch !== undefined) {+ assert.match(+ result.response.result,+ options.outputMustMatch,+ `${label}: output lacked denial evidence\n${result.response.result}`,+ );+ }+ console.log(`ok: ${label}`);+ return { exitCode: result.response.exitCode, result: result.response.result };+}++/**+ * Host TCP listeners on loopback must be unreachable from the sandbox+ * (macOS Seatbelt deny, or Linux netns isolation).+ */+async function smokeLoopbackDenied(provider: LocalSandboxProvider, sandboxId: string): Promise<void> {+ const listen = async (host: string): Promise<{ port: number; close: () => Promise<void> }> => {+ const server = createServer(socket => {+ socket.end('loopback-open\n');+ });+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, host, () => resolve());+ });+ const addr = server.address();+ if (addr === null || typeof addr === 'string') {+ throw new Error(`expected TCP address for ${host}`);+ }+ return {+ port: addr.port,+ close: () =>+ new Promise((resolve, reject) => {+ server.close(err => (err ? reject(err) : resolve()));+ }),+ };+ };++ const v4 = await listen('127.0.0.1');+ let v6: { port: number; close: () => Promise<void> } | undefined;+ try {+ v6 = await listen('::1');+ } catch {+ v6 = undefined;+ }++ try {+ await assertExecFails(+ provider,+ sandboxId,+ [+ "python3 - <<'PY'",+ 'import socket, sys',+ `port = ${String(v4.port)}`,+ 'try:',+ ' s = socket.create_connection(("127.0.0.1", port), timeout=2)',+ ' data = s.recv(64)',+ ' s.close()',+ ' print("loopback-v4-open", data)',+ ' raise SystemExit(0)',+ 'except OSError as e:',+ ' print("loopback-v4-blocked", type(e).__name__, e)',+ ' raise SystemExit(2)',+ 'PY',+ ].join('\n'),+ 'host 127.0.0.1 listener unreachable from sandbox',+ { outputMustMatch: /loopback-v4-blocked/ },+ );++ if (v6 !== undefined) {+ const v6Port = v6.port;+ await assertExecFails(+ provider,+ sandboxId,+ [+ "python3 - <<'PY'",+ 'import socket, sys',+ `port = ${String(v6Port)}`,+ 'try:',+ ' s = socket.create_connection(("::1", port), timeout=2)',+ ' data = s.recv(64)',+ ' s.close()',+ ' print("loopback-v6-open", data)',+ ' raise SystemExit(0)',+ 'except OSError as e:',+ ' print("loopback-v6-blocked", type(e).__name__, e)',+ ' raise SystemExit(2)',+ 'PY',+ ].join('\n'),+ 'host ::1 listener unreachable from sandbox',+ { outputMustMatch: /loopback-v6-blocked/ },+ );+ } else {+ console.log('ok: skip ::1 listener (host cannot bind)');+ }++ // Private / link-local: no controlled listener; still must not connect.+ await assertExecFails(+ provider,+ sandboxId,+ [+ "python3 - <<'PY'",+ 'import socket, sys',+ 'targets = [("10.255.255.1", 9), ("169.254.169.254", 80), ("192.168.255.1", 9)]',+ 'opened = []',+ 'for host, port in targets:',+ ' try:',+ ' s = socket.create_connection((host, port), timeout=1)',+ ' s.close()',+ ' opened.append(f"{host}:{port}")',+ ' except OSError as e:',+ ' print(f"private-blocked {host}:{port} {type(e).__name__}")',+ 'if opened:',+ ' print("private-open", opened)',+ ' raise SystemExit(0)',+ 'raise SystemExit(2)',+ 'PY',+ ].join('\n'),+ 'private/link-local TCP connect denied',+ { outputMustMatch: /private-blocked/ },+ );+ } finally {+ await v4.close().catch(() => undefined);+ if (v6 !== undefined) {+ await v6.close().catch(() => undefined);+ }+ }+}++/**+ * setsid/double-fork vs kill(-pgid):+ * - macOS: no PID ns — escape leaves the process group and survives killpg+ * (known limitation; host must reap via the written host pid).+ * - Linux SRT: PID ns + die-with-parent — escape dies with the sandbox; in-ns+ * pids are not host-visible, so we watch a heartbeat file instead of kill(pid).+ */+async function smokeSetsidEscapeSurvivesKillpg(params: {+ sandboxRootPath: string;+ shell: string;+ platform: 'darwin' | 'linux';+}): Promise<void> {+ const heartbeatPath = join(params.sandboxRootPath, 'escaped.heartbeat');+ // Escaped child drops stdio so host pipes can close after killpg.+ // Cap wait: SRT wrapper teardown can still lag; do not hang the suite.+ const sessionPromise = runSupervisorSession({+ sandboxRootPath: params.sandboxRootPath,+ shell: params.shell,+ platform: params.platform,+ command: [+ "python3 - <<'PY'",+ 'import os, time',+ 'open("leader.pid", "w", encoding="utf-8").write(str(os.getpid()))',+ 'child = os.fork()',+ 'if child == 0:',+ ' os.setsid()',+ ' grand = os.fork()',+ ' if grand > 0:',+ ' os._exit(0)',+ ' dn = os.open("/dev/null", os.O_RDWR)',+ ' os.dup2(dn, 0); os.dup2(dn, 1); os.dup2(dn, 2)',+ ' if dn > 2: os.close(dn)',+ ' # Close Code Mode fds if present so host is not held open.',+ ' for fd in (3, 4):',+ ' try: os.close(fd)',+ ' except OSError: pass',+ ' open("escaped.pid", "w", encoding="utf-8").write(str(os.getpid()))',+ ' n = 0',+ ' while True:',+ ' n += 1',+ ' open("escaped.heartbeat", "w", encoding="utf-8").write(str(n))',+ ' time.sleep(0.2)',+ 'os.waitpid(child, 0)',+ 'time.sleep(3600)',+ 'PY',+ ].join('\n'),+ timeoutMs: 1500,+ });++ let escapedRaw = '';+ for (let i = 0; i < 60 && !/^\d+$/.test(escapedRaw); i++) {+ try {+ escapedRaw = (await readFile(join(params.sandboxRootPath, 'escaped.pid'), 'utf8')).trim();+ } catch {+ // not yet+ }+ await sleep(50);+ }+ assert.match(escapedRaw, /^\d+$/, 'escaped.pid missing — setsid child never started');+ const escapedPid = Number(escapedRaw);++ let heartbeatBeforeSession = '';+ for (let i = 0; i < 40 && heartbeatBeforeSession === ''; i++) {+ try {+ heartbeatBeforeSession = (await readFile(heartbeatPath, 'utf8')).trim();+ } catch {+ // not yet+ }+ await sleep(50);+ }+ assert.match(heartbeatBeforeSession, /^\d+$/, 'escaped.heartbeat missing — escape never ran');++ const sessionOrTimeout = await Promise.race([+ sessionPromise.then(session => ({ kind: 'session' as const, session })),+ sleep(5000).then(() => ({ kind: 'hung' as const })),+ ]);+ if (sessionOrTimeout.kind === 'hung') {+ // Last resort: session did not settle after killpg (SRT wrapper leak).+ if (process.platform === 'darwin') {+ try {+ process.kill(escapedPid, 'SIGKILL');+ } catch {+ // ignore+ }+ }+ assert.fail('runSupervisorSession hung after timeout — killpg did not finish teardown');+ }+ const { session } = sessionOrTimeout;+ assert.equal(session.timedOut, true, 'session should time out');+ await sleep(500);++ const hb1 = (await readFile(heartbeatPath, 'utf8')).trim();+ await sleep(600);+ const hb2 = (await readFile(heartbeatPath, 'utf8')).trim();++ if (process.platform === 'linux') {+ // In-ns pid is not the host pid; survival is judged by heartbeat freeze.+ assert.equal(hb2, hb1, 'Linux: setsid escape should die with PID ns / die-with-parent (heartbeat still advancing)');+ console.log('ok: setsid escape dies with Linux PID ns / die-with-parent');+ return;+ }++ // macOS: host-visible pid; kill(-pgid) misses the new session.+ assert.notEqual(hb2, hb1, 'macOS: expected setsid escape to keep writing heartbeat after kill(-pgid)');+ assert.equal(pidAlive(escapedPid), true, `expected setsid escape pid ${String(escapedPid)} to survive kill(-pgid)`);+ try {+ process.kill(escapedPid, 'SIGKILL');+ } catch {+ // already gone+ }+ console.log('ok: setsid/double-fork escape survives killpg on macOS (known limitation)');+}++/**+ * Match hostRun AF_UNIX policy (Linux allowAllUnixSockets; macOS allowUnixSockets=[sandboxRoot]),+ * then prove pathname connect is still gated by allowRead (FS) / seatbelt, not by the Unix-socket toggle alone.+ * On Linux, also prove /proc/net/unix is the sandbox netns table (host abstract absent).+ */+async function smokeUnixSocketFsGate(): Promise<void> {+ // Keep paths short: macOS sun_path is ~104 bytes (long sandbox path UUIDs → EINVAL).+ const id = randomUUID().replaceAll('-', '').slice(0, 8);+ const sandboxRootPath = join(SANDBOXES, `u${id}`);+ const insideSock = join(sandboxRootPath, 'c.sock');+ const outsideSock = join(SANDBOXES, `o${id}.sock`);+ // Host-owned fake Docker socket (path shape only) — must not be in allowRead / allowUnixSockets.+ const emulatedDockerRoot = join(SANDBOXES, `v${id}`);+ const emulatedDockerSock = join(emulatedDockerRoot, 'run', 'docker.sock');+ const hostAbstractName = `\0tfy-abs-${id}`;+ const hostAbstractProcMarker = `@tfy-abs-${id}`;++ const platform = process.platform === 'darwin' ? 'darwin' : 'linux';+ const allowRead = [sandboxRootPath, ...platformAllowRead(platform)];++ const denyWrite = getDefaultWritePaths().filter(path => !path.startsWith('/dev/'));++ const listenUds = async (path: string): Promise<{ close: () => Promise<void> }> => {+ await unlink(path).catch(() => undefined);+ const server = createServer(socket => {+ socket.end('uds-ok\n');+ });+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(path, () => resolve());+ });+ return {+ close: async () => {+ await new Promise<void>(resolve => {+ server.close(() => resolve());+ });+ await unlink(path).catch(() => undefined);+ },+ };+ };++ const runSandboxed = async (command: string): Promise<{ code: number | null; out: string }> => {+ const wrap = await SandboxManager.wrapWithSandboxArgv(+ command,+ '/bin/bash',+ {+ filesystem: {+ allowWrite: [sandboxRootPath],+ denyWrite,+ denyRead: ['/'],+ allowRead,+ },+ network: { allowedDomains: [], deniedDomains: [] },+ },+ undefined,+ sandboxRootPath,+ { commandId: randomUUID(), commandText: command },+ );+ const [argv0, ...argvRest] = wrap.argv;+ if (argv0 === undefined) throw new Error('empty argv');+ return await new Promise((resolve, reject) => {+ const child = spawn(argv0, argvRest, {+ cwd: sandboxRootPath,+ env: {+ HOME: join(sandboxRootPath, '.home'),+ TMPDIR: join(sandboxRootPath, '.tmp'),+ PATH: commandPath(platform),+ ...wrap.env,+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let out = '';+ child.stdout?.on('data', (c: Buffer) => {+ out += c.toString('utf8');+ });+ child.stderr?.on('data', (c: Buffer) => {+ out += c.toString('utf8');+ });+ child.on('error', reject);+ child.on('close', code => resolve({ code, out }));+ });+ };++ const connectScript = (sockPath: string): string =>+ [+ "python3 - <<'PY'",+ 'import socket, sys',+ `path = ${JSON.stringify(sockPath)}`,+ 'try:',+ ' s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ ' s.settimeout(2)',+ ' s.connect(path)',+ ' data = s.recv(64)',+ ' s.close()',+ ' print("CONNECT_OK", data)',+ ' sys.exit(0)',+ 'except OSError as e:',+ ' print("CONNECT_FAIL", type(e).__name__, e.errno, e)',+ ' sys.exit(2)',+ 'PY',+ ].join('\n');++ /** Prove path is not discoverable/readable and connect also fails (no discover-then-connect shortcut). */+ const discoverAndConnectDeniedScript = (sockPath: string): string =>+ [+ "python3 - <<'PY'",+ 'import os, socket, stat, sys',+ `path = ${JSON.stringify(sockPath)}`,+ 'parent = os.path.dirname(path)',+ 'base = os.path.basename(path)',+ 'discover_ok = False',+ 'try:',+ ' st = os.stat(path)',+ ' print("STAT_OK", int(st.st_mode))',+ ' if stat.S_ISSOCK(st.st_mode):',+ ' discover_ok = True',+ ' print("DISCOVER_STAT_SOCK")',+ 'except OSError as e:',+ ' print("STAT_FAIL", type(e).__name__, getattr(e, "errno", None))',+ 'try:',+ ' if os.path.exists(path):',+ ' discover_ok = True',+ ' print("DISCOVER_EXISTS")',+ ' else:',+ ' print("EXISTS_FALSE")',+ 'except OSError as e:',+ ' print("EXISTS_FAIL", type(e).__name__, getattr(e, "errno", None))',+ 'try:',+ ' names = os.listdir(parent)',+ ' print("LISTDIR_OK", names)',+ ' if base in names:',+ ' discover_ok = True',+ ' print("DISCOVER_LISTDIR")',+ 'except OSError as e:',+ ' print("LISTDIR_FAIL", type(e).__name__, getattr(e, "errno", None))',+ 'if discover_ok:',+ ' print("DISCOVER_REACHABLE")',+ ' sys.exit(1)',+ 'print("DISCOVER_DENIED")',+ 'try:',+ ' s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ ' s.settimeout(2)',+ ' s.connect(path)',+ ' s.close()',+ ' print("CONNECT_OK")',+ ' sys.exit(2)',+ 'except OSError as e:',+ ' print("CONNECT_FAIL", type(e).__name__, getattr(e, "errno", None))',+ ' sys.exit(0)',+ 'PY',+ ].join('\n');++ await mkdir(join(sandboxRootPath, '.tmp'), { recursive: true, mode: 0o700 });+ await mkdir(join(sandboxRootPath, '.home'), { recursive: true, mode: 0o700 });+ await mkdir(dirname(emulatedDockerSock), { recursive: true, mode: 0o700 });+ const inside = await listenUds(insideSock);+ const outside = await listenUds(outsideSock);+ const emulatedDocker = await listenUds(emulatedDockerSock);++ // Match hostRun: Linux allowAll + FS gate; macOS allowUnixSockets=[sandboxRootPath] (FS does not gate UDS).+ const network =+ process.platform === 'darwin'+ ? {+ allowedDomains: [] as string[],+ deniedDomains: [] as string[],+ allowAllUnixSockets: false,+ allowUnixSockets: [sandboxRootPath],+ }+ : {+ allowedDomains: [] as string[],+ deniedDomains: [] as string[],+ allowAllUnixSockets: true,+ };++ await SandboxManager.initialize({+ network,+ filesystem: {+ allowWrite: [],+ denyWrite,+ denyRead: ['/'],+ allowRead,+ },+ });++ let hostAbstract: { close: () => Promise<void> } | undefined;+ try {+ const ok = await runSandboxed(connectScript(insideSock));+ assert.equal(ok.code, 0, `inside sock should connect:\n${ok.out}`);+ assert.match(ok.out, /CONNECT_OK/);+ console.log('ok: sandbox can connect to sandbox UDS (allowRead)');++ await access(outsideSock);+ const denied = await runSandboxed(connectScript(outsideSock));+ assert.notEqual(denied.code, 0, `outside sock must not connect:\n${denied.out}`);+ assert.match(denied.out, /CONNECT_FAIL/);+ console.log(+ process.platform === 'linux'+ ? 'ok: FS-denied path UDS connect fails under allowAllUnixSockets'+ : 'ok: path outside allowUnixSockets=[sandboxRootPath] connect fails (macOS seatbelt)',+ );++ // Prove the emulated docker listener is live on the host, then denied from the sandbox.+ const hostDockerConnect = await new Promise<{ code: number | null; out: string }>((resolve, reject) => {+ const child = spawn(+ 'python3',+ [+ '-c',+ [+ 'import socket, sys',+ 'path = sys.argv[1]',+ 's = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ 's.settimeout(2)',+ 's.connect(path)',+ 'print(s.recv(64))',+ 's.close()',+ ].join('\n'),+ emulatedDockerSock,+ ],+ { stdio: ['ignore', 'pipe', 'pipe'] },+ );+ let out = '';+ child.stdout?.on('data', (c: Buffer) => {+ out += c.toString('utf8');+ });+ child.stderr?.on('data', (c: Buffer) => {+ out += c.toString('utf8');+ });+ child.on('error', reject);+ child.on('close', code => resolve({ code, out }));+ });+ assert.equal(hostDockerConnect.code, 0, `host must reach emulated docker.sock:\n${hostDockerConnect.out}`);+ assert.match(hostDockerConnect.out, /uds-ok/);+ console.log('ok: host can connect to emulated docker.sock');++ const dockerDenied = await runSandboxed(connectScript(emulatedDockerSock));+ assert.notEqual(dockerDenied.code, 0, `sandbox must not connect to emulated docker.sock:\n${dockerDenied.out}`);+ assert.match(dockerDenied.out, /CONNECT_FAIL/);+ console.log('ok: sandbox cannot connect to host-created emulated docker.sock');++ const inventory = await runSandboxed(+ [+ "python3 - <<'PY'",+ 'import os, socket, stat, sys',+ 'roots = ["/dev", "/etc", "/usr"]',+ 'found = []',+ 'for root in roots:',+ ' if not os.path.isdir(root):',+ ' continue',+ ' for dirpath, dirnames, filenames in os.walk(root):',+ ' if dirpath.count(os.sep) - root.count(os.sep) > 3:',+ ' dirnames[:] = []',+ ' continue',+ ' for name in filenames:',+ ' p = os.path.join(dirpath, name)',+ ' try:',+ ' st = os.stat(p)',+ ' except OSError:',+ ' continue',+ ' if stat.S_ISSOCK(st.st_mode):',+ ' found.append(p)',+ 'print("FOUND", len(found))',+ 'for p in found[:20]:',+ ' print("SOCK", p)',+ 'bad = 0',+ 'for p in found:',+ ' try:',+ ' s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ ' s.settimeout(0.3)',+ ' s.connect(p)',+ ' s.close()',+ ' print("CONNECTED", p)',+ ' bad += 1',+ ' except OSError as e:',+ ' print("BLOCKED_OR_USELESS", p, type(e).__name__)',+ 'sys.exit(1 if bad else 0)',+ 'PY',+ ].join('\n'),+ );+ const invLines = inventory.out.trim().split('\n').slice(0, 40);+ console.log(invLines.join('\n'));+ assert.equal(inventory.code, 0, `sandbox connected to a socket under /dev|/etc|/usr:\n${inventory.out}`);+ console.log('ok: no successful connect to sockets under /dev|/etc|/usr (if any visible)');++ if (process.platform === 'linux') {+ // Host abstract listener (Linux-only). Sandbox has --unshare-net → own /proc/net/unix.+ const absServer = createServer(socket => {+ socket.end('abs-ok\n');+ });+ await new Promise<void>((resolve, reject) => {+ absServer.once('error', reject);+ absServer.listen(hostAbstractName, () => resolve());+ });+ hostAbstract = {+ close: async () => {+ await new Promise<void>(resolve => {+ absServer.close(() => resolve());+ });+ },+ };++ const hostProc = await readFile('/proc/net/unix', 'utf8');+ assert.match(+ hostProc,+ new RegExp(hostAbstractProcMarker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),+ 'host /proc/net/unix must list the abstract listener',+ );++ const procUnix = await runSandboxed(+ [+ "python3 - <<'PY'",+ 'import sys',+ `marker = ${JSON.stringify(hostAbstractProcMarker)}`,+ 'path = "/proc/net/unix"',+ 'try:',+ ' text = open(path, "r", encoding="utf-8", errors="replace").read()',+ 'except OSError as e:',+ ' print("PROC_NET_UNIX_UNREADABLE", getattr(e, "errno", None), e)',+ ' sys.exit(2)',+ 'print("PROC_NET_UNIX_READABLE", "bytes", len(text), "lines", len(text.splitlines()))',+ 'if marker in text:',+ ' print("HOST_ABSTRACT_VISIBLE", marker)',+ ' sys.exit(3)',+ 'print("HOST_ABSTRACT_ABSENT", marker)',+ // Also prove connect to host abstract fails (different netns).+ 'import socket',+ `abs_name = ${JSON.stringify(hostAbstractName)}`,+ 'try:',+ ' s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)',+ ' s.settimeout(1)',+ ' s.connect(abs_name)',+ ' s.close()',+ ' print("HOST_ABSTRACT_CONNECT_OK")',+ ' sys.exit(4)',+ 'except OSError as e:',+ ' print("HOST_ABSTRACT_CONNECT_FAIL", type(e).__name__, getattr(e, "errno", None))',+ 'sys.exit(0)',+ 'PY',+ ].join('\n'),+ );+ assert.equal(procUnix.code, 0, procUnix.out);+ assert.match(procUnix.out, /PROC_NET_UNIX_READABLE/);+ assert.match(procUnix.out, /HOST_ABSTRACT_ABSENT/);+ assert.match(procUnix.out, /HOST_ABSTRACT_CONNECT_FAIL/);+ console.log('ok: /proc/net/unix is sandbox netns (host abstract not listed / not connectable)');+ console.log(procUnix.out.trim().split('\n').filter(Boolean).join(' | '));+ } else {+ console.log('ok: skip Linux abstract /proc/net/unix netns probe (not Linux)');+ }++ console.log(+ process.platform === 'linux'+ ? 'ok: Linux allowAllUnixSockets + FS allowRead gates pathname UDS'+ : 'ok: macOS allowUnixSockets=[sandboxRootPath] gates pathname UDS (not allowRead)',+ );+ } finally {+ await hostAbstract?.close().catch(() => undefined);+ await emulatedDocker.close().catch(() => undefined);+ await inside.close().catch(() => undefined);+ await outside.close().catch(() => undefined);+ await SandboxManager.reset().catch(() => undefined);+ await removeSandbox(sandboxRootPath).catch(() => undefined);+ await rm(emulatedDockerRoot, { recursive: true, force: true }).catch(() => undefined);+ }+}++async function smokeHostPackageManagerDenied(provider: LocalSandboxProvider, sandboxId: string): Promise<void> {+ if (process.platform === 'darwin') {+ await assertExecFails(+ provider,+ sandboxId,+ "printf 'poc\\n' > /opt/homebrew/Cellar/.tfy-poc-write || exit 2",+ 'host Homebrew Cellar write denied',+ { outputMustMatch: /Permission|Read-only|Operation not permitted|denied|No such|cannot/i },+ );+ // Prefer reinstall so an already-installed keg cannot no-op to exit 0.+ // Brew also needs host API/cache reads + network; both are denied under SRT.+ await assertExecFails(+ provider,+ sandboxId,+ [+ 'set +e',+ 'command -v brew >/dev/null 2>&1 || { echo "brew-missing" >&2; exit 127; }',+ 'export HOMEBREW_NO_AUTO_UPDATE=1 HOMEBREW_NO_ANALYTICS=1 HOMEBREW_NO_ENV_HINTS=1',+ 'brew install lima',+ 'install_rc=$?',+ 'if [ "$install_rc" -eq 0 ]; then',+ ' brew reinstall lima',+ ' install_rc=$?',+ 'fi',+ 'exit "$install_rc"',+ ].join('\n'),+ 'brew install/reinstall lima denied',+ {+ // Brew may stall on network/API; fail-closed quickly under SRT.+ timeoutSeconds: 20,+ forbidExitCodes: [127],+ outputMustMatch: /not writable|Permission|Operation not permitted|Read-only|denied|Failed to download|Error:/i,+ },+ );+ return;+ }++ await assertExecFails(+ provider,+ sandboxId,+ "printf 'poc\\n' > /usr/bin/.tfy-poc-write || exit 2",+ 'host /usr/bin write denied',+ { outputMustMatch: /Permission|Read-only|Operation not permitted|denied|No such file|cannot/i },+ );+ await assertExecFails(+ provider,+ sandboxId,+ [+ 'set +e',+ 'command -v apt-get >/dev/null 2>&1 || { echo "apt-get-missing" >&2; exit 127; }',+ 'export DEBIAN_FRONTEND=noninteractive',+ 'apt-get install -y cowsay',+ 'exit $?',+ ].join('\n'),+ 'apt-get install denied',+ {+ timeoutSeconds: 20,+ forbidExitCodes: [127],+ outputMustMatch: /Permission|Read-only|Operation not permitted|denied|not open|Could not|E:/i,+ },+ );+}++async function main(): Promise<void> {+ if (process.platform !== 'darwin' && process.platform !== 'linux') {+ console.error('smoke: skipping (darwin/linux only)');+ process.exit(0);+ }++ process.env[ENV_LEAK_MARKER] = ENV_LEAK_VALUE;++ const support = await LocalSandboxProvider.isSupported();+ assert.equal(support.supported, true, support.supported ? '' : support.reason);+ console.log('ok: LocalSandboxProvider.isSupported');++ const sandboxRootPathParent = await mkdtemp(join(tmpdir(), 'tfy-local-sandbox-smoke-'));+ const codeModeSocketParentPath = join(tmpdir(), 'cm');+ await mkdir(codeModeSocketParentPath, { recursive: true, mode: 0o700 });+ if (!support.supported) {+ throw new Error(support.reason);+ }+ const provider = new LocalSandboxProvider({ sandboxRootPathParent, codeModeSocketParentPath, support });+ const instructions = provider.getAdditionalInstructions();+ assert.match(instructions, /sandbox shell: \S+/);+ assert.match(instructions, /Python 3 is available as: \S+/);+ console.log('ok: getAdditionalInstructions names shell and python');+ await prepareHostProbeFiles();+ let codeModeSandboxRootPath: string | undefined;+ try {+ const { sandboxId } = await provider.createSandbox();+ console.log('sandboxId', sandboxId);++ const printf = await provider.exec({+ sandboxId,+ command: "printf 'poc-ok\\n'",+ });+ assert.equal(printf.success, true);+ if (!printf.success) throw new Error('unreachable');+ assert.equal(printf.response.exitCode, 0);+ assert.equal(printf.response.result, 'poc-ok\n');+ console.log('ok: provider exec printf');++ await smokeLiveSrtUnixSocketAllowlistUpdate({+ sandboxRootPath: sandboxId,+ codeModeSocketParentPath,+ shell: support.shell,+ platform: support.platform,+ });++ const write = await provider.exec({+ sandboxId,+ command: "printf 'sandbox-ok\\n' > note.txt && cat note.txt",+ });+ assert.equal(write.success, true);+ if (!write.success) throw new Error('unreachable');+ assert.equal(write.response.exitCode, 0);+ assert.equal(write.response.result, 'sandbox-ok\n');+ console.log('ok: sandbox-local write/read');++ await provider.uploadFile({+ sandboxId,+ remotePath: 'uploads/hello.txt',+ content: Buffer.from('upload-ok\n'),+ });+ const downloaded = await provider.downloadFile({+ sandboxId,+ path: 'uploads/hello.txt',+ });+ assert.equal(downloaded.toString('utf8'), 'upload-ok\n');+ const catUpload = await provider.exec({+ sandboxId,+ command: 'cat uploads/hello.txt',+ });+ assert.equal(catUpload.success, true);+ if (!catUpload.success) throw new Error('unreachable');+ assert.equal(catUpload.response.result, 'upload-ok\n');+ console.log('ok: upload/download');++ await assertExecFails(+ provider,+ sandboxId,+ "printf 'leak\\n' > /tmp/claude/poc-should-fail.txt || exit 2",+ 'SRT default /tmp/claude write denied',+ { outputMustMatch: /Permission|Read-only|Operation not permitted|denied|No such|cannot/i },+ );++ const before = await readFile(DELETE_TARGET, 'utf8');+ assert.equal(before, 'delete-me\n');+ await assertExecFails(+ provider,+ sandboxId,+ `python3 -c 'import os; os.unlink(${JSON.stringify(DELETE_TARGET)})'`,+ 'SRT default /tmp/claude delete denied',+ );+ await access(DELETE_TARGET);++ const denyRead = await provider.exec({+ sandboxId,+ command: `cat ${JSON.stringify(DENY_READ_SECRET)}`,+ });+ assert.equal(denyRead.success, true);+ if (!denyRead.success) throw new Error('unreachable');+ assert.notEqual(denyRead.response.exitCode, 0);+ assert.ok(!denyRead.response.result.includes('host-secret-should-not-leak'));+ console.log('ok: host secret outside sandbox blocked');++ assert.ok(HOST_HOME && HOST_HOME.length > 0);+ await assertExecFails(provider, sandboxId, `ls ${JSON.stringify(HOST_HOME)}`, 'host home listing denied');++ await smokeHostPackageManagerDenied(provider, sandboxId);++ // System pip install (no --user/--target): must fail closed without network.+ // Local trivial package so the failure is install/prefix write, not PyPI fetch.+ await assertExecFails(+ provider,+ sandboxId,+ [+ 'set -euo pipefail',+ // ensurepip covers guests that only have python3 (no python3-pip package).+ 'python3 -m pip --version >/dev/null 2>&1 || python3 -m ensurepip --upgrade >/dev/null 2>&1 || true',+ 'python3 -m pip --version >/dev/null || { echo "pip-missing" >&2; exit 127; }',+ 'mkdir -p tfy_poc_pip_pkg/tfy_poc_pip',+ "cat > tfy_poc_pip_pkg/setup.py <<'EOF'",+ 'from setuptools import setup',+ 'setup(name="tfy-poc-pip", version="0.0.1", packages=["tfy_poc_pip"])',+ 'EOF',+ 'touch tfy_poc_pip_pkg/tfy_poc_pip/__init__.py',+ 'python3 -m pip install --no-input --no-deps --no-build-isolation ./tfy_poc_pip_pkg',+ ].join('\n'),+ 'system pip install denied',+ {+ forbidExitCodes: [127],+ outputMustMatch: /Permission|Read-only|Operation not permitted|denied|ERROR:|Could not|No module|error/i,+ },+ );++ await smokeLoopbackDenied(provider, sandboxId);++ await assertExecFails(+ provider,+ sandboxId,+ 'python3 -c \'import socket,sys\ntry:\n socket.create_connection(("1.1.1.1",443),timeout=2)\n print("network-open"); sys.exit(0)\nexcept OSError as e:\n print("network-blocked:%s"%e); sys.exit(2)\'',+ 'egress to 1.1.1.1:443 denied',+ { outputMustMatch: /network-blocked:/ },+ );+ await assertExecFails(+ provider,+ sandboxId,+ 'python3 -c \'import socket,sys\ntry:\n socket.getaddrinfo("example.com",443)\n print("dns-open"); sys.exit(0)\nexcept OSError as e:\n print("dns-blocked:%s"%e); sys.exit(2)\'',+ 'DNS for example.com denied',+ { outputMustMatch: /dns-blocked:/ },+ );++ const envLeak = await provider.exec({+ sandboxId,+ command: `printenv ${ENV_LEAK_MARKER} || true`,+ });+ assert.equal(envLeak.success, true);+ if (!envLeak.success) throw new Error('unreachable');+ assert.ok(!envLeak.response.result.includes(ENV_LEAK_VALUE));+ console.log('ok: host env secret not visible in sandbox');++ await smokeEnvInheritance(provider, sandboxId);+ await smokeUdsPeerCredentials();+ await smokeSameUidEnvironRead();+ await smokeSameUidInheritedFdAccess();++ await assertExecFails(+ provider,+ sandboxId,+ `cat ${JSON.stringify('../.poc-deny-read-secret')}`,+ 'path escape via .. denied',+ );++ await assertExecFails(+ provider,+ sandboxId,+ ['set -e', `ln -sf ${JSON.stringify(DENY_READ_SECRET)} escape-link`, 'cat escape-link'].join('\n'),+ 'symlink escape read denied',+ );++ // Plain sandboxed open() following a sandbox→host symlink must not leak the host file.+ await assertExecFails(+ provider,+ sandboxId,+ [+ `ln -sf ${JSON.stringify(DENY_READ_SECRET)} escape-open`,+ "python3 - <<'PY'",+ 'import sys',+ 'try:',+ ' data = open("escape-open", "rb").read()',+ ' sys.stdout.write(data.decode("utf-8", "replace"))',+ ' raise SystemExit(0)',+ 'except OSError as e:',+ ' print(f"open-blocked {type(e).__name__}", file=sys.stderr)',+ ' raise SystemExit(2)',+ 'PY',+ ].join('\n'),+ 'sandbox open() symlink follow read denied',+ {+ outputMustMatch: /open-blocked|Permission|Operation not permitted|denied|No such file/i,+ },+ );+ assert.equal(await readFile(DENY_READ_SECRET, 'utf8'), SECRET_CONTENTS);++ // Symlink follow write: host target must stay intact regardless of sandbox exit code.+ const writeFollow = await provider.exec({+ sandboxId,+ command: [+ `ln -sf ${JSON.stringify(DENY_READ_SECRET)} escape-open-w`,+ "python3 - <<'PY'",+ 'import sys',+ 'try:',+ ' open("escape-open-w", "wb").write(b"pwned-exec\\n")',+ ' print("open-write-ok")',+ ' raise SystemExit(0)',+ 'except OSError as e:',+ ' print(f"open-write-blocked {type(e).__name__}", file=sys.stderr)',+ ' raise SystemExit(2)',+ 'PY',+ ].join('\n'),+ });+ assert.equal(writeFollow.success, true, JSON.stringify(writeFollow));+ if (!writeFollow.success) throw new Error('unreachable');+ assert.equal(+ await readFile(DENY_READ_SECRET, 'utf8'),+ SECRET_CONTENTS,+ 'sandbox symlink follow write must not mutate host secret',+ );+ if (writeFollow.response.exitCode !== 0) {+ assert.match(writeFollow.response.result, /open-write-blocked|Permission|Operation not permitted|denied/i);+ }+ console.log('ok: sandbox open() symlink follow write left host secret intact');++ // Provider upload/download: SRT must stop symlink follow from leaking or mutating the host.+ const mkDlLink = await provider.exec({+ sandboxId,+ command: `ln -sf ${JSON.stringify(DENY_READ_SECRET)} api-escape-dl && test -L api-escape-dl`,+ });+ assert.equal(mkDlLink.success, true);+ if (!mkDlLink.success) throw new Error('unreachable');+ assert.equal(mkDlLink.response.exitCode, 0, mkDlLink.response.result);+ let downloadLeaked = false;+ try {+ const leaked = await provider.downloadFile({ sandboxId, path: 'api-escape-dl' });+ downloadLeaked = leaked.toString('utf8').includes('host-secret-should-not-leak');+ } catch {+ // deny / throw is fine; host check below still runs+ }+ assert.equal(downloadLeaked, false, 'downloadFile must not return host secret via symlink');+ assert.equal(await readFile(DENY_READ_SECRET, 'utf8'), SECRET_CONTENTS);+ console.log('ok: downloadFile does not leak host via symlink (SRT)');++ const mkUlLink = await provider.exec({+ sandboxId,+ command: `ln -sf ${JSON.stringify(DENY_READ_SECRET)} api-escape-ul && test -L api-escape-ul`,+ });+ assert.equal(mkUlLink.success, true);+ if (!mkUlLink.success) throw new Error('unreachable');+ assert.equal(mkUlLink.response.exitCode, 0, mkUlLink.response.result);+ try {+ await provider.uploadFile({+ sandboxId,+ remotePath: 'api-escape-ul',+ content: Buffer.from('pwned-via-host-api\n'),+ });+ } catch {+ // deny / throw is fine; host check below is the gate+ }+ assert.equal(+ await readFile(DENY_READ_SECRET, 'utf8'),+ SECRET_CONTENTS,+ 'uploadFile must not mutate host via symlink',+ );+ console.log('ok: uploadFile does not mutate host via symlink (SRT)');++ const { sandboxId: otherId } = await provider.createSandbox();+ await provider.uploadFile({+ sandboxId,+ remotePath: 'cross-secret.txt',+ content: Buffer.from('cross-sandbox-secret\n'),+ });+ const otherRead = await provider.exec({+ sandboxId: otherId,+ command: `cat ${JSON.stringify(join(sandboxId, 'cross-secret.txt'))}`,+ });+ assert.equal(otherRead.success, true);+ if (!otherRead.success) throw new Error('unreachable');+ assert.notEqual(otherRead.response.exitCode, 0);+ assert.ok(!otherRead.response.result.includes('cross-sandbox-secret'));+ console.log('ok: cross-sandbox absolute path read denied');++ const otherWrite = await provider.exec({+ sandboxId: otherId,+ command: `printf 'cross-write\\n' > ${JSON.stringify(join(sandboxId, 'cross-write.txt'))}`,+ });+ assert.equal(otherWrite.success, true);+ if (!otherWrite.success) throw new Error('unreachable');+ assert.notEqual(otherWrite.response.exitCode, 0);+ await assert.rejects(async () => readFile(join(sandboxId, 'cross-write.txt')));+ console.log('ok: cross-sandbox absolute path write denied');++ const persist1 = await provider.exec({+ sandboxId,+ command: "printf 'persist-ok\\n' > persist.txt",+ });+ assert.equal(persist1.success, true);+ if (!persist1.success) throw new Error('unreachable');+ assert.equal(persist1.response.exitCode, 0);+ const persist2 = await provider.exec({+ sandboxId,+ command: 'cat persist.txt',+ });+ assert.equal(persist2.success, true);+ if (!persist2.success) throw new Error('unreachable');+ assert.equal(persist2.response.result, 'persist-ok\n');+ console.log('ok: sandbox persists across execs');++ const flood = await provider.exec({+ sandboxId,+ command: `python3 -c 'import sys; sys.stdout.write("x" * ${String(MAX_OUTPUT_BYTES + 1)})'`,+ timeoutSeconds: 30,+ });+ assert.equal(flood.success, false);+ if (flood.success) throw new Error('unreachable');+ assert.match(flood.error, /buffered output exceeded/);+ console.log(`ok: oversized stdout is terminal (${String(MAX_OUTPUT_BYTES)} byte cap)`);++ assert.match(provider.getToolResultDumpDir(sandboxId), /tool-results$/);+ assert.match(provider.getGitCredentialsPath(sandboxId), /\.git-credentials$/);+ console.log('ok: dump/git credential paths');++ codeModeSandboxRootPath = await createSandbox(join(sandboxRootPathParent, `codemode-${Date.now()}`));+ await smokeProcessGroupTimeout({+ sandboxRootPath: codeModeSandboxRootPath,+ shell: support.shell,+ platform: support.platform,+ });+ await smokeSetsidEscapeSurvivesKillpg({+ sandboxRootPath: codeModeSandboxRootPath,+ shell: support.shell,+ platform: support.platform,+ });+ await smokeCodeMode({+ sandboxRootPath: codeModeSandboxRootPath,+ codeModeSocketParentPath,+ shell: support.shell,+ platform: support.platform,+ });++ console.log('all LocalSandboxProvider + Code Mode smokes passed');+ } finally {+ delete process.env[ENV_LEAK_MARKER];+ await provider.dispose();+ if (codeModeSandboxRootPath !== undefined) {+ await removeSandbox(codeModeSandboxRootPath).catch(() => undefined);+ }+ await rm(sandboxRootPathParent, { recursive: true, force: true }).catch(() => undefined);+ await cleanupHostProbeFiles().catch(() => undefined);+ }++ // Own SRT session: AF_UNIX enabled so FS / allowUnixSockets gating is what we measure.+ await smokeUnixSocketFsGate();+ console.log('all smokes passed');+}++test('local-sandbox smoke', async () => {+ await main();+}, 600_000);diff --git a/packages/local-sandbox/tsconfig.build.json b/packages/local-sandbox/tsconfig.build.jsonnew file mode 100644index 000000000..719f4cee2--- /dev/null+++ b/packages/local-sandbox/tsconfig.build.json@@ -0,0 +1,8 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "types": ["node"]+ },+ "include": ["src/**/*.ts"],+ "exclude": ["dist", "node_modules", "test", "scripts"]+}diff --git a/packages/local-sandbox/tsconfig.json b/packages/local-sandbox/tsconfig.jsonnew file mode 100644index 000000000..2bd98076d--- /dev/null+++ b/packages/local-sandbox/tsconfig.json@@ -0,0 +1,31 @@+{+ "compilerOptions": {+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "noImplicitOverride": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noPropertyAccessFromIndexSignature": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "allowUnreachableCode": false,+ "allowUnusedLabels": false,+ "verbatimModuleSyntax": true,+ "isolatedModules": true,+ "noUncheckedSideEffectImports": true,+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2022"],+ "types": ["node"],+ "skipLibCheck": true,+ "outDir": "dist",+ "rootDir": ".",+ "sourceMap": true,+ "declaration": true,+ "declarationMap": true+ },+ "include": ["src/**/*.ts", "scripts/**/*.ts"],+ "exclude": ["dist", "test", "node_modules"]+}diff --git a/packages/local-sandbox/tsconfig.smoke.json b/packages/local-sandbox/tsconfig.smoke.jsonnew file mode 100644index 000000000..ddf5cd4bd--- /dev/null+++ b/packages/local-sandbox/tsconfig.smoke.json@@ -0,0 +1,12 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "types": ["node"],+ "declaration": false,+ "declarationMap": false,+ "noUnusedLocals": false,+ "noUnusedParameters": false+ },+ "include": ["src/**/*.ts", "scripts/probe-loopback.ts"],+ "exclude": ["dist", "test", "node_modules"]+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9a66643d0..509441fc9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -204,6 +204,40 @@ importers:specifier: ^7.0.2version: 7.0.2+ packages/local-sandbox:+ dependencies:+ '@anthropic-ai/sandbox-runtime':+ specifier: 0.0.71+ version: 0.0.71+ '@truefoundry/trueforge-core':+ specifier: workspace:*+ version: link:../harness+ ulid:+ specifier: ^3.0.2+ version: 3.0.2+ zod:+ specifier: ^4.4.3+ version: 4.4.3+ devDependencies:+ '@swc/core':+ specifier: ^1.11.0+ version: 1.15.46+ '@swc/jest':+ specifier: ^0.2.37+ version: 0.2.39(@swc/[email protected])+ '@types/jest':+ specifier: ^29.5.14+ version: 29.5.14+ '@types/node':+ specifier: ^24.12.0+ version: 24.13.3+ jest:+ specifier: ^29.7.0+ typescript:+ specifier: ^7.0.2+ version: 7.0.2+packages/sdk:devDependencies:'@biomejs/biome':@@ -506,6 +540,11 @@ packages:resolution: {integrity: sha512-9WAerTaPU2jcVi8dh8x27tySEuLur1Kfg7Go74GuCmsC/2MDSvrTkrK8ZrXWjryEevKfcPPmO1enveE7eqlzoA==}engines: {node: '>=22'}+ '@anthropic-ai/[email protected]':+ resolution: {integrity: sha512-/ZMCavpMElD0ku2BlA95vezKUsVN0DD/wVd3WIEAfFjkTF2nsmzQA+MhejIWhuSUS9HpxMtTj57eFL+kdbKZ/A==}+ engines: {node: '>=20.11.0'}+ hasBin: true+'@asamuzakjp/[email protected]':resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}@@ -2190,6 +2229,9 @@ packages:resolution: {integrity: sha512-pOr5+q1fLYKwFN3LAJuGZEnfXDcQ73zqgDHMtGy+K+uIoUqyY+6MeDCWFwfu+4EFuq76I5EPFofoNAI+Bmmq4A==}engines: {node: '>=22.13'}+ '@pondwader/[email protected]':+ resolution: {integrity: sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg==}+'@protobufjs/[email protected]':resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}@@ -4276,6 +4318,10 @@ packages:resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}+ resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==}engines: {node: '>=20'}@@ -6004,6 +6050,10 @@ packages:resolution: {integrity: sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw==}engines: {node: '>=18'}+ resolution: {integrity: sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==}+ engines: {node: '>= 6.13.0'}+resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}@@ -7523,6 +7573,13 @@ snapshots:dependencies:json-schema: 0.4.0+ '@anthropic-ai/[email protected]':+ dependencies:+ '@pondwader/socks5-server': 1.0.10+ commander: 12.1.0+ node-forge: 1.4.0+ zod: 3.25.76+'@asamuzakjp/[email protected]':dependencies:'@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])@@ -9383,6 +9440,8 @@ snapshots:'@pnpm/[email protected]': {}+ '@pondwader/[email protected]': {}+'@protobufjs/[email protected]': {}'@protobufjs/[email protected]': {}@@ -10750,10 +10809,10 @@ snapshots:transitivePeerDependencies:- supports-color- '@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])':+ '@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])':dependencies:'@eslint-community/regexpp': 4.12.2- '@typescript-eslint/parser': 8.65.0([email protected]([email protected])([email protected]))([email protected])([email protected])+ '@typescript-eslint/parser': 8.65.0([email protected]([email protected])([email protected]))([email protected])([email protected])'@typescript-eslint/scope-manager': 8.65.0'@typescript-eslint/type-utils': 8.65.0([email protected]([email protected])([email protected]))([email protected])([email protected])'@typescript-eslint/utils': 8.65.0([email protected]([email protected])([email protected]))([email protected])([email protected])@@ -11487,6 +11546,8 @@ snapshots:+ [email protected]: {}+@@ -13058,7 +13119,7 @@ snapshots:whatwg-encoding: 3.1.1whatwg-mimetype: 4.0.0whatwg-url: 14.2.0- ws: 8.21.1+ ws: 8.21.3xml-name-validator: 5.0.0transitivePeerDependencies:- bufferutil@@ -13779,6 +13840,8 @@ snapshots:emojilib: 2.4.0skin-tone: 2.0.0+ [email protected]: {}+@@ -14920,7 +14983,7 @@ snapshots:[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]):dependencies:- '@typescript-eslint/eslint-plugin': 8.65.0(@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])+ '@typescript-eslint/eslint-plugin': 8.65.0(@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])'@typescript-eslint/parser': 8.65.0([email protected]([email protected])([email protected]))([email protected])([email protected])'@typescript-eslint/typescript-estree': 8.65.0([email protected])([email protected])'@typescript-eslint/utils': 8.65.0([email protected]([email protected])([email protected]))([email protected])([email protected])