The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Impl Local Sandbox (#306)
Chirag Jain42eee39597d4
diff --git a/.changeset/20260817110000-local-sandbox-standalone-fallback.md b/.changeset/20260817110000-local-sandbox-standalone-fallback.mdnew file mode 100644index 000000000..4802608e9--- /dev/null+++ b/.changeset/20260817110000-local-sandbox-standalone-fallback.md@@ -0,0 +1,6 @@+---+'@truefoundry/trueforge-core': patch+'@truefoundry/trueforge': patch+---++Enable a standalone in-memory local sandbox fallback (no settings row), persist fancy `v1:type:raw` sandbox ids, drop tenant-prefix ownership checks, keep TFY sandbox writes cwd-relative (no `/opt` / `/usr/local`), let each sandbox provider own PATH (no hardcoded Daytona tail in Sandbox), and grant only the Code Mode socket parent in SRT (not host `/tmp`).diff --git a/.changeset/pre.json b/.changeset/pre.jsonnew file mode 100644index 000000000..d1deaa4cf--- /dev/null+++ b/.changeset/pre.json@@ -0,0 +1,4 @@+{+ "mode": "pre",+ "tag": "rc"+}diff --git a/.cursor/BUGBOT.md b/.cursor/BUGBOT.mdindex aaca56cc1..5d0aa58f2 100644--- a/.cursor/BUGBOT.md+++ b/.cursor/BUGBOT.md@@ -15,7 +15,7 @@ If the diff changes code that ships in a published package and does not add a neSkip when:- The PR already adds `.changeset/*.md`-- Changes are docs, `AGENTS.md`, CI/workflows, charts, docker-compose, or `packages/local-sandbox` only+- Changes are docs, `AGENTS.md`, CI/workflows, charts, or docker-compose only- The PR is a Version Packages / `changeset-release/*` release PR## CI and release wiringdiff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex f93d37294..bd8cddd60 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -6018,7 +6018,7 @@}}},- "description": "Caller is not the session creator, or sandbox belongs to another tenant."+ "description": "Caller is not the session creator."},"404": {"content": {diff --git a/.gitignore b/.gitignoreindex eb5ff3960..6ba4f9250 100644--- a/.gitignore+++ b/.gitignore@@ -14,6 +14,7 @@ packages/trueforge/src/catalog/modelCatalog.gen.tspackages/trueforge/src/catalog/mcpCatalog.gen.tspackages/trueforge/src/catalog/skillCatalog.gen.tspackages/trueforge/src/catalog/sandboxCatalog.gen.ts+packages/trueforge/src/sandbox/local/sandboxScripts.gen.tsdata/# Helm subchart deps are fetched via `helm dependency build` (pinned by the# committed Chart.lock); the downloaded .tgz/dirs are not committed.diff --git a/AGENTS.md b/AGENTS.mdindex bda083a68..313e093e1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,7 +1,7 @@- Workspace tasks MUST use `package.json` scripts; add a script when a missing workflow is repeatable like the existing commands, not ad hoc commands.- CI package path filters, matrix package ids, and root scripts `test:*` in `.github/workflows/ci.yml` and root `package.json` MUST stay synchronized when a workspace package is added, renamed, or moved; the `store` filter sync rule lives in `packages/trueforge-core/src/agent-session/store/AGENTS.md`.- Release wiring MUST keep dist-free host development, `pnpm smoke`, and packed CJS/ESM consumers of `@truefoundry/trueforge-core` working without changes.-- PRs that change published-package code (`packages/trueforge-core`, `packages/trueforge`, `packages/trueforge-ui`, `packages/trueforge-sdk`) or `packages/frontend` (ships inside `@truefoundry/trueforge`) MUST include a new `.changeset/*.md` file (`pnpm changeset`). Docs, CI/workflows, charts, docker-compose, and `packages/local-sandbox`-only changes do not. SDK regeneration already adds `@truefoundry/trueforge-sdk` via `pnpm changeset:sdk-regen`.+- PRs that change published-package code (`packages/trueforge-core`, `packages/trueforge`, `packages/trueforge-ui`, `packages/trueforge-sdk`) or `packages/frontend` (ships inside `@truefoundry/trueforge`) MUST include a new `.changeset/*.md` file (`pnpm changeset`). Docs, CI/workflows, charts, and docker-compose changes do not. SDK regeneration already adds `@truefoundry/trueforge-sdk` via `pnpm changeset:sdk-regen`.- Shared Postgres/Redis settings in `docker-compose.yml` and `docker-compose.dev.yml` (image versions, health checks, `env_file`) MUST stay synchronized; intentional differences (app services, data paths, project `name`, host ports, in-network `POSTGRES_HOST` / `REDIS_URL`) MUST stay explicit. `packages/trueforge/.env` is the host-dev + secrets source; `docker-compose.yml` may read it but MUST override container connectivity so host-dev localhost values are not used inside the smoke-test stack.- Changes to types or schemas MUST keep `packages/trueforge-core`, `packages/frontend`, `packages/trueforge`, and `patches` synchronized; they MUST NOT update only one affected layer.- TypeScript code MUST NOT use assertion escapes such as `as T`, `as unknown as T`, non-null `!`, or `as never` to silence type errors; implementations MUST use sound contracts, guards, or corrected types.diff --git a/docs/openapi.json b/docs/openapi.jsonindex f93d37294..bd8cddd60 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -6018,7 +6018,7 @@}}},- "description": "Caller is not the session creator, or sandbox belongs to another tenant."+ "description": "Caller is not the session creator."},"404": {"content": {diff --git a/package.json b/package.jsonindex 66cb49e74..8440ec19f 100644--- a/package.json+++ b/package.json@@ -41,12 +41,15 @@"test:frontend": "pnpm --filter frontend test","test:trueforge-core": "pnpm --filter @truefoundry/trueforge-core test","test:trueforge": "pnpm --filter @truefoundry/trueforge test",+ "test:local-sandbox:contract": "pnpm --filter @truefoundry/trueforge test:local-sandbox:contract",+ "smoke:local-sandbox": "pnpm --filter @truefoundry/trueforge smoke:local-sandbox",+ "smoke:local-sandbox:lima": "pnpm --filter @truefoundry/trueforge smoke:local-sandbox:lima","test:store:local": "bash scripts/test-store-local.sh","test:store:postgres": "pnpm --filter @truefoundry/trueforge test:store:postgres","test:store:sqlite": "pnpm --filter @truefoundry/trueforge test:store:sqlite","test:trueforge-ui": "pnpm --filter @truefoundry/trueforge-ui test","test": "pnpm test:trueforge-core && pnpm test:trueforge-ui && pnpm test:trueforge && 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 && pnpm --filter @truefoundry/local-sandbox typecheck",+ "typecheck": "pnpm --filter @truefoundry/trueforge-core typecheck && pnpm --filter @truefoundry/trueforge-ui typecheck && pnpm --filter @truefoundry/trueforge typecheck && pnpm --filter frontend typecheck","version": "node scripts/version.mjs"},"devDependencies": {diff --git a/packages/local-sandbox/.gitignore b/packages/local-sandbox/.gitignoredeleted file mode 100644index 16fc3238e..000000000--- a/packages/local-sandbox/.gitignore+++ /dev/null@@ -1,5 +0,0 @@-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.pydeleted file mode 100644index 8c55b77ef..000000000--- a/packages/local-sandbox/fixtures/mcp_pipe_client.py+++ /dev/null@@ -1,144 +0,0 @@-#!/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.cjsdeleted file mode 100644index 88fe39627..000000000--- a/packages/local-sandbox/jest.config.cjs+++ /dev/null@@ -1,38 +0,0 @@-/** @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>/../trueforge-core/src/core/$1',- '^@truefoundry/trueforge-core/core$': '<rootDir>/../trueforge-core/src/core/index.ts',- '^@truefoundry/trueforge-core$': '<rootDir>/../trueforge-core/src/index.ts',- },- testTimeout: 120_000,- maxWorkers: '50%',- roots: ['<rootDir>/test'],- testMatch: ['**/test/**/*.test.ts'],-};diff --git a/packages/local-sandbox/package.json b/packages/local-sandbox/package.jsondeleted file mode 100644index 2e683c2a3..000000000--- a/packages/local-sandbox/package.json+++ /dev/null@@ -1,49 +0,0 @@-{- "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"- },- "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/src/index.ts b/packages/local-sandbox/src/index.tsdeleted file mode 100644index 6837f1448..000000000--- a/packages/local-sandbox/src/index.ts+++ /dev/null@@ -1,5 +0,0 @@-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.tsdeleted file mode 100644index 53e82e315..000000000--- a/packages/local-sandbox/src/provider/LocalSandboxProvider.ts+++ /dev/null@@ -1,400 +0,0 @@-/**- * 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/tsconfig.build.json b/packages/local-sandbox/tsconfig.build.jsondeleted file mode 100644index 829cd0426..000000000--- a/packages/local-sandbox/tsconfig.build.json+++ /dev/null@@ -1,19 +0,0 @@-{- "extends": "./tsconfig.json",- "compilerOptions": {- "types": ["node"],- "noEmit": false,- "module": "NodeNext",- "moduleResolution": "NodeNext",- "customConditions": [],- "target": "ES2022",- "lib": ["ES2022"],- "outDir": "dist",- "rootDir": ".",- "sourceMap": true,- "declaration": true,- "declarationMap": true- },- "include": ["src/**/*.ts"],- "exclude": ["dist", "node_modules", "test", "scripts"]-}diff --git a/packages/local-sandbox/tsconfig.json b/packages/local-sandbox/tsconfig.jsondeleted file mode 100644index c73f1c2e4..000000000--- a/packages/local-sandbox/tsconfig.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": "../../tsconfig.base.json",- "compilerOptions": {- "types": ["node"],- "noEmit": true,- "customConditions": ["trueforge-dev"]- },- "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.jsondeleted file mode 100644index 2f185cb86..000000000--- a/packages/local-sandbox/tsconfig.smoke.json+++ /dev/null@@ -1,21 +0,0 @@-{- "extends": "./tsconfig.json",- "compilerOptions": {- "types": ["node"],- "noEmit": false,- "module": "NodeNext",- "moduleResolution": "NodeNext",- "customConditions": [],- "target": "ES2022",- "lib": ["ES2022"],- "outDir": "dist",- "rootDir": ".",- "sourceMap": true,- "declaration": false,- "declarationMap": false,- "noUnusedLocals": false,- "noUnusedParameters": false- },- "include": ["src/**/*.ts", "scripts/probe-loopback.ts"],- "exclude": ["dist", "test", "node_modules"]-}diff --git a/packages/trueforge-core/src/core/index.ts b/packages/trueforge-core/src/core/index.tsindex 03be317a9..5ebbd311a 100644--- a/packages/trueforge-core/src/core/index.ts+++ b/packages/trueforge-core/src/core/index.ts@@ -139,11 +139,12 @@ export { 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 type { CodeModeClientInstall, 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 { absolutizeRelativeExecEnv } from './sandbox/provider/execEnv';export { ensureExecSuccess, shellEscape } from './sandbox/provider/Provider';export type {ExecErrorResult,@@ -169,6 +170,8 @@ export {validateSandboxOwnedByTenant,} from './sandbox/SandboxErrors';export { SANDBOX_IMAGE_URI } from './sandbox/sandboxImage';+export { existingSandboxIdForProvider, formatSandboxId, parseSandboxId, rawSandboxId } from './sandbox/sandboxRef';+export type { SandboxRefParts } from './sandbox/sandboxRef';// Skills: the ISkillMounter seam lets hosts plug in their own skill sourcesexport { InstructionBuilder } from './InstructionBuilder';diff --git a/packages/trueforge-core/src/core/sandbox/Sandbox.ts b/packages/trueforge-core/src/core/sandbox/Sandbox.tsindex 65c80646b..2a8b0a774 100644--- a/packages/trueforge-core/src/core/sandbox/Sandbox.ts+++ b/packages/trueforge-core/src/core/sandbox/Sandbox.ts@@ -16,15 +16,21 @@ import {import type { AgentTracing } from '../tracing/AgentTracing';import { extractErrorLogFields } from '../util/errorLogFields';import { CodeModeDispatcher } from './codeMode/CodeModeDispatcher';-import type { CodeModeTransport } from './codeMode/CodeModeTransport';-import { SANDBOX_FILE_UPLOADS_DIR } from './constants';+import { type CodeModeClientInstall, type CodeModeTransport } from './codeMode/CodeModeTransport';import { ensureExecSuccess, shellEscape, type SandboxProvider } from './provider/Provider';-import { validateNoPathTraversal, validateSandboxOwnedByTenant } from './SandboxErrors';-import { sandboxScripts } from './sandboxScripts.gen';+import { SandboxNotAvailableError, validateNoPathTraversal } from './SandboxErrors';+import { formatSandboxId, rawSandboxId } from './sandboxRef';// Import submodules, not the ./skills barrel, to avoid a cycle (the mounters import from Sandbox).-import { SKILLS_DIR } from './skills/constants';+import { dirname, join, relative } from 'node:path';import type { ISkillMounter } from './skills/ISkillMounter';+/** Layout derived from install remotePath (always `…/mcp_client.py`). */+function mcpClientLayout(remotePath: string): { pythonPath: string; binDir: string; binLink: string } {+ const pythonPath = dirname(remotePath);+ const binDir = join(pythonPath, 'bin');+ return { pythonPath, binDir, binLink: join(binDir, 'mcp-client') };+}+export interface SandboxInfo {sandbox_id: string;}@@ -39,32 +45,31 @@ const NATS_REQUEST_TIMEOUT_BUFFER_SECONDS = 30;// Write a script (base64-encoded, never interpolated raw) to a path and run it. Skill mounters reuse it.export function buildWriteAndRunScriptCommand(params: { scriptPath: string; scriptContent: string }): string {const b64 = Buffer.from(params.scriptContent, 'utf-8').toString('base64');+ const scriptPath = shellEscape(params.scriptPath);return [- `mkdir -p "$(dirname ${params.scriptPath})"`,- `rm -f ${params.scriptPath}`,- `echo ${shellEscape(b64)} | base64 -d > ${params.scriptPath}`,- `chmod a-w ${params.scriptPath}`,- `python3 ${params.scriptPath}`,+ `mkdir -p "$(dirname ${scriptPath})"`,+ `rm -f ${scriptPath}`,+ `echo ${shellEscape(b64)} | base64 -d > ${scriptPath}`,+ `chmod a-w ${scriptPath}`,+ `python3 ${scriptPath}`,].join(' && ');}/** Write or clear the git credential-store file at an absolute path (no global git config mutation). */function buildSyncGitCredentialsCommand(credentialsContent: string | null, credentialsPath: string): string {+ const path = shellEscape(credentialsPath);if (credentialsContent === null) {- return `rm -f ${credentialsPath}`;+ return `rm -f ${path}`;}// Base64 avoids interpolating credentials directly into the shell command.const b64 = Buffer.from(credentialsContent, 'utf-8').toString('base64');- return (- `mkdir -p "$(dirname ${credentialsPath})" && ` +- `echo '${b64}' | base64 -d > ${credentialsPath} && ` +- `chmod 600 ${credentialsPath}`- );+ return `mkdir -p "$(dirname ${path})" && ` + `echo '${b64}' | base64 -d > ${path} && ` + `chmod 600 ${path}`;}/*** Process-scoped credential.helper via GIT_CONFIG_* (avoids shared ~/.gitconfig).- * Required for TFY sandbox where many logical sandboxes share one pod/HOME.+ * Path is whatever the provider returns; providers with a shared FS (TFY) make+ * `store --file` absolute in their own `exec`.*/function buildGitCredentialHelperEnv(credentialsPath: string): Record<string, string> {return {@@ -94,7 +99,6 @@ export interface SandboxOptions {/** Used to derive the Code Mode NATS wait as request + connect. */mcpRequestTimeoutMs: number;mcpConnectTimeoutMs: number;- tenantName: string;tracing: AgentTracing;logger: Logger;}@@ -105,15 +109,6 @@ const SANDBOX_FILE_OUTPUT_TAG = 'sandbox-file-output';export const SANDBOX_SCHEMA_INFER_TAG = 'sandbox-schema-infer';const SANDBOX_FILE_UPLOADS_TAG = 'sandbox-file-uploads';-// Stable directory inside the sandbox where the MCP client library is uploaded.-// MCP client upload dir. Two lookup channels:-// - Python imports → PYTHONPATH points here (set by injectMCPClientEnv).-// - Shell `mcp-client` → symlinked into MCP_CLIENT_BIN_SYMLINK (on default PATH);-// basename drops `.py` so the agent doesn't reflexively prefix with `python`.-const MCP_CLIENT_DIR = '/opt/tfy/mcp-client';-const MCP_CLIENT_PATH = `${MCP_CLIENT_DIR}/mcp_client.py`;-const MCP_CLIENT_BIN_SYMLINK = '/usr/local/bin/mcp-client';-// Per-server config sent to mcp_client.py via TFY_MCP_SERVERS.interface SandboxMcpServerConfig {allowed_tools: string[];@@ -139,17 +134,24 @@ function injectTraceContextEnv(): Record<string, string> {/*** Injects environment variables required for mcp_client.py into sandbox_exec arguments.* Transport-specific vars (NATS URL/prefix/timeout) come from `codeModeEnv` via transport.start().+ * PYTHONPATH comes from transport.getClientInstall remotePath. PATH is provider-owned:+ * Sandbox never writes PATH (Daytona uses the image PATH; TFY/local set it in exec).*/function injectMCPClientEnv(params: {env?: Record<string, string> | undefined;mcpServers: Record<string, SandboxMcpServerConfig>;codeModeEnv?: Record<string, string> | undefined;+ mcpClientInstall?: CodeModeClientInstall | undefined;}): Record<string, string> {const codeModeEnv = params.codeModeEnv ?? {};const hasCodeModeTransport = Object.keys(codeModeEnv).length > 0;+ const install = params.mcpClientInstall;+ const layout = install === undefined ? undefined : mcpClientLayout(install.remotePath);return {...(params.env ?? {}),- PYTHONPATH: MCP_CLIENT_DIR,+ ...(layout !== undefined && {+ PYTHONPATH: layout.pythonPath,+ }),...(Object.keys(params.mcpServers).length > 0 && {TFY_MCP_SERVERS: Buffer.from(JSON.stringify(params.mcpServers)).toString('base64'),}),@@ -193,11 +195,9 @@ export class Sandbox extends LocalToolMCP {readonly name = SANDBOX_MCP_SERVER_ID;readonly displayName = 'Sandbox';override readonly description = 'Persistent sandbox environment for code execution';- static readonly FILE_UPLOADS_DIR = SANDBOX_FILE_UPLOADS_DIR;private readonly provider: SandboxProvider;private readonly existingSandboxId?: string | undefined;- private readonly tenantName: string;private existingSandboxInfo: SandboxInfo | undefined;// Cached promise to prevent concurrent sub-agents from creating duplicate sandboxes.private sandboxCreationPromise?: Promise<SandboxInfo> | undefined;@@ -207,12 +207,13 @@ export class Sandbox extends LocalToolMCP {private readonly requestTimeoutSeconds: number;private readonly skillMounter?: ISkillMounter | undefined;private cachedSkillsSection?: string | undefined;- private readonly mcpClientScriptBase64: string;private readonly logger: Logger;// Pre-resolved credential-store file content (null = clear / no git auth).private readonly resolvedGitCredentialsContent: string | null;private codeModeDispatcher: CodeModeDispatcher | undefined;private codeModeTransport: CodeModeTransport | undefined;+ /** Cached from transport.getClientInstall after sandbox init (when Code Mode is configured). */+ private mcpClientInstall: CodeModeClientInstall | undefined;private tools = [defineTool({@@ -227,24 +228,28 @@ export class Sandbox extends LocalToolMCP {super({ tracing: options.tracing });this.provider = options.provider;this.existingSandboxId = options.existingSandboxId;- this.tenantName = options.tenantName;this.skillMounter = options.skillMounter;this.fileDownloadEnabled = options.fileDownloadEnabled ?? false;const mcpBoundTimeoutMs = options.mcpRequestTimeoutMs + options.mcpConnectTimeoutMs;this.requestTimeoutSeconds = Math.ceil(mcpBoundTimeoutMs / 1000) + NATS_REQUEST_TIMEOUT_BUFFER_SECONDS;- // Scripts are internal to Sandbox: the upload paths, env contract, and prompt- // text are all hardcoded here, so injecting different content was never a- // real extension point. Consumers don't see or provide them.- this.mcpClientScriptBase64 = Buffer.from(sandboxScripts.mcpClient, 'utf-8').toString('base64');this.logger = options.logger.child({ module: 'Sandbox' });this.resolvedGitCredentialsContent = options.resolvedGitCredentialsContent ?? null;if (this.existingSandboxId) {- validateSandboxOwnedByTenant(this.existingSandboxId, this.tenantName);this.existingSandboxInfo = { sandbox_id: this.existingSandboxId };}}+ /** Provider-facing id (unwraps `v1:type:raw`; legacy ids pass through). */+ private providerSandboxId(sessionId: string): string {+ return rawSandboxId(sessionId);+ }++ /** Raw id for prompt layout paths before create (empty when this turn has no existing sandbox). */+ private promptSandboxId(): string {+ return this.existingSandboxId === undefined ? '' : rawSandboxId(this.existingSandboxId);+ }+private buildMcpServersEnvelope(): Record<string, SandboxMcpServerConfig> {const out: Record<string, SandboxMcpServerConfig> = {};for (const server of this.codeExecToolSets) {@@ -278,7 +283,7 @@ export class Sandbox extends LocalToolMCP {private renderSkillsSection(): string {if (this.cachedSkillsSection === undefined) {const skills = new InstructionBuilder('skills');- this.skillMounter?.instruction(skills);+ this.skillMounter?.instruction(skills, { skillsDir: this.provider.getSkillsDir(this.promptSandboxId()) });this.cachedSkillsSection = skills.build();}return this.cachedSkillsSection;@@ -308,7 +313,7 @@ export class Sandbox extends LocalToolMCP {private buildFileUploadsSection(builder: InstructionBuilder): void {builder.addSection(SANDBOX_FILE_UPLOADS_TAG,- `User-uploaded files are placed in ${Sandbox.FILE_UPLOADS_DIR}/. The Agent must not modify files in this directory. Always create a copy at a different location and work on the copy.`,+ `User-uploaded files are placed in ${this.provider.getFileUploadsDir(this.promptSandboxId())}/. The Agent must not modify files in this directory. Always create a copy at a different location and work on the copy.`,);}@@ -437,6 +442,13 @@ export class Sandbox extends LocalToolMCP {return this.existingSandboxInfo;}+ private clearExistingSandbox(): void {+ this.existingSandboxInfo = undefined;+ this.sandboxCreationPromise = undefined;+ this.sandboxInitPromise = undefined;+ this.mcpClientInstall = undefined;+ }+private async ensureSandboxCreated(): Promise<{sandboxInfo: SandboxInfo;sandboxCreated: SandboxInfo | undefined;@@ -444,15 +456,12 @@ export class Sandbox extends LocalToolMCP {if (this.existingSandboxInfo) {return { sandboxInfo: this.existingSandboxInfo, sandboxCreated: undefined };}- // Provider returns camelCase `{ sandboxId }`; rename to the snake_case- // `SandboxInfo` shape used everywhere downstream (Redis JSON, wire event,- // in-memory state).+ // Provider returns a raw id; persist the fancy `v1:type:raw` session id.this.sandboxCreationPromise ??= this.provider.createSandbox()- .then(({ sandboxId }) => {- validateSandboxOwnedByTenant(sandboxId, this.tenantName);- return { sandbox_id: sandboxId };- })+ .then(({ sandboxId }) => ({+ sandbox_id: formatSandboxId({ providerType: this.provider.type, rawId: sandboxId }),+ })).catch((e: unknown) => {this.sandboxCreationPromise = undefined;throw e;@@ -460,61 +469,145 @@ export class Sandbox extends LocalToolMCP {const sandboxInfo = await this.sandboxCreationPromise;// Concurrent callers may both await the same creation promise; only the first- // should report sandboxCreated. Read via a local to avoid control-flow narrowing- // that treats existingSandboxInfo as always undefined after the early return above.- const prior = this.existingSandboxInfo as SandboxInfo | undefined;- const isNew = prior === undefined;+ // should report sandboxCreated. Read through a method so TS does not keep the+ // pre-await "undefined" narrowing on the field.+ const raced = this.peekExistingSandboxInfo();+ if (raced !== undefined) {+ return { sandboxInfo: raced, sandboxCreated: undefined };+ }this.existingSandboxInfo = sandboxInfo;- return { sandboxInfo, sandboxCreated: isNew ? sandboxInfo : undefined };+ return { sandboxInfo, sandboxCreated: sandboxInfo };}- private async handleExec(input: SandboxExecInput): Promise<CallToolResponse> {- const { sandboxInfo, sandboxCreated } = await this.ensureSandboxCreated();- const sandboxCreatedFlag = Boolean(sandboxCreated);+ private peekExistingSandboxInfo(): SandboxInfo | undefined {+ return this.existingSandboxInfo;+ }++ /** Same-type missing remote/local root: drop the stale id and create a new fancy id. */+ private async recreateAfterUnavailable(): Promise<{+ sandboxInfo: SandboxInfo;+ sandboxCreated: SandboxInfo;+ }> {+ this.clearExistingSandbox();+ const created = await this.ensureSandboxCreated();+ if (created.sandboxCreated === undefined) {+ throw new Error('Sandbox recreate did not create a new sandbox');+ }+ return { sandboxInfo: created.sandboxInfo, sandboxCreated: created.sandboxCreated };+ }++ /**+ * Create or reattach, then init. A missing same-type sandbox throws+ * `SandboxNotAvailableError` from the provider; reattach then recreates.+ */+ private async ensureReadySandbox(): Promise<{+ sandboxInfo: SandboxInfo;+ sandboxCreated: SandboxInfo | undefined;+ }> {+ const first = await this.ensureSandboxCreated();try {await this.ensureSandboxInitialized();+ return first;+ } catch (error) {+ if (!(error instanceof SandboxNotAvailableError) || first.sandboxCreated !== undefined) {+ throw error;+ }+ const recreated = await this.recreateAfterUnavailable();+ await this.ensureSandboxInitialized();+ return recreated;+ }+ }++ private async handleExec(input: SandboxExecInput): Promise<CallToolResponse> {+ let sandboxInfo: SandboxInfo;+ let sandboxCreated: SandboxInfo | undefined;+ try {+ ({ sandboxInfo, sandboxCreated } = await this.ensureReadySandbox());} catch (e) {this.logger.error('Sandbox initialization failed', extractErrorLogFields(e));const message = e instanceof Error ? e.message : 'Sandbox initialization failed';+ const fallback = this.existingSandboxInfo;return toolResultResponse({text: `Sandbox initialization failed: ${message}`,isError: true,- overrides: { sandboxCreated: sandboxCreatedFlag, sandboxInfo },+ overrides: {+ sandboxCreated: Boolean(fallback),+ ...(fallback !== undefined ? { sandboxInfo: fallback } : {}),+ },});}- const codeModeEnv = await this.ensureCodeModeStarted(sandboxInfo.sandbox_id);+ const sandboxCreatedFlag = Boolean(sandboxCreated);+ const rawId = this.providerSandboxId(sandboxInfo.sandbox_id);+ const codeModeEnv = await this.ensureCodeModeStarted(rawId);const mcpClientEnv = injectMCPClientEnv({env: input.env,mcpServers: this.buildMcpServersEnvelope(),codeModeEnv,+ mcpClientInstall: this.mcpClientInstall,});const gitAuthEnv =this.resolvedGitCredentialsContent !== null- ? buildGitCredentialHelperEnv(this.provider.getGitCredentialsPath(sandboxInfo.sandbox_id))+ ? buildGitCredentialHelperEnv(this.provider.getGitCredentialsPath(rawId)): {};const env = { ...mcpClientEnv, ...gitAuthEnv };- const result = await this.provider.exec({- sandboxId: sandboxInfo.sandbox_id,- command: input.command,- cwd: input.cwd,- env,- });+ try {+ const result = await this.provider.exec({+ sandboxId: rawId,+ command: input.command,+ cwd: input.cwd,+ env,+ });- return {- result: {- content: [{ type: 'text', text: JSON.stringify(result) }],- isError: !result.success,- },- wasInitialized: undefined,- sandboxCreated: sandboxCreatedFlag,- sandboxInfo,- };+ return {+ result: {+ content: [{ type: 'text', text: JSON.stringify(result) }],+ isError: !result.success,+ },+ wasInitialized: undefined,+ sandboxCreated: sandboxCreatedFlag,+ sandboxInfo,+ };+ } catch (error) {+ if (!(error instanceof SandboxNotAvailableError) || sandboxCreated !== undefined) {+ throw error;+ }+ const recreated = await this.recreateAfterUnavailable();+ await this.ensureSandboxInitialized();+ const recreatedRawId = this.providerSandboxId(recreated.sandboxInfo.sandbox_id);+ const retryCodeModeEnv = await this.ensureCodeModeStarted(recreatedRawId);+ const retryEnv = {+ ...injectMCPClientEnv({+ env: input.env,+ mcpServers: this.buildMcpServersEnvelope(),+ codeModeEnv: retryCodeModeEnv,+ mcpClientInstall: this.mcpClientInstall,+ }),+ ...(this.resolvedGitCredentialsContent !== null+ ? buildGitCredentialHelperEnv(this.provider.getGitCredentialsPath(recreatedRawId))+ : {}),+ };+ const retryResult = await this.provider.exec({+ sandboxId: recreatedRawId,+ command: input.command,+ cwd: input.cwd,+ env: retryEnv,+ });+ return {+ result: {+ content: [{ type: 'text', text: JSON.stringify(retryResult) }],+ isError: !retryResult.success,+ },+ wasInitialized: undefined,+ sandboxCreated: true,+ sandboxInfo: recreated.sandboxInfo,+ };+ }}async getToolResultDumpDir(): Promise<{ dir: string; sandboxCreated: SandboxInfo | undefined }> {- const { sandboxCreated } = await this.ensureSandboxCreated();- const dir = this.provider.getToolResultDumpDir(this.requiredSandboxInfo.sandbox_id).replace(/\/+$/, '');+ const { sandboxCreated, sandboxInfo } = await this.ensureSandboxCreated();+ const dir = this.provider.getToolResultDumpDir(this.providerSandboxId(sandboxInfo.sandbox_id)).replace(/\/+$/, '');return { dir, sandboxCreated };}@@ -523,26 +616,30 @@ export class Sandbox extends LocalToolMCP {fileName: string;content: Buffer;}): Promise<{ filePath: string; sandboxCreated: SandboxInfo | undefined }> {- const { sandboxCreated } = await this.ensureSandboxCreated();- await this.ensureSandboxInitialized();- const { sandbox_id: sandboxId } = this.requiredSandboxInfo;+ const { sandboxCreated, sandboxInfo } = await this.ensureReadySandbox();const fileName = params.fileName.replace(/^\/+/, '');const targetDir = params.targetDir.replace(/\/+$/, '');const filePath = `${targetDir}/${fileName}`;- await this.provider.uploadFile({ sandboxId, remotePath: filePath, content: params.content });+ await this.provider.uploadFile({+ sandboxId: this.providerSandboxId(sandboxInfo.sandbox_id),+ remotePath: filePath,+ content: params.content,+ });return { filePath, sandboxCreated };}async uploadUserFile(input: { fileName: string; content: Buffer; mime: string }): Promise<SandboxStoredFile> {validateNoPathTraversal(input.fileName);+ const { sandboxCreated, sandboxInfo } = await this.ensureReadySandbox();const result = await this.uploadFile({- targetDir: Sandbox.FILE_UPLOADS_DIR,+ targetDir: this.provider.getFileUploadsDir(this.providerSandboxId(sandboxInfo.sandbox_id)),fileName: input.fileName,content: input.content,});+ const created = sandboxCreated ?? result.sandboxCreated;return {filePath: result.filePath,- ...(result.sandboxCreated && { sandboxCreated: result.sandboxCreated }),+ ...(created && { sandboxCreated: created }),};}@@ -578,7 +675,7 @@ export class Sandbox extends LocalToolMCP {}private async writeGitCredentials(): Promise<void> {- const sandboxId = this.requiredSandboxInfo.sandbox_id;+ const sandboxId = this.providerSandboxId(this.requiredSandboxInfo.sandbox_id);const credentialsPath = this.provider.getGitCredentialsPath(sandboxId);const result = await this.provider.exec({sandboxId,@@ -588,36 +685,70 @@ export class Sandbox extends LocalToolMCP {}private async initSandboxEnvironment(): Promise<void> {- const toolResultDumpDir = this.provider.getToolResultDumpDir(this.requiredSandboxInfo.sandbox_id);+ const sandboxId = this.providerSandboxId(this.requiredSandboxInfo.sandbox_id);+ const fileUploadsDir = this.provider.getFileUploadsDir(sandboxId);+ const skillsDir = this.provider.getSkillsDir(sandboxId);+ const toolResultDumpDir = this.provider.getToolResultDumpDir(sandboxId);this.logger.info('Uploading MCP client script and preparing skills directory in sandbox');- const initSteps = [- `mkdir -p ${MCP_CLIENT_DIR} ${Sandbox.FILE_UPLOADS_DIR} ${toolResultDumpDir} ${SKILLS_DIR}`,- `rm -f ${MCP_CLIENT_PATH}`,- `echo '${this.mcpClientScriptBase64}' | base64 -d > ${MCP_CLIENT_PATH}`,- // Make executable + symlink onto PATH so `mcp-client` runs by name.- `chmod 0555 ${MCP_CLIENT_PATH}`,- `ln -sf ${MCP_CLIENT_PATH} ${MCP_CLIENT_BIN_SYMLINK}`,- ];+ this.mcpClientInstall = this.codeModeTransport?.getClientInstall({ sandboxId });+ const install = this.mcpClientInstall;++ const dirs = [shellEscape(fileUploadsDir), shellEscape(toolResultDumpDir), shellEscape(skillsDir)];+ if (install !== undefined) {+ const { pythonPath, binDir } = mcpClientLayout(install.remotePath);+ dirs.push(shellEscape(pythonPath));+ // Layout bin is only for providers that put that dir on PATH (no image-PATH symlink).+ if (install.pathBinSymlink === undefined) {+ dirs.push(shellEscape(binDir));+ }+ }+ ensureExecSuccess(await this.provider.exec({ sandboxId, command: `mkdir -p ${dirs.join(' ')}` }));++ const initSteps: string[] = [];+ if (install !== undefined) {+ await this.provider.uploadFile({+ sandboxId,+ remotePath: install.remotePath,+ content: Buffer.from(install.content, 'utf-8'),+ });+ initSteps.push(`chmod 0555 ${shellEscape(install.remotePath)}`);+ if (install.pathBinSymlink !== undefined) {+ initSteps.push(`ln -sf ${shellEscape(install.remotePath)} ${shellEscape(install.pathBinSymlink)}`);+ } else {+ // Link target is relative to binDir (`mcp-client/mcp_client.py` from `mcp-client/bin`+ // would resolve to `mcp-client/bin/mcp-client/mcp_client.py`).+ const { binDir, binLink } = mcpClientLayout(install.remotePath);+ initSteps.push(`ln -sf ${shellEscape(relative(binDir, install.remotePath))} ${shellEscape(binLink)}`);+ }+ }// Fold skill installation into this single init exec. The mounter returns a declarative// command + env + timeout; runs even when empty so its downloader can prune a reused sandbox.- const skillInit = this.skillMounter?.getSandboxInit();+ const skillInit = this.skillMounter?.getSandboxInit({+ skillsDir,+ gitDownloaderPath: this.provider.getGitDownloaderPath(sandboxId),+ });if (skillInit) {initSteps.push(skillInit.command);}- const script = initSteps.join(' && ');- const result = await this.provider.exec({- sandboxId: this.requiredSandboxInfo.sandbox_id,- command: script,- env: skillInit?.env,- timeoutSeconds: skillInit?.timeoutSeconds,- });- ensureExecSuccess(result);+ if (initSteps.length > 0) {+ ensureExecSuccess(+ await this.provider.exec({+ sandboxId,+ command: initSteps.join(' && '),+ env: skillInit?.env,+ timeoutSeconds: skillInit?.timeoutSeconds,+ }),+ );+ }+this.logger.info(- `Sandbox initialized: MCP client at ${MCP_CLIENT_PATH} (symlinked to ${MCP_CLIENT_BIN_SYMLINK}); skills dir ${SKILLS_DIR}`,+ install === undefined+ ? `Sandbox initialized: skills dir ${skillsDir}`+ : `Sandbox initialized: MCP client at ${install.remotePath}; skills dir ${skillsDir}`,);await this.writeGitCredentials();diff --git a/packages/trueforge-core/src/core/sandbox/SandboxErrors.ts b/packages/trueforge-core/src/core/sandbox/SandboxErrors.tsindex 5b1dd5388..01f903caf 100644--- a/packages/trueforge-core/src/core/sandbox/SandboxErrors.ts+++ b/packages/trueforge-core/src/core/sandbox/SandboxErrors.ts@@ -1,7 +1,7 @@export abstract class SandboxError extends Error {/**- * Every sandbox failure is caused by the request itself — a bad path, another tenant's sandbox,- * a missing or oversized file — so each subclass carries the status a host should reply with.+ * Every sandbox failure is caused by the request itself — a bad path, a missing+ * or oversized file — so each subclass carries the status a host should reply with.* Listing the codes in use rather than `number` lets a typed route return this directly; adding* a subclass with a new code means widening this union and declaring it on the route.*/@@ -57,6 +57,14 @@ class SandboxTenantMismatchError extends SandboxError {}}+/** Daytona/TFY raw ids are `tenantName.<uuid>`. Fancy ids and local paths must not be passed here. */+export function validateSandboxOwnedByTenant(params: { sandboxId: string; tenantName: string }): void {+ const dotIndex = params.sandboxId.indexOf('.');+ if (dotIndex === -1 || params.sandboxId.slice(0, dotIndex) !== params.tenantName) {+ throw new SandboxTenantMismatchError(params.tenantName);+ }+}+class SandboxPathTraversalError extends SandboxError {readonly statusCode = 400;@@ -66,13 +74,6 @@ class SandboxPathTraversalError extends SandboxError {}}-export function validateSandboxOwnedByTenant(sandboxId: string, tenantName: string): void {- const dotIndex = sandboxId.indexOf('.');- if (dotIndex === -1 || sandboxId.substring(0, dotIndex) !== tenantName) {- throw new SandboxTenantMismatchError(tenantName);- }-}-const PATH_TRAVERSAL_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/;export function validateNoPathTraversal(path: string): void {diff --git a/packages/trueforge-core/src/core/sandbox/codeMode/CodeModeTransport.ts b/packages/trueforge-core/src/core/sandbox/codeMode/CodeModeTransport.tsindex 3a144b7b9..c5c0f42d5 100644--- a/packages/trueforge-core/src/core/sandbox/codeMode/CodeModeTransport.ts+++ b/packages/trueforge-core/src/core/sandbox/codeMode/CodeModeTransport.ts@@ -1,10 +1,31 @@import type { CodeModeDispatcher } from './CodeModeDispatcher';+/** Payload for installing the Code Mode MCP client into a sandbox filesystem. */+export interface CodeModeClientInstall {+ /** UTF-8 Python source (installed as mcp_client.py). */+ content: string;+ /**+ * Path for the Python module file inside the sandbox FS.+ * Absolute when the provider has a real FS (Daytona); cwd-relative when exec cwd is the jail (TFY, local).+ */+ remotePath: string;+ /**+ * Optional CLI symlink on a directory already on the default PATH (Daytona: `/usr/local/bin/mcp-client`).+ * When set, Sandbox skips `dirname(remotePath)/bin/mcp-client` — the symlink is the shell CLI.+ */+ pathBinSymlink?: string | undefined;+}+/*** 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 {+ /**+ * MCP client script + install path for this transport (sync; no listen required).+ * Sandbox applies the install during init; channel env still comes from `start`.+ */+ getClientInstall(params: { sandboxId: string }): CodeModeClientInstall;/*** Lazy connect/listen; may be called again after a failed attempt (non-sticky).* Idempotent once successfully started.diff --git a/packages/trueforge-core/src/core/sandbox/codeMode/nats/CodeModeNatsTransport.ts b/packages/trueforge-core/src/core/sandbox/codeMode/nats/CodeModeNatsTransport.tsindex 6ef7d9698..d028c716f 100644--- a/packages/trueforge-core/src/core/sandbox/codeMode/nats/CodeModeNatsTransport.ts+++ b/packages/trueforge-core/src/core/sandbox/codeMode/nats/CodeModeNatsTransport.ts@@ -7,8 +7,9 @@ import { WebSocket } from 'ws';import { extractErrorLogFields } from '../../../util/errorLogFields';import { withTimeout } from '../../../util/promiseUtils';import { DEFAULT_SANDBOX_NATS_WS_PORT } from '../../constants';+import { sandboxScripts } from '../../sandboxScripts.gen';import type { CodeModeDispatcher } from '../CodeModeDispatcher';-import type { CodeModeTransport } from '../CodeModeTransport';+import type { CodeModeClientInstall, 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@@ -36,14 +37,29 @@ export class CodeModeNatsTransport implements CodeModeTransport {private nc: NatsConnection | undefined;private dispatcher: CodeModeDispatcher | undefined;+ private readonly mcpClientRemotePath: string;+ private readonly mcpClientPathBinSymlink: string | undefined;+constructor(params: {resolveHostUrl: (sandboxId: string) => Promise<string>;sandboxClientNatsUrl?: string;logger: Logger;+ /** Provider-owned MCP client layout (absolute or cwd-relative). */+ mcpClientInstall: { remotePath: string; pathBinSymlink?: string | undefined };}) {this.resolveHostUrl = params.resolveHostUrl;this.sandboxClientNatsUrl = params.sandboxClientNatsUrl ?? `ws://localhost:${String(DEFAULT_SANDBOX_NATS_WS_PORT)}`;this.logger = params.logger.child({ module: 'CodeModeNatsTransport' });+ this.mcpClientRemotePath = params.mcpClientInstall.remotePath;+ this.mcpClientPathBinSymlink = params.mcpClientInstall.pathBinSymlink;+ }++ getClientInstall(): CodeModeClientInstall {+ return {+ content: sandboxScripts.mcpClient,+ remotePath: this.mcpClientRemotePath,+ ...(this.mcpClientPathBinSymlink === undefined ? {} : { pathBinSymlink: this.mcpClientPathBinSymlink }),+ };}start(params: {diff --git a/packages/trueforge-core/src/core/sandbox/constants.ts b/packages/trueforge-core/src/core/sandbox/constants.tsindex 2bc24fc55..76fc1300c 100644--- a/packages/trueforge-core/src/core/sandbox/constants.ts+++ b/packages/trueforge-core/src/core/sandbox/constants.ts@@ -1,6 +1,3 @@-/** Stable directory inside the sandbox for user file uploads (mkdir during sandbox init). */-export const SANDBOX_FILE_UPLOADS_DIR = '/tmp/uploads';-/** Default port of the pod-local NATS WebSocket broker used by the sandbox→gateway MCP bridge. */export const DEFAULT_SANDBOX_NATS_WS_PORT = 4444;diff --git a/packages/trueforge-core/src/core/sandbox/provider/DaytonaProvider.ts b/packages/trueforge-core/src/core/sandbox/provider/DaytonaProvider.tsindex e07273a62..1fba52e16 100644--- a/packages/trueforge-core/src/core/sandbox/provider/DaytonaProvider.ts+++ b/packages/trueforge-core/src/core/sandbox/provider/DaytonaProvider.ts@@ -2,7 +2,8 @@ import type { Sandbox, Snapshot } from '@daytona/sdk';import { Daytona, DaytonaError } from '@daytona/sdk';import { context } from '@opentelemetry/api';import { suppressTracing } from '@opentelemetry/core';-import { randomUUID } from 'crypto';+import { randomUUID } from 'node:crypto';+import { join } from 'node:path/posix';import type { Logger } from 'winston';import { extractErrorLogFields } from '../../util/errorLogFields';import {@@ -10,6 +11,7 @@ import {SandboxFileTooLargeError,SandboxNotAvailableError,SandboxPathIsDirectoryError,+ validateSandboxOwnedByTenant,} from '../SandboxErrors';import type { CodeModeTransport } from '../codeMode/CodeModeTransport';import { CodeModeNatsTransport } from '../codeMode/nats/CodeModeNatsTransport';@@ -100,6 +102,7 @@ export interface DaytonaSandboxProviderOptions {}export class DaytonaSandboxProvider implements SandboxProvider {+ readonly type = 'daytona';private readonly tenantName: string;/** Release-owned sandbox image reference; built into a Daytona snapshot and cloned per sandbox. */private readonly imageUri: string;@@ -139,6 +142,7 @@ export class DaytonaSandboxProvider implements SandboxProvider {private async getOrCreateSandbox(sandboxId?: string): Promise<{ sandbox: Sandbox; defaultTimeoutMs: number }> {if (sandboxId) {+ validateSandboxOwnedByTenant({ sandboxId, tenantName: this.tenantName });const cached = DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);if (cached) {return cached;@@ -396,6 +400,9 @@ export class DaytonaSandboxProvider implements SandboxProvider {});} catch (e: unknown) {DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);+ if (e instanceof SandboxNotAvailableError) {+ throw e;+ }this.logger.error('Sandbox execution error', extractErrorLogFields(e));const message = e instanceof Error ? e.message : 'Unknown error';return { success: false, error: message };@@ -480,6 +487,10 @@ export class DaytonaSandboxProvider implements SandboxProvider {},sandboxClientNatsUrl: `ws://localhost:${String(this.natsBridgePort)}`,logger: this.logger,+ mcpClientInstall: {+ remotePath: join('/opt', 'tf', 'mcp-client', 'mcp_client.py'),+ pathBinSymlink: join('/usr', 'local', 'bin', 'mcp-client'),+ },});}@@ -487,12 +498,26 @@ export class DaytonaSandboxProvider implements SandboxProvider {return undefined;}+ // Isolated container: image-absolute layout. GIT_CONFIG store --file needs an absolute path.+ // /opt/tf/{uploads,skills,tool-results,git_downloader.py,.git-credentials}+ // /opt/tfy/mcp-client/mcp_client.py + /usr/local/bin/mcp-client (image PATH; no layout bin)getToolResultDumpDir(): string {- return '/tmp/tool-results';+ return join('/opt', 'tf', 'tool-results');}getGitCredentialsPath(): string {- // Isolated container per sandbox; absolute path so GIT_CONFIG_* needs no $HOME expansion.- return '/tmp/.git-credentials';+ return join('/opt', 'tf', '.git-credentials');+ }++ getFileUploadsDir(): string {+ return join('/opt', 'tf', 'uploads');+ }++ getSkillsDir(): string {+ return join('/opt', 'tf', 'skills');+ }++ getGitDownloaderPath(): string {+ return join('/opt', 'tf', 'git_downloader.py');}}diff --git a/packages/trueforge-core/src/core/sandbox/provider/Provider.ts b/packages/trueforge-core/src/core/sandbox/provider/Provider.tsindex b2325359c..6801c239d 100644--- a/packages/trueforge-core/src/core/sandbox/provider/Provider.ts+++ b/packages/trueforge-core/src/core/sandbox/provider/Provider.ts@@ -65,6 +65,8 @@ export interface SandboxBuild {}export interface SandboxProvider {+ /** Stable provider kind used in fancy sandbox ids and carry-forward (plain string). */+ readonly type: string;/*** Ensures the release image is being built into the provider's backing store and* returns its current status. Idempotent: an already-built image reports `ready`;@@ -79,8 +81,18 @@ export interface SandboxProvider {getAdditionalInstructions(): string | undefined;/** Directory inside the sandbox where large tool responses are dumped. */getToolResultDumpDir(sandboxId: string): string;- /** Absolute path for the git credential-store file (per logical sandbox when sharing a pod). */+ /**+ * Git credential-store file (absolute, or cwd-relative when exec cwd is the jail).+ * `GIT_CONFIG` `store --file` is relative to the git process cwd — providers that+ * return a relative path must make it absolute in their own `exec`.+ */getGitCredentialsPath(sandboxId: string): string;+ /** Directory for user-uploaded files (absolute, or cwd-relative when the provider has no global FS). */+ getFileUploadsDir(sandboxId: string): string;+ /** Directory where git skills are materialized. */+ getSkillsDir(sandboxId: string): string;+ /** Path the git skill downloader script is written to before it runs. */+ getGitDownloaderPath(sandboxId: string): string;/** Downloads a file from the sandbox as a Buffer. Throws SandboxFileNotFoundError / SandboxNotAvailableError / SandboxPathIsDirectoryError / SandboxFileTooLargeError. */downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer>;/** Uploads a file to the sandbox. */diff --git a/packages/trueforge-core/src/core/sandbox/provider/TFYSandboxProvider.ts b/packages/trueforge-core/src/core/sandbox/provider/TFYSandboxProvider.tsindex 7b51354fe..4dc6a05f2 100644--- a/packages/trueforge-core/src/core/sandbox/provider/TFYSandboxProvider.ts+++ b/packages/trueforge-core/src/core/sandbox/provider/TFYSandboxProvider.ts@@ -1,15 +1,23 @@import { context } from '@opentelemetry/api';import { suppressTracing } from '@opentelemetry/core';-import { randomUUID } from 'crypto';import dedent from 'dedent';+import { randomUUID } from 'node:crypto';+import { join } from 'node:path/posix';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 {+ SandboxFileNotFoundError,+ SandboxFileTooLargeError,+ SandboxPathIsDirectoryError,+ validateSandboxOwnedByTenant,+} from '../SandboxErrors';+import { absolutizeRelativeExecEnv } from './execEnv';import {ensureExecSuccess,+ shellEscape,type ExecResult,type SandboxBuild,type SandboxExecParams,@@ -21,10 +29,21 @@ const DEFAULT_TIMEOUT_SECONDS = 60;// Buffer for network latency + response processing on top of the server-side timeout.const CLIENT_TIMEOUT_BUFFER_SECONDS = 5;-// Wraps a value in single quotes for safe use in shell commands.-// Inner single quotes are escaped via the standard shell idiom: ' → '\''-function shellEscape(value: string): string {- return `'${value.replace(/'/g, "'\\''")}'`;+const TFY_MCP_CLIENT_BIN = 'mcp-client/bin';++/** Put the layout CLI first on PATH (cwd-relative; {@link absolutizeRelativeExecEnv} makes it absolute). */+export function withMcpClientOnPath(path: string): string {+ const rest = path.split(':').filter(part => part.length > 0 && part !== TFY_MCP_CLIENT_BIN);+ return rest.length === 0 ? TFY_MCP_CLIENT_BIN : `${TFY_MCP_CLIENT_BIN}:${rest.join(':')}`;+}++function parsePwdAndPath(text: string): { root: string; inheritedPath: string } | undefined {+ const lines = text.replace(/\r\n/g, '\n').split('\n');+ const root = lines[0];+ if (!root?.startsWith('/')) {+ return undefined;+ }+ return { root, inheritedPath: lines[1] ?? '' };}export interface TFYSandboxProviderOptions {@@ -42,12 +61,15 @@ interface StatResult {}export class TFYSandboxProvider implements SandboxProvider {+ readonly type = 'tfy';private readonly serverUrl: string;private readonly natsBridgeUrl: string;private readonly tenantName: string;private readonly fileMaxBytesForDownload: number;private readonly defaultExecTimeoutSeconds: number;private readonly logger: Logger;+ /** Discovered via `pwd` + `$PATH` — never a hardcoded host layout. */+ private readonly sandboxLayouts = new Map<string, { root: string; inheritedPath: string }>();constructor(options: TFYSandboxProviderOptions) {this.serverUrl = options.serverUrl.replace(/\/+$/, '');@@ -79,7 +101,43 @@ export class TFYSandboxProvider implements SandboxProvider {return Promise.resolve({ sandboxId });}+ /**+ * No extra FS jail: exec cwd is the logical sandbox root. Layout getters are cwd-relative+ * so writes cannot escape it. `GIT_CONFIG` / PATH / PYTHONPATH must still be absolute so+ * git and `mcp-client` work after `cd` — resolved from `pwd` / `$PATH`, not a hardcoded prefix.+ */async exec(params: SandboxExecParams): Promise<ExecResult> {+ validateSandboxOwnedByTenant({ sandboxId: params.sandboxId, tenantName: this.tenantName });+ const { root, inheritedPath } = await this.sandboxLayout(params.sandboxId);+ const incoming = params.env ?? {};+ const env = absolutizeRelativeExecEnv({+ root,+ env: { ...incoming, PATH: withMcpClientOnPath(incoming['PATH'] ?? inheritedPath) },+ });+ return this.postExec({ ...params, env });+ }++ private async sandboxLayout(sandboxId: string): Promise<{ root: string; inheritedPath: string }> {+ const cached = this.sandboxLayouts.get(sandboxId);+ if (cached !== undefined) {+ return cached;+ }+ const result = await this.postExec({+ sandboxId,+ command: 'printf \'%s\\n%s\\n\' "$(pwd)" "$PATH"',+ });+ if (!result.success) {+ throw new Error(`Failed to resolve sandbox working directory: ${result.error}`);+ }+ const parsed = parsePwdAndPath(result.response.result);+ if (parsed === undefined) {+ throw new Error(`sandbox pwd did not return an absolute path: ${result.response.result}`);+ }+ this.sandboxLayouts.set(sandboxId, parsed);+ return parsed;+ }++ private async postExec(params: SandboxExecParams): Promise<ExecResult> {return context.with(suppressTracing(context.active()), async (): Promise<ExecResult> => {// Honor the per-call timeout (e.g. the longer skill-download timeout) for both the server-side// request timeout and the client abort timer; fall back to the provider default otherwise.@@ -186,23 +244,39 @@ export class TFYSandboxProvider implements SandboxProvider {resolveHostUrl: () => Promise.resolve(this.natsBridgeUrl),sandboxClientNatsUrl: `ws://localhost:${String(DEFAULT_SANDBOX_NATS_WS_PORT)}`,logger: this.logger,+ mcpClientInstall: { remotePath: join('mcp-client', 'mcp_client.py') },});}getAdditionalInstructions(): string {return dedent`SANDBOX RULES:- - 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.+ - uploads, skills, and tool-results live in the sandbox working directory (not /tmp or /opt).+ - ALL file creation and writes MUST stay within the sandbox working directory.- The Agent must NOT write to /tmp/, ~/, or any absolute path outside the working directory.`;}- getToolResultDumpDir(sandboxId: string): string {- return `/tmp/${sandboxId}/tool-results`;+ // Cwd-relative (no FS jail). exec() pwd-joins GIT_CONFIG / PATH / PYTHONPATH.+ // uploads, skills, tool-results, git_downloader.py, .git-credentials+ // mcp-client/mcp_client.py (no /usr/local/bin symlink)+ getToolResultDumpDir(): string {+ return 'tool-results';+ }++ getGitCredentialsPath(): string {+ return '.git-credentials';+ }++ getFileUploadsDir(): string {+ return 'uploads';+ }++ getSkillsDir(): string {+ return 'skills';}- getGitCredentialsPath(sandboxId: string): string {- return `/tmp/${sandboxId}/.git-credentials`;+ getGitDownloaderPath(): string {+ return 'git_downloader.py';}}diff --git a/packages/trueforge-core/src/core/sandbox/provider/execEnv.ts b/packages/trueforge-core/src/core/sandbox/provider/execEnv.tsnew file mode 100644index 000000000..9c919342f--- /dev/null+++ b/packages/trueforge-core/src/core/sandbox/provider/execEnv.ts@@ -0,0 +1,35 @@+import { join } from 'node:path/posix';++const GIT_STORE_FILE_PREFIX = 'store --file ';++function resolveMaybeRelative(params: { root: string; path: string }): string {+ return params.path.startsWith('/') ? params.path : join(params.root, params.path);+}++/** Make cwd-relative PATH / PYTHONPATH / GIT_CONFIG store --file / TFY_SKILLS_DIR usable from any cwd. */+export function absolutizeRelativeExecEnv(params: {+ root: string;+ env: Record<string, string>;+}): Record<string, string> {+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(params.env)) {+ if (key === 'PATH' || key === 'PYTHONPATH') {+ out[key] = value+ .split(':')+ .map(part => (part.length === 0 ? part : resolveMaybeRelative({ root: params.root, path: part })))+ .join(':');+ continue;+ }+ if (key === 'TFY_SKILLS_DIR' || key === 'VIRTUAL_ENV') {+ out[key] = resolveMaybeRelative({ root: params.root, path: value });+ continue;+ }+ if (key.startsWith('GIT_CONFIG_VALUE_') && value.startsWith(GIT_STORE_FILE_PREFIX)) {+ const file = value.slice(GIT_STORE_FILE_PREFIX.length);+ out[key] = `${GIT_STORE_FILE_PREFIX}${resolveMaybeRelative({ root: params.root, path: file })}`;+ continue;+ }+ out[key] = value;+ }+ return out;+}diff --git a/packages/trueforge-core/src/core/sandbox/sandboxRef.ts b/packages/trueforge-core/src/core/sandbox/sandboxRef.tsnew file mode 100644index 000000000..d85127a1b--- /dev/null+++ b/packages/trueforge-core/src/core/sandbox/sandboxRef.ts@@ -0,0 +1,55 @@+export interface SandboxRefParts {+ /** Provider kind from `SandboxProvider.type` (e.g. `daytona`, `local`) — plain string, not a closed union. */+ providerType: string;+ rawId: string;+}++const SANDBOX_ID_VERSION = 'v1';+const SANDBOX_ID_PREFIX = `${SANDBOX_ID_VERSION}:`;++/** `v1:type:raw` — raw may contain `:` (split only on the first two colons after version). */+export function formatSandboxId(parts: SandboxRefParts): string {+ return `${SANDBOX_ID_PREFIX}${parts.providerType}:${parts.rawId}`;+}++/**+ * Parse a fancy id. No `v1:` prefix, or a malformed `v1:` (too few segments),+ * → `{ kind: 'legacy', rawId: fullString }` so carry-forward stays safe.+ */+export function parseSandboxId(+ sandboxId: string,+): { kind: 'v1'; parts: SandboxRefParts } | { kind: 'legacy'; rawId: string } {+ if (!sandboxId.startsWith(SANDBOX_ID_PREFIX)) {+ return { kind: 'legacy', rawId: sandboxId };+ }+ const rest = sandboxId.slice(SANDBOX_ID_PREFIX.length);+ const colon = rest.indexOf(':');+ if (colon <= 0 || colon === rest.length - 1) {+ return { kind: 'legacy', rawId: sandboxId };+ }+ return {+ kind: 'v1',+ parts: { providerType: rest.slice(0, colon), rawId: rest.slice(colon + 1) },+ };+}++/** Raw id for provider calls. Legacy ids pass through unchanged. */+export function rawSandboxId(sandboxId: string): string {+ const parsed = parseSandboxId(sandboxId);+ return parsed.kind === 'v1' ? parsed.parts.rawId : parsed.rawId;+}++/** Carry-forward gate for turn admit / download. Type mismatch drops the id (create fresh). */+export function existingSandboxIdForProvider(params: {+ existingSandboxId: string | undefined;+ currentProviderType: string;+}): string | undefined {+ if (params.existingSandboxId === undefined) {+ return undefined;+ }+ const parsed = parseSandboxId(params.existingSandboxId);+ if (parsed.kind === 'v1' && parsed.parts.providerType !== params.currentProviderType) {+ return undefined;+ }+ return params.existingSandboxId;+}diff --git a/packages/trueforge-core/src/core/sandbox/skills/ISkillMounter.ts b/packages/trueforge-core/src/core/sandbox/skills/ISkillMounter.tsindex afacd62c8..07fbd601e 100644--- a/packages/trueforge-core/src/core/sandbox/skills/ISkillMounter.ts+++ b/packages/trueforge-core/src/core/sandbox/skills/ISkillMounter.ts@@ -5,7 +5,7 @@ import type { SandboxInit } from '../provider/Provider';// holds one mounter and never inspects individual skills.export interface ISkillMounter {// Renders the <skills> section; adds nothing when empty, so InstructionBuilder drops the section.- instruction(builder: InstructionBuilder): void;+ instruction(builder: InstructionBuilder, paths: { skillsDir: string }): void;// The command (+ env, timeout) that installs these skills; Sandbox folds it into its init exec.- getSandboxInit(): SandboxInit;+ getSandboxInit(paths: { skillsDir: string; gitDownloaderPath: string }): SandboxInit;}diff --git a/packages/trueforge-core/src/core/sandbox/skills/SkillMounter.ts b/packages/trueforge-core/src/core/sandbox/skills/SkillMounter.tsindex 17156b7f0..6037b5be3 100644--- a/packages/trueforge-core/src/core/sandbox/skills/SkillMounter.ts+++ b/packages/trueforge-core/src/core/sandbox/skills/SkillMounter.ts@@ -5,9 +5,6 @@ import { sandboxScripts } from '../sandboxScripts.gen';import { SKILLS_PREAMBLE, getSkillPath, renderSkillPromptBody } from './constants';import type { ISkillMounter } from './ISkillMounter';-// Absolute path the git skill downloader script is uploaded to before it is run.-const GIT_DOWNLOADER_PATH = '/opt/tfy/git_downloader.py';-// A git-sourced skill materialized by a sparse clone in the sandbox (git_downloader.py). Git skills// never preload — their SKILL.md is read from disk at runtime (only name/description/path are// advertised in the prompt). Wire fields match the agent_spec git mount (`url`/`path`/`name`/`ref`);@@ -38,7 +35,7 @@ export class SkillMounter implements ISkillMounter {this.skills = skills;}- instruction(builder: InstructionBuilder): void {+ instruction(builder: InstructionBuilder, paths: { skillsDir: string }): void {if (this.skills.length === 0) {return;}@@ -47,7 +44,7 @@ export class SkillMounter implements ISkillMounter {builder.addSection('skill',renderSkillPromptBody({- path: getSkillPath(skill.name),+ path: getSkillPath({ skillsDir: paths.skillsDir, skillName: skill.name }),name: skill.name,description: skill.description,preloadContent: null,@@ -56,7 +53,7 @@ export class SkillMounter implements ISkillMounter {}}- getSandboxInit(): SandboxInit {+ getSandboxInit(paths: { skillsDir: string; gitDownloaderPath: string }): SandboxInit {// An empty desired set is also the source-neutral cleanup path for a reused sandbox.const specs: GitSkillSpec[] = this.skills.map(skill => ({name: skill.name,@@ -67,11 +64,11 @@ export class SkillMounter implements ISkillMounter {const gitSkillsB64 = Buffer.from(JSON.stringify(specs)).toString('base64');return {command: buildWriteAndRunScriptCommand({- scriptPath: GIT_DOWNLOADER_PATH,+ scriptPath: paths.gitDownloaderPath,// Bundled at build time (sandboxScripts.gen.ts) so the packaged library has no loose files.scriptContent: sandboxScripts.gitDownloader,}),- env: { AGENT_GIT_SKILLS: gitSkillsB64 },+ env: { AGENT_GIT_SKILLS: gitSkillsB64, TFY_SKILLS_DIR: paths.skillsDir },timeoutSeconds: SKILL_DOWNLOAD_TIMEOUT_SECONDS,};}diff --git a/packages/trueforge-core/src/core/sandbox/skills/constants.ts b/packages/trueforge-core/src/core/sandbox/skills/constants.tsindex 8ef328f61..e51a9ba21 100644--- a/packages/trueforge-core/src/core/sandbox/skills/constants.ts+++ b/packages/trueforge-core/src/core/sandbox/skills/constants.ts@@ -1,11 +1,8 @@// Skill prompt constants and helpers: how skills are described to the agent in the system prompt.-// Directory inside the sandbox where every skill (whatever its origin) is materialized.-export const SKILLS_DIR = '/opt/tfy/skills';-// On-disk directory a skill is materialized into, keyed by its (unique) name.-export function getSkillPath(skillName: string): string {- return `${SKILLS_DIR}/${skillName}`;+export function getSkillPath(params: { skillsDir: string; skillName: string }): string {+ return `${params.skillsDir.replace(/\/+$/, '')}/${params.skillName}`;}export const SKILLS_PREAMBLE = [diff --git a/packages/trueforge-core/src/core/sandbox/skills/index.ts b/packages/trueforge-core/src/core/sandbox/skills/index.tsindex 4940b6927..23636c14b 100644--- a/packages/trueforge-core/src/core/sandbox/skills/index.ts+++ b/packages/trueforge-core/src/core/sandbox/skills/index.ts@@ -1,4 +1,4 @@-export { SKILLS_DIR, SKILLS_PREAMBLE, getSkillPath, renderSkillPromptBody } from './constants';+export { SKILLS_PREAMBLE, getSkillPath, renderSkillPromptBody } from './constants';export type { ISkillMounter } from './ISkillMounter';export { SkillMounter } from './SkillMounter';export type { GitSkill } from './SkillMounter';diff --git a/packages/trueforge-core/tests/core/harnessMocks.ts b/packages/trueforge-core/tests/core/harnessMocks.tsindex ef12abd41..22d110b5f 100644--- a/packages/trueforge-core/tests/core/harnessMocks.ts+++ b/packages/trueforge-core/tests/core/harnessMocks.ts@@ -55,8 +55,9 @@ export function makeMockIMCPServer(params: {};}-export function makeStubPublicSandbox(tenantName = 'test-tenant'): Sandbox {+export function makeStubPublicSandbox(): Sandbox {const provider: SandboxProvider = {+ type: 'test',buildImage: jest.fn(),getImageBuildStatus: jest.fn(),createSandbox: jest.fn(),@@ -64,6 +65,9 @@ export function makeStubPublicSandbox(tenantName = 'test-tenant'): Sandbox {getAdditionalInstructions: () => undefined,getToolResultDumpDir: () => '/tmp/tool-results',getGitCredentialsPath: () => '/tmp/.git-credentials',+ getFileUploadsDir: () => '/tmp/uploads',+ getSkillsDir: () => '/opt/tfy/skills',+ getGitDownloaderPath: () => '/opt/tfy/git_downloader.py',downloadFile: jest.fn(),uploadFile: jest.fn(),createCodeModeTransport: jest.fn(),@@ -73,7 +77,6 @@ export function makeStubPublicSandbox(tenantName = 'test-tenant'): Sandbox {blockDestructiveToolsInCodeMode: true,mcpRequestTimeoutMs: 60_000,mcpConnectTimeoutMs: 5_000,- tenantName,logger: makeSilentLogger(),tracing: NOOP_AGENT_TRACING,});diff --git a/packages/trueforge-core/tests/core/sandbox/Sandbox.ids.test.ts b/packages/trueforge-core/tests/core/sandbox/Sandbox.ids.test.tsnew file mode 100644index 000000000..27673b0ae--- /dev/null+++ b/packages/trueforge-core/tests/core/sandbox/Sandbox.ids.test.ts@@ -0,0 +1,110 @@+import { isCallToolResponseResult } from '../../../src/core/mcp/IMCPServer';+import type { ExecResult, SandboxExecParams, SandboxProvider } from '../../../src/core/sandbox/provider/Provider';+import { SANDBOX_EXEC_TOOL_NAME, Sandbox } from '../../../src/core/sandbox/Sandbox';+import { SandboxNotAvailableError } from '../../../src/core/sandbox/SandboxErrors';+import { NOOP_AGENT_TRACING } from '../../../src/core/tracing/NoopAgentTracing';+import { makeSilentLogger } from '../harnessMocks';++function readyExec(): Promise<ExecResult> {+ return Promise.resolve({ success: true, response: { exitCode: 0, result: 'ok' } });+}++function makeProvider(+ overrides: Partial<SandboxProvider> & Pick<SandboxProvider, 'createSandbox' | 'exec'>,+): SandboxProvider {+ return {+ type: 'local',+ buildImage: () => Promise.resolve({ status: 'ready', reason: null, metadata: null }),+ getImageBuildStatus: () => Promise.resolve({ status: 'ready', reason: null, metadata: null }),+ getAdditionalInstructions: () => undefined,+ getToolResultDumpDir: sandboxId => `${sandboxId}/tool-results`,+ getGitCredentialsPath: sandboxId => `${sandboxId}/.git-credentials`,+ getFileUploadsDir: sandboxId => `${sandboxId}/uploads`,+ getSkillsDir: sandboxId => `${sandboxId}/skills`,+ getGitDownloaderPath: sandboxId => `${sandboxId}/git_downloader.py`,+ downloadFile: jest.fn(),+ uploadFile: jest.fn().mockResolvedValue(undefined),+ createCodeModeTransport: jest.fn(),+ ...overrides,+ };+}++function makeSandbox(provider: SandboxProvider, existingSandboxId?: string): Sandbox {+ return new Sandbox({+ provider,+ existingSandboxId,+ blockDestructiveToolsInCodeMode: true,+ mcpRequestTimeoutMs: 60_000,+ mcpConnectTimeoutMs: 5_000,+ logger: makeSilentLogger(),+ tracing: NOOP_AGENT_TRACING,+ });+}++describe('Sandbox fancy ids', () => {+ it('wraps createSandbox raw id as v1:type:raw and calls the provider with raw', async () => {+ const execCalls: SandboxExecParams[] = [];+ const provider = makeProvider({+ createSandbox: () => Promise.resolve({ sandboxId: '/tmp/raw-1' }),+ exec: params => {+ execCalls.push(params);+ return readyExec();+ },+ });+ const sandbox = makeSandbox(provider);+ const result = await sandbox.callTool({+ name: SANDBOX_EXEC_TOOL_NAME,+ arguments: { intent: 'pwd', command: 'pwd' },+ });+ if (!isCallToolResponseResult(result)) {+ throw new Error('expected tool result');+ }+ expect(result.sandboxInfo?.sandbox_id).toBe('v1:local:/tmp/raw-1');+ expect(result.sandboxCreated).toBe(true);+ expect(execCalls.every(call => call.sandboxId === '/tmp/raw-1')).toBe(true);+ });++ it('reattaches a fancy id using the raw id and recreates when the provider reports missing', async () => {+ let execCount = 0;+ const provider = makeProvider({+ createSandbox: jest.fn().mockResolvedValue({ sandboxId: '/tmp/raw-2' }),+ exec: params => {+ execCount += 1;+ if (params.sandboxId === '/tmp/gone') {+ throw new SandboxNotAvailableError(params.sandboxId);+ }+ return readyExec();+ },+ });+ const sandbox = makeSandbox(provider, 'v1:local:/tmp/gone');+ const result = await sandbox.callTool({+ name: SANDBOX_EXEC_TOOL_NAME,+ arguments: { intent: 'pwd', command: 'pwd' },+ });+ if (!isCallToolResponseResult(result)) {+ throw new Error('expected tool result');+ }+ expect(provider.createSandbox).toHaveBeenCalled();+ expect(result.sandboxInfo?.sandbox_id).toBe('v1:local:/tmp/raw-2');+ expect(result.sandboxCreated).toBe(true);+ expect(execCount).toBeGreaterThan(1);+ });++ it('passes a legacy existing id through to the provider unchanged', async () => {+ const execCalls: SandboxExecParams[] = [];+ const provider = makeProvider({+ createSandbox: jest.fn(),+ exec: params => {+ execCalls.push(params);+ return readyExec();+ },+ });+ const sandbox = makeSandbox(provider, 'tenant.legacy-id');+ await sandbox.callTool({+ name: SANDBOX_EXEC_TOOL_NAME,+ arguments: { intent: 'pwd', command: 'pwd' },+ });+ expect(provider.createSandbox).not.toHaveBeenCalled();+ expect(execCalls.every(call => call.sandboxId === 'tenant.legacy-id')).toBe(true);+ });+});diff --git a/packages/trueforge-core/tests/core/sandbox/Sandbox.paths.test.ts b/packages/trueforge-core/tests/core/sandbox/Sandbox.paths.test.tsnew file mode 100644index 000000000..7184725af--- /dev/null+++ b/packages/trueforge-core/tests/core/sandbox/Sandbox.paths.test.ts@@ -0,0 +1,106 @@+import { InstructionBuilder } from '../../../src/core/InstructionBuilder';+import type { CodeModeTransport } from '../../../src/core/sandbox/codeMode/CodeModeTransport';+import type { ExecResult, SandboxExecParams, SandboxProvider } from '../../../src/core/sandbox/provider/Provider';+import { SANDBOX_EXEC_TOOL_NAME, Sandbox } from '../../../src/core/sandbox/Sandbox';+import { NOOP_AGENT_TRACING } from '../../../src/core/tracing/NoopAgentTracing';+import { makeMockIMCPServer, makeSilentLogger } from '../harnessMocks';++function readyExec(): Promise<ExecResult> {+ return Promise.resolve({ success: true, response: { exitCode: 0, result: 'ok' } });+}++function makeProvider(overrides: Partial<SandboxProvider> = {}): SandboxProvider {+ return {+ type: 'test',+ buildImage: () => Promise.resolve({ status: 'ready', reason: null, metadata: null }),+ getImageBuildStatus: () => Promise.resolve({ status: 'ready', reason: null, metadata: null }),+ createSandbox: () => Promise.resolve({ sandboxId: 'raw-1' }),+ exec: () => readyExec(),+ getAdditionalInstructions: () => undefined,+ getToolResultDumpDir: () => '/prov/tool-results',+ getGitCredentialsPath: () => '/prov/.git-credentials',+ getFileUploadsDir: () => '/prov/uploads',+ getSkillsDir: () => '/prov/skills',+ getGitDownloaderPath: () => '/prov/git_downloader.py',+ downloadFile: jest.fn(),+ uploadFile: jest.fn().mockResolvedValue(undefined),+ createCodeModeTransport: jest.fn(),+ ...overrides,+ };+}++function makeSandbox(provider: SandboxProvider, options: { existingSandboxId?: string } = {}): Sandbox {+ return new Sandbox({+ provider,+ existingSandboxId: options.existingSandboxId,+ blockDestructiveToolsInCodeMode: true,+ mcpRequestTimeoutMs: 60_000,+ mcpConnectTimeoutMs: 5_000,+ logger: makeSilentLogger(),+ tracing: NOOP_AGENT_TRACING,+ });+}++describe('Sandbox provider-owned paths', () => {+ it('puts the provider uploads dir in the system prompt, not /tmp/uploads', () => {+ const sandbox = makeSandbox(makeProvider());+ const builder = new InstructionBuilder('root');+ sandbox.buildInstruction(builder);+ const prompt = builder.build();+ expect(prompt).toContain('/prov/uploads/');+ expect(prompt).not.toContain('/tmp/uploads');+ });++ it('uploads user files to the provider uploads dir', async () => {+ const uploadFile = jest.fn().mockResolvedValue(undefined);+ const provider = makeProvider({ uploadFile });+ const sandbox = makeSandbox(provider);+ const stored = await sandbox.uploadUserFile({+ fileName: 'notes.txt',+ content: Buffer.from('hi'),+ mime: 'text/plain',+ });+ expect(stored.filePath).toBe('/prov/uploads/notes.txt');+ expect(uploadFile).toHaveBeenCalledWith({+ sandboxId: 'raw-1',+ remotePath: '/prov/uploads/notes.txt',+ content: Buffer.from('hi'),+ });+ });++ it('does not rewrite a caller PATH (providers own PATH)', async () => {+ const execCalls: SandboxExecParams[] = [];+ const transport: CodeModeTransport = {+ getClientInstall: () => ({+ content: 'print("mock")\n',+ remotePath: 'mcp-client/mcp_client.py',+ }),+ start: () =>+ Promise.resolve({+ env: { TFY_NATS_URL: 'ws://localhost:4223', TFY_NATS_SUBJECT_PREFIX: 'sandbox.bridge.test' },+ }),+ stop: () => Promise.resolve(),+ };+ const sandbox = makeSandbox(+ makeProvider({+ exec: (params): Promise<ExecResult> => {+ execCalls.push(params);+ return readyExec();+ },+ uploadFile: jest.fn().mockResolvedValue(undefined),+ createCodeModeTransport: () => transport,+ }),+ );+ sandbox.configureCodeMode([makeMockIMCPServer({ name: 'github', preload: true })]);+ await sandbox.callTool({+ name: SANDBOX_EXEC_TOOL_NAME,+ arguments: { intent: 'Run command', command: 'true', env: { PATH: '/usr/bin' } },+ });+ const call = execCalls.find(item => item.command === 'true');+ expect(call?.env?.['PATH']).toBe('/usr/bin');+ expect(call?.env?.['PYTHONPATH']).toBe('mcp-client');+ const init = execCalls.find(item => item.command.includes('ln -sf'));+ expect(init?.command).toContain("ln -sf '../mcp_client.py'");+ expect(init?.command).toContain('mcp-client/bin/mcp-client');+ });+});diff --git a/packages/trueforge-core/tests/core/sandbox/daytonaSnapshotRegistration.test.ts b/packages/trueforge-core/tests/core/sandbox/daytonaSnapshotRegistration.test.tsindex 26414fb24..2c94b868d 100644--- a/packages/trueforge-core/tests/core/sandbox/daytonaSnapshotRegistration.test.ts+++ b/packages/trueforge-core/tests/core/sandbox/daytonaSnapshotRegistration.test.ts@@ -1,5 +1,6 @@import { Daytona, DaytonaError } from '@daytona/sdk';import { DaytonaSandboxProvider } from '../../../src/core/sandbox/provider/DaytonaProvider';+import { SandboxNotAvailableError } from '../../../src/core/sandbox/SandboxErrors';import { makeSilentLogger } from '../harnessMocks';const NOT_FOUND_STATUS = 404;@@ -78,3 +79,27 @@ describe('DaytonaSandboxProvider register-only snapshot create', () => {});});});++describe('DaytonaSandboxProvider exec', () => {+ it('rethrows SandboxNotAvailableError when the sandbox is gone', async () => {+ const client = new Daytona({ apiKey: 'dtn-test', useDeprecatedPolling: true });+ jest.spyOn(client, 'get').mockRejectedValue(new DaytonaError('not found', NOT_FOUND_STATUS));+ const provider = new DaytonaSandboxProvider({+ client,+ apiKey: 'dtn-test',+ apiUrl: API_URL,+ tenantName: 'test-tenant',+ sandboxImage: 'registry.example.com/sandbox:029ea5ff',+ timeoutMs: 1000,+ autoStopIntervalInMinutes: 5,+ autoArchiveIntervalInMinutes: 60,+ autoDeleteIntervalInMinutes: 7200,+ fileMaxBytesForDownload: 1024,+ logger: makeSilentLogger(),+ });++ await expect(provider.exec({ sandboxId: 'test-tenant.gone', command: 'true' })).rejects.toBeInstanceOf(+ SandboxNotAvailableError,+ );+ });+});diff --git a/packages/trueforge-core/tests/core/sandbox/provider/sandboxProviderContractSuite.ts b/packages/trueforge-core/tests/core/sandbox/provider/sandboxProviderContractSuite.tsindex 223f85d34..ca93ddb7c 100644--- a/packages/trueforge-core/tests/core/sandbox/provider/sandboxProviderContractSuite.ts+++ b/packages/trueforge-core/tests/core/sandbox/provider/sandboxProviderContractSuite.ts@@ -25,6 +25,19 @@ export function runSandboxProviderContractSuite(await fixture.dispose();}, 60_000);+ it('exec cwd is the sandbox root so relative layout paths work', async () => {+ const { sandboxId } = await fixture.provider.createSandbox();+ const result = await fixture.provider.exec({+ sandboxId,+ command: 'pwd && mkdir -p skills && test -d skills',+ });+ ensureExecSuccess(result);+ if (!result.success) {+ throw new Error('unreachable');+ }+ expect(result.response.result.trim().split('\n')[0]).toBe(sandboxId);+ });+it('exec is stateful across calls in the same sandbox', async () => {const { sandboxId } = await fixture.provider.createSandbox();const write = await fixture.provider.exec({diff --git a/packages/trueforge-core/tests/core/sandbox/provider/tfyLayout.test.ts b/packages/trueforge-core/tests/core/sandbox/provider/tfyLayout.test.tsnew file mode 100644index 000000000..8cdf834ef--- /dev/null+++ b/packages/trueforge-core/tests/core/sandbox/provider/tfyLayout.test.ts@@ -0,0 +1,56 @@+import { absolutizeRelativeExecEnv } from '../../../../src/core/sandbox/provider/execEnv';+import { TFYSandboxProvider, withMcpClientOnPath } from '../../../../src/core/sandbox/provider/TFYSandboxProvider';+import { makeSilentLogger } from '../../harnessMocks';++describe('TFYSandboxProvider layout', () => {+ it('keeps exec writes cwd-relative (no extra FS jail)', () => {+ const provider = new TFYSandboxProvider({+ serverUrl: 'http://sandbox.example',+ natsBridgeUrl: 'ws://nats.example',+ tenantName: 'acme',+ fileMaxBytesForDownload: 1024,+ logger: makeSilentLogger(),+ });+ const sandboxId = 'acme.00000000-0000-0000-0000-000000000001';+ const layout = [+ provider.getToolResultDumpDir(),+ provider.getGitCredentialsPath(),+ provider.getFileUploadsDir(),+ provider.getSkillsDir(),+ provider.getGitDownloaderPath(),+ ];+ for (const path of layout) {+ expect(path.startsWith('/')).toBe(false);+ }+ const install = provider.createCodeModeTransport().getClientInstall({ sandboxId });+ expect(install.remotePath.startsWith('/')).toBe(false);+ expect(install.pathBinSymlink).toBeUndefined();+ const instructions = provider.getAdditionalInstructions();+ expect(instructions).toContain('uploads, skills, and tool-results live in the sandbox working directory');+ expect(instructions).not.toContain('/data/sandboxes');+ });++ it('absolutizes GIT_CONFIG store --file and PATH for git/mcp-client after cd', () => {+ const env = absolutizeRelativeExecEnv({+ root: '/discovered/root',+ env: {+ GIT_CONFIG_VALUE_0: 'store --file .git-credentials',+ PATH: 'mcp-client/bin:/usr/bin',+ PYTHONPATH: 'mcp-client',+ TFY_SKILLS_DIR: 'skills',+ TFY_NATS_URL: 'ws://localhost',+ },+ });+ expect(env['GIT_CONFIG_VALUE_0']).toBe('store --file /discovered/root/.git-credentials');+ expect(env['PATH']).toBe('/discovered/root/mcp-client/bin:/usr/bin');+ expect(env['PYTHONPATH']).toBe('/discovered/root/mcp-client');+ expect(env['TFY_SKILLS_DIR']).toBe('/discovered/root/skills');+ expect(env['TFY_NATS_URL']).toBe('ws://localhost');+ });++ it('puts mcp-client/bin first on PATH without duplicating it', () => {+ expect(withMcpClientOnPath('')).toBe('mcp-client/bin');+ expect(withMcpClientOnPath('/usr/bin:/bin')).toBe('mcp-client/bin:/usr/bin:/bin');+ expect(withMcpClientOnPath('mcp-client/bin:/usr/bin')).toBe('mcp-client/bin:/usr/bin');+ });+});diff --git a/packages/trueforge-core/tests/core/sandbox/sandboxBridgeTimeout.test.ts b/packages/trueforge-core/tests/core/sandbox/sandboxBridgeTimeout.test.tsindex 8a9ecce97..c7b90c1b3 100644--- a/packages/trueforge-core/tests/core/sandbox/sandboxBridgeTimeout.test.ts+++ b/packages/trueforge-core/tests/core/sandbox/sandboxBridgeTimeout.test.ts@@ -17,6 +17,7 @@ function makeSandbox(options: {const execCalls: SandboxExecParams[] = [];const transport = options.transport;const provider: SandboxProvider = {+ type: 'test',buildImage: () => Promise.resolve({ status: 'ready', reason: null, metadata: null }),getImageBuildStatus: () => Promise.resolve({ status: 'ready', reason: null, metadata: null }),createSandbox: () => Promise.resolve({ sandboxId: 'test-tenant.sandbox-1' }),@@ -27,6 +28,9 @@ function makeSandbox(options: {getAdditionalInstructions: () => undefined,getToolResultDumpDir: () => '/tmp/tool-results',getGitCredentialsPath: () => '/tmp/.git-credentials',+ getFileUploadsDir: () => '/tmp/uploads',+ getSkillsDir: () => '/opt/tfy/skills',+ getGitDownloaderPath: () => '/opt/tfy/git_downloader.py',downloadFile: jest.fn(),uploadFile: jest.fn(),createCodeModeTransport: () => {@@ -42,7 +46,6 @@ function makeSandbox(options: {blockDestructiveToolsInCodeMode: true,mcpRequestTimeoutMs: options.mcpRequestTimeoutMs,mcpConnectTimeoutMs: options.mcpConnectTimeoutMs,- tenantName: 'test-tenant',logger: makeSilentLogger(),tracing: NOOP_AGENT_TRACING,}),@@ -64,6 +67,11 @@ describe('Code Mode timeouts', () => {it('derives the Code Mode wait from MCP request + connect plus a buffer', async () => {let capturedTimeoutSeconds: number | undefined;const transport: CodeModeTransport = {+ getClientInstall: () => ({+ content: '#!/usr/bin/env python3\nprint("mock")\n',+ remotePath: '/opt/tfy/mcp-client/mcp_client.py',+ pathBinSymlink: '/usr/local/bin/mcp-client',+ }),start: params => {capturedTimeoutSeconds = params.requestTimeoutSeconds;return Promise.resolve({@@ -87,6 +95,11 @@ describe('Code Mode timeouts', () => {expect(capturedTimeoutSeconds).toBe(150);expect(call.env?.['TFY_CM_REQUEST_TIMEOUT_SECONDS']).toBe('150');+ expect(call.env?.['PATH']).toBeUndefined();+ expect(call.env?.['PYTHONPATH']).toBe('/opt/tfy/mcp-client');+ const init = execCalls.find(item => item.command.includes('ln -sf'));+ expect(init?.command).toContain('/usr/local/bin/mcp-client');+ expect(init?.command).not.toContain('/opt/tfy/mcp-client/bin/mcp-client');});it('leaves the exec timeout to the provider default', async () => {diff --git a/packages/trueforge-core/tests/core/sandbox/sandboxRef.test.ts b/packages/trueforge-core/tests/core/sandbox/sandboxRef.test.tsnew file mode 100644index 000000000..0afc83820--- /dev/null+++ b/packages/trueforge-core/tests/core/sandbox/sandboxRef.test.ts@@ -0,0 +1,47 @@+import {+ existingSandboxIdForProvider,+ formatSandboxId,+ parseSandboxId,+ rawSandboxId,+} from '../../../src/core/sandbox/sandboxRef';++describe('sandboxRef', () => {+ it('formats v1:type:raw and parses it back (raw may contain colons)', () => {+ const formatted = formatSandboxId({ providerType: 'local', rawId: '/tmp/a:b:c' });+ expect(formatted).toBe('v1:local:/tmp/a:b:c');+ expect(parseSandboxId(formatted)).toEqual({+ kind: 'v1',+ parts: { providerType: 'local', rawId: '/tmp/a:b:c' },+ });+ expect(rawSandboxId(formatted)).toBe('/tmp/a:b:c');+ });++ it('treats missing v1 prefix and malformed v1 ids as legacy', () => {+ expect(parseSandboxId('tenant.uuid')).toEqual({ kind: 'legacy', rawId: 'tenant.uuid' });+ expect(parseSandboxId('v1:')).toEqual({ kind: 'legacy', rawId: 'v1:' });+ expect(parseSandboxId('v1:daytona')).toEqual({ kind: 'legacy', rawId: 'v1:daytona' });+ expect(parseSandboxId('v1:daytona:')).toEqual({ kind: 'legacy', rawId: 'v1:daytona:' });+ expect(rawSandboxId('tenant.uuid')).toBe('tenant.uuid');+ });++ it('carries legacy and same-type v1 ids; drops cross-type v1 ids', () => {+ expect(+ existingSandboxIdForProvider({ existingSandboxId: undefined, currentProviderType: 'local' }),+ ).toBeUndefined();+ expect(existingSandboxIdForProvider({ existingSandboxId: 'tenant.uuid', currentProviderType: 'local' })).toBe(+ 'tenant.uuid',+ );+ expect(+ existingSandboxIdForProvider({+ existingSandboxId: 'v1:local:/tmp/s',+ currentProviderType: 'local',+ }),+ ).toBe('v1:local:/tmp/s');+ expect(+ existingSandboxIdForProvider({+ existingSandboxId: 'v1:daytona:abc',+ currentProviderType: 'local',+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/trueforge-core/tests/core/sandbox/skills/skillMounter.test.ts b/packages/trueforge-core/tests/core/sandbox/skills/skillMounter.test.tsindex 1a4988364..aa41fc036 100644--- a/packages/trueforge-core/tests/core/sandbox/skills/skillMounter.test.ts+++ b/packages/trueforge-core/tests/core/sandbox/skills/skillMounter.test.ts@@ -15,37 +15,47 @@ const GIT_SKILL = {ref: 'a'.repeat(40),};+const PROVIDER_PATHS = {+ skillsDir: '/custom/skills',+ gitDownloaderPath: '/custom/git_downloader.py',+};+// Renders a mounter's <skills> section the same way Sandbox does (empty section => '').function renderSkills(mounter: ISkillMounter): string {const builder = new InstructionBuilder('skills');- mounter.instruction(builder);+ mounter.instruction(builder, { skillsDir: PROVIDER_PATHS.skillsDir });return builder.build();}describe('SkillMounter (public, git-only)', () => {- it('embeds the git downloader and passes only git skills', () => {- const init = new SkillMounter([GIT_SKILL]).getSandboxInit();+ it('embeds the injected git downloader and TFY_SKILLS_DIR', () => {+ const init = new SkillMounter([GIT_SKILL]).getSandboxInit(PROVIDER_PATHS);- expect(init.command).toContain('/opt/tfy/git_downloader.py');+ expect(init.command).toContain('/custom/git_downloader.py');+ expect(init.command).not.toContain('/opt/tfy/git_downloader.py');expect(init.env?.['AGENT_GIT_SKILLS']).toBeDefined();+ expect(init.env?.['TFY_SKILLS_DIR']).toBe('/custom/skills');expect(init.env?.['AGENT_SKILL_VERSION_FQNS']).toBeUndefined();expect(init.env?.['TFY_API_KEY']).toBeUndefined();expect(init.timeoutSeconds).toBe(180);});- it('renders a <skills> section with a block per skill', () => {+ it('renders a <skills> section with a block per skill using the injected skills dir', () => {const rendered = renderSkills(new SkillMounter([GIT_SKILL]));expect(rendered).toContain('<skills>');expect(rendered).toContain('git-skill');+ expect(rendered).toContain('/custom/skills/git-skill');+ expect(rendered).not.toContain('/opt/tfy/skills');});it('uses an empty desired set for cleanup on a reused sandbox and renders nothing', () => {const mounter = new SkillMounter([]);- const init = mounter.getSandboxInit();+ const init = mounter.getSandboxInit(PROVIDER_PATHS);expect(renderSkills(mounter)).toBe('');- expect(init.command).toContain('/opt/tfy/git_downloader.py');+ expect(init.command).toContain('/custom/git_downloader.py');+ expect(init.env?.['TFY_SKILLS_DIR']).toBe('/custom/skills');expect(JSON.parse(Buffer.from(init.env?.['AGENT_GIT_SKILLS'] ?? '', 'base64').toString())).toEqual([]);});});diff --git a/packages/trueforge-core/tests/core/sandbox/tenantOwnership.test.ts b/packages/trueforge-core/tests/core/sandbox/tenantOwnership.test.tsnew file mode 100644index 000000000..094418603--- /dev/null+++ b/packages/trueforge-core/tests/core/sandbox/tenantOwnership.test.ts@@ -0,0 +1,24 @@+import { validateSandboxOwnedByTenant } from '../../../src/core/sandbox/SandboxErrors';++describe('validateSandboxOwnedByTenant', () => {+ it('accepts a Daytona/TFY raw id prefixed with the tenant', () => {+ expect(() =>+ validateSandboxOwnedByTenant({ sandboxId: 'acme.01900000-0000-0000-0000-000000000001', tenantName: 'acme' }),+ ).not.toThrow();+ });++ it('rejects another tenant prefix, a fancy id, and a local path', () => {+ expect(() =>+ validateSandboxOwnedByTenant({ sandboxId: 'other.01900000-0000-0000-0000-000000000001', tenantName: 'acme' }),+ ).toThrow(/does not belong to tenant acme/);+ expect(() =>+ validateSandboxOwnedByTenant({+ sandboxId: 'v1:daytona:acme.01900000-0000-0000-0000-000000000001',+ tenantName: 'acme',+ }),+ ).toThrow(/does not belong to tenant acme/);+ expect(() => validateSandboxOwnedByTenant({ sandboxId: '/var/folders/xx/sandbox', tenantName: 'acme' })).toThrow(+ /does not belong to tenant acme/,+ );+ });+});diff --git a/packages/trueforge/jest.local-sandbox.contract.config.cjs b/packages/trueforge/jest.local-sandbox.contract.config.cjsnew file mode 100644index 000000000..34cc0cc61--- /dev/null+++ b/packages/trueforge/jest.local-sandbox.contract.config.cjs@@ -0,0 +1,40 @@+/** @type {import('jest').Config} */+module.exports = {+ testEnvironment: 'node',+ transform: {+ '^.+\\.tsx?$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'typescript', decorators: true, dynamicImport: true },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ '^.+\\.m?js$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'ecmascript', dynamicImport: true },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ },+ transformIgnorePatterns: [],+ moduleNameMapper: {+ '^(\\.{1,2}/.*)\\.js$': '$1',+ '^@truefoundry/trueforge-core/agent-session$': '<rootDir>/../trueforge-core/src/agent-session/index.ts',+ '^@truefoundry/trueforge-core/agent-session/(.*)$': '<rootDir>/../trueforge-core/src/agent-session/$1',+ '^@truefoundry/trueforge-core/request-reply$': '<rootDir>/../trueforge-core/src/request-reply/index.ts',+ '^@truefoundry/trueforge-core/request-reply/(.*)$': '<rootDir>/../trueforge-core/src/request-reply/$1',+ '^@truefoundry/trueforge-core/core$': '<rootDir>/../trueforge-core/src/core/index.ts',+ '^@truefoundry/trueforge-core/core/(.*)$': '<rootDir>/../trueforge-core/src/core/$1',+ },+ testTimeout: 120_000,+ maxWorkers: 1,+ roots: ['<rootDir>/tests/unit'],+ testMatch: ['<rootDir>/tests/unit/sandbox/local/**/*.contract.test.ts'],+};diff --git a/packages/trueforge/jest.local-sandbox.smoke.config.cjs b/packages/trueforge/jest.local-sandbox.smoke.config.cjsnew file mode 100644index 000000000..330ee2292--- /dev/null+++ b/packages/trueforge/jest.local-sandbox.smoke.config.cjs@@ -0,0 +1,40 @@+/** @type {import('jest').Config} */+module.exports = {+ testEnvironment: 'node',+ transform: {+ '^.+\\.tsx?$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'typescript', decorators: true, dynamicImport: true },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ '^.+\\.m?js$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'ecmascript', dynamicImport: true },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ },+ transformIgnorePatterns: [],+ moduleNameMapper: {+ '^(\\.{1,2}/.*)\\.js$': '$1',+ '^@truefoundry/trueforge-core/agent-session$': '<rootDir>/../trueforge-core/src/agent-session/index.ts',+ '^@truefoundry/trueforge-core/agent-session/(.*)$': '<rootDir>/../trueforge-core/src/agent-session/$1',+ '^@truefoundry/trueforge-core/request-reply$': '<rootDir>/../trueforge-core/src/request-reply/index.ts',+ '^@truefoundry/trueforge-core/request-reply/(.*)$': '<rootDir>/../trueforge-core/src/request-reply/$1',+ '^@truefoundry/trueforge-core/core$': '<rootDir>/../trueforge-core/src/core/index.ts',+ '^@truefoundry/trueforge-core/core/(.*)$': '<rootDir>/../trueforge-core/src/core/$1',+ },+ testTimeout: 120_000,+ maxWorkers: 1,+ roots: ['<rootDir>/tests/sandbox/local'],+ testMatch: ['<rootDir>/tests/sandbox/local/smoke.test.ts'],+};diff --git a/packages/trueforge/jest.unit.config.cjs b/packages/trueforge/jest.unit.config.cjsindex f2331ae7e..389e40499 100644--- a/packages/trueforge/jest.unit.config.cjs+++ b/packages/trueforge/jest.unit.config.cjs@@ -39,4 +39,6 @@ module.exports = {maxWorkers: '50%',roots: ['<rootDir>/tests/unit'],testMatch: ['<rootDir>/tests/unit/**/*.test.ts'],+ // SRT contract suites need a real host sandbox; run via `pnpm test:local-sandbox:contract`.+ testPathIgnorePatterns: ['contract\\.test\\.ts$'],};diff --git a/packages/trueforge/package.json b/packages/trueforge/package.jsonindex 19abca884..f2a7c8d96 100644--- a/packages/trueforge/package.json+++ b/packages/trueforge/package.json@@ -29,8 +29,9 @@},"scripts": {"build:frontend-assets": "node scripts/copy-frontend.mjs",- "build:gen:watch": "node --watch-path=catalog/model-catalog.yaml --watch-path=catalog/mcp-catalog.yaml --watch-path=catalog/skill-catalog.yaml --watch-path=catalog/sandbox-catalog.yaml scripts/generate-catalog.mjs",- "build:gen": "node scripts/generate-catalog.mjs",+ "build:gen:local-sandbox": "node scripts/generate-local-sandbox-scripts.mjs",+ "build:gen:watch": "node --watch-path=catalog/model-catalog.yaml --watch-path=catalog/mcp-catalog.yaml --watch-path=catalog/skill-catalog.yaml --watch-path=catalog/sandbox-catalog.yaml --watch-path=src/sandbox/local/scripts scripts/generate-dev.mjs",+ "build:gen": "pnpm run build:gen:local-sandbox && node scripts/generate-catalog.mjs","build:clean": "rm -rf dist","build": "pnpm run build:gen && tsc --noEmit && pnpm run build:clean && tsup && chmod +x dist/cli.js && pnpm run build:frontend-assets","dev:serve": "NODE_OPTIONS='--conditions=trueforge-dev' NODE_ENV=development tsx watch --env-file=.env src/main.ts",@@ -48,9 +49,14 @@"test:store:postgres": "jest --config jest.store.postgres.config.cjs","test:store:sqlite": "jest --config jest.store.sqlite.config.cjs","test": "pnpm run build:gen && NODE_OPTIONS='--conditions=trueforge-dev' node --env-file=.env.test ./node_modules/jest/bin/jest.js --config jest.unit.config.cjs",+ "test:local-sandbox:contract": "pnpm run build:gen && NODE_OPTIONS='--conditions=trueforge-dev' node --env-file=.env.test ./node_modules/jest/bin/jest.js --config jest.local-sandbox.contract.config.cjs",+ "smoke:local-sandbox": "pnpm run build:gen && NODE_OPTIONS='--conditions=trueforge-dev' jest --config jest.local-sandbox.smoke.config.cjs --runInBand --forceExit tests/sandbox/local/smoke.test.ts",+ "smoke:local-sandbox:lima": "bash scripts/local-sandbox/smoke-lima.sh",+ "probe:loopback": "pnpm exec tsx scripts/local-sandbox/probe-loopback.ts","typecheck": "pnpm run build:gen && tsc --noEmit && tsc --noEmit -p tests/db/tsconfig.json && tsc --noEmit -p tests/unit/tsconfig.json"},"dependencies": {+ "@anthropic-ai/sandbox-runtime": "0.0.71","@daytona/sdk": "^0.204.1","@hono/node-server": "^2.0.11","@hono/swagger-ui": "^0.2.1",diff --git a/packages/trueforge/scripts/generate-dev.mjs b/packages/trueforge/scripts/generate-dev.mjsnew file mode 100644index 000000000..be1054c93--- /dev/null+++ b/packages/trueforge/scripts/generate-dev.mjs@@ -0,0 +1,14 @@+/**+ * Watch-mode codegen: local sandbox scripts + shipped catalogs.+ */+import { spawnSync } from 'node:child_process';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const dir = dirname(fileURLToPath(import.meta.url));+for (const script of ['generate-local-sandbox-scripts.mjs', 'generate-catalog.mjs']) {+ const result = spawnSync(process.execPath, [join(dir, script)], { stdio: 'inherit' });+ if (result.status !== 0) {+ process.exit(result.status ?? 1);+ }+}diff --git a/packages/trueforge/scripts/generate-local-sandbox-scripts.mjs b/packages/trueforge/scripts/generate-local-sandbox-scripts.mjsnew file mode 100644index 000000000..9d39b1aee--- /dev/null+++ b/packages/trueforge/scripts/generate-local-sandbox-scripts.mjs@@ -0,0 +1,22 @@+/**+ * Inlines the local Code Mode MCP client into a generated TS module so+ * install paths can self-serve the script with no loose fixture files.+ * A plain generated `.ts` file works unchanged across tsc and @swc/jest.+ *+ * Runs via `build:gen` before build/typecheck/test. The generated output+ * (src/sandbox/local/sandboxScripts.gen.ts) is gitignored.+ */+import { readFileSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++const root = join(dirname(fileURLToPath(import.meta.url)), '..');+const scriptsDir = join(root, 'src/sandbox/local/scripts');+const read = f => readFileSync(join(scriptsDir, f), 'utf-8');++const out = `// AUTO-GENERATED by scripts/generate-local-sandbox-scripts.mjs — do not edit.+export const sandboxScripts = {+ mcpClientLocal: ${JSON.stringify(read('mcp_client_local.py'))},+} as const;+`;+writeFileSync(join(root, 'src/sandbox/local/sandboxScripts.gen.ts'), out);diff --git a/packages/local-sandbox/lima/local-sandbox.yaml b/packages/trueforge/scripts/local-sandbox/lima.yamlsimilarity index 91%rename from packages/local-sandbox/lima/local-sandbox.yamlrename to packages/trueforge/scripts/local-sandbox/lima.yamlindex 109f495b4..3c1cb6bc6 100644--- a/packages/local-sandbox/lima/local-sandbox.yaml+++ b/packages/trueforge/scripts/local-sandbox/lima.yaml@@ -1,5 +1,5 @@# Minimal Lima guest for local-sandbox Linux SRT smoke.-# Mounts the package root at the same absolute host path.+# Mounts the workspace root at the same absolute host path.cpus: 1memory: '2GiB'disk: '20GiB'@@ -10,7 +10,7 @@ images:- 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+# `location` is rewritten to an absolute host path by smoke-lima.shmounts:- location: '__LOCAL_SANDBOX_ROOT__'writable: truediff --git a/packages/local-sandbox/scripts/probe-loopback.ts b/packages/trueforge/scripts/local-sandbox/probe-loopback.tssimilarity index 100%rename from packages/local-sandbox/scripts/probe-loopback.tsrename to packages/trueforge/scripts/local-sandbox/probe-loopback.tsdiff --git a/packages/local-sandbox/scripts/smoke-lima.sh b/packages/trueforge/scripts/local-sandbox/smoke-lima.shsimilarity index 71%rename from packages/local-sandbox/scripts/smoke-lima.shrename to packages/trueforge/scripts/local-sandbox/smoke-lima.shindex a0a57b96d..7a3f8f2a3 100755--- a/packages/local-sandbox/scripts/smoke-lima.sh+++ b/packages/trueforge/scripts/local-sandbox/smoke-lima.sh@@ -1,10 +1,12 @@#!/usr/bin/env bash-# Create/start a minimal Lima VM and run `pnpm smoke` for Linux SRT coverage.+# Create/start a minimal Lima VM and run `pnpm smoke:local-sandbox` for Linux SRT coverage.set -euo pipefail-ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+# packages/trueforge/scripts/local-sandbox → workspace root (pnpm install --filter).+ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)"INSTANCE="${LIMA_INSTANCE:-local-sandbox-poc}"-YAML_TEMPLATE="${ROOT}/lima/local-sandbox.yaml"+YAML_TEMPLATE="${SCRIPT_DIR}/lima.yaml"if ! command -v limactl >/dev/null 2>&1; thenecho "limactl not found; install Lima first (e.g. brew install lima)" >&2@@ -31,6 +33,6 @@ echo "running Linux smoke inside ${INSTANCE}..."limactl shell "${INSTANCE}" -- bash -lc "set -euo pipefailcd $(printf '%q' "${ROOT}")- CI=true pnpm install --ignore-workspace --no-frozen-lockfile- pnpm smoke+ CI=true pnpm install --no-frozen-lockfile+ pnpm --filter @truefoundry/trueforge smoke:local-sandbox"diff --git a/packages/trueforge/src/apis/capabilities.ts b/packages/trueforge/src/apis/capabilities.tsindex 6f4f65b58..1149a3024 100644--- a/packages/trueforge/src/apis/capabilities.ts+++ b/packages/trueforge/src/apis/capabilities.ts@@ -5,6 +5,7 @@ import { isAdmin, resolveUserContext } from '../auth/identity';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';import type { WithTransaction } from '../db/transaction';import { getCapabilitiesRoute } from '../routes/capabilityRoutes';+import { isLocalSandboxFallbackEnabled } from '../sandbox/localRuntime';import { checkSnapshotStatus } from '../sandbox/providerUtils';import type { SandboxBuildStatus } from '../schemas/sandboxProvider';import { TENANT_ID } from './sessions';@@ -40,7 +41,7 @@ export function createCapabilitiesRouter<TTransaction>(deps: {} catch (error) {deps.logger.warn('Sandbox image status check failed; reporting sandbox disabled', extractErrorLogFields(error));}- const sandboxEnabled = status === 'ready';+ const sandboxEnabled = status === 'ready' || (status === undefined && isLocalSandboxFallbackEnabled());const settingsEnabled = isAdmin(resolveUserContext(c));return c.json({diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.tsindex 5837e43b5..26ec91bac 100644--- a/packages/trueforge/src/apis/turns.ts+++ b/packages/trueforge/src/apis/turns.ts@@ -14,12 +14,13 @@ import {} from '@truefoundry/trueforge-core/agent-session';import {AgentHarnessError,+ existingSandboxIdForProvider,extractErrorLogFields,isAgentInputUserMessage,isFileContentPart,McpConnectionError,+ rawSandboxId,SandboxError,- validateSandboxOwnedByTenant,VercelAILLM,} from '@truefoundry/trueforge-core/core';import type { Context } from 'hono';@@ -128,6 +129,7 @@ function createTurnResolver(deps: {logger: Logger;signal: AbortSignal;userRef: string;+ sessionId: string;}): TurnResourceResolver {const {mcpServerStore,@@ -139,6 +141,7 @@ function createTurnResolver(deps: {logger,signal,userRef,+ sessionId,} = deps;return new TurnResourceResolver({llm: async name => {@@ -179,16 +182,21 @@ function createTurnResolver(deps: {tenant_id: TENANT_ID,store: sandboxProviderStore,logger,+ sessionId,});if (provider === undefined) {throw new HTTPException(422, {message: 'no sandbox provider configured — PUT /settings/sandbox-providers',});}- // A fresh sandbox is cloned from the release snapshot, so the build must be ready first.- // Restoring an existing sandbox goes through daytona.get and never touches the snapshot,- // so reuse skips this gate entirely.- if (existingSandboxId === undefined) {+ const carriedSandboxId = existingSandboxIdForProvider({+ existingSandboxId,+ currentProviderType: provider.type,+ });+ // A fresh Daytona sandbox is cloned from the release snapshot, so the build must be ready first.+ // Restoring an existing sandbox goes through daytona.get and never touches the snapshot.+ // Local fallback has no image build.+ if (carriedSandboxId === undefined && provider.type !== 'local') {const status = await checkSnapshotStatus({ store: sandboxProviderStore, tenant_id: TENANT_ID, logger });if (status?.status !== 'ready') {throw new HTTPException(422, {@@ -209,9 +217,8 @@ function createTurnResolver(deps: {logger,gitSkills,fileDownloadEnabled: spec.config.sandbox.file_downloads,- existingSandboxId,+ existingSandboxId: carriedSandboxId,tracing,- tenantName: TENANT_ID,});},agent: async agentId => {@@ -426,14 +433,14 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {tenant_id: TENANT_ID,store: deps.sandboxProviderStore,logger: deps.logger,+ sessionId,});if (provider === undefined) {return c.json({ error: { message: 'No sandbox provider configured' } }, 412);}- validateSandboxOwnedByTenant(sandboxId, TENANT_ID);// TODO: stream the body instead of buffering the whole file in memory.- const content = await provider.downloadFile({ sandboxId, path });+ const content = await provider.downloadFile({ sandboxId: rawSandboxId(sandboxId), path });return c.body(toArrayBuffer(content), 200, {'Content-Type': 'application/octet-stream','Content-Length': String(content.byteLength),@@ -508,6 +515,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {logger: deps.logger,signal: abortController.signal,userRef: deps.resolveUserContext(c).userRef,+ sessionId,});// First turn only: derive the title from the first user message. The storediff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.tsindex 7f0ec6398..7db39e5a6 100644--- a/packages/trueforge/src/config.ts+++ b/packages/trueforge/src/config.ts@@ -12,6 +12,7 @@* `redis://localhost:6379`).*/import { existsSync } from 'node:fs';+import os from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -167,6 +168,16 @@ function resolveSqlitePath(): string {return path.join(paths.data, 'db', 'db.sqlite');}+/** Parent for local sandbox roots. Same env-paths data dir as SQLite (`{suffix:''}`). */+function resolveLocalSandboxRootParent(): string {+ return path.join(envPaths(ENV_PATHS_APP_NAME, { suffix: '' }).data, 'sandboxes');+}++/** Short tmp parent for Code Mode UDS socks (≤65 bytes after realpath). */+function resolveCodeModeSocketParent(): string {+ return path.join(os.tmpdir(), 'tf_cms');+}+/** Redis peering URL for distributed mode. Env: `REDIS_URL`. */function resolveRedisUrl(): string {const raw = getEnv('REDIS_URL', { defaultValue: DEFAULT_REDIS_URL }) ?? DEFAULT_REDIS_URL;@@ -399,6 +410,16 @@ export type StandaloneServerConfiguration = SharedServerConfiguration & {* Env: `SQLITE_PATH` (optional). Default: env-paths data dir + `db/db.sqlite`.*/SQLITE_PATH: string;+ /**+ * Parent directory for local sandbox roots (ULID children).+ * Derived: `{env-paths data}/sandboxes`.+ */+ LOCAL_SANDBOX_ROOT_PARENT: string;+ /**+ * Parent directory for Code Mode UDS sockets (`tf_cms` under os.tmpdir()).+ * Caller prepares/removes this directory; must stay ≤65 bytes after realpath.+ */+ CODE_MODE_SOCKET_PARENT: string;};export type DistributedServerConfiguration = SharedServerConfiguration & {@@ -542,6 +563,8 @@ const configuration: ServerConfiguration = standalone...shared,STANDALONE: true,SQLITE_PATH: resolveSqlitePath(),+ LOCAL_SANDBOX_ROOT_PARENT: resolveLocalSandboxRootParent(),+ CODE_MODE_SOCKET_PARENT: resolveCodeModeSocketParent(),}: {...shared,diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.tsindex f0a634d63..c1ffa761d 100644--- a/packages/trueforge/src/main.ts+++ b/packages/trueforge/src/main.ts@@ -12,6 +12,12 @@import { extractErrorLogFields } from '@truefoundry/trueforge-core/core';import { mkdir } from 'node:fs/promises';import path from 'node:path';+import {+ ensureLocalSandboxRootParent,+ prepareCodeModeSocketParent,+ removeCodeModeSocketParent,+} from './sandbox/localLifecycle';+import { setCachedLocalSandboxSupport } from './sandbox/localRuntime';let configuration: typeof import('./config').default;let isOidcConfigured: typeof import('./config').isOidcConfigured;@@ -248,6 +254,26 @@ try {if (configuration.STANDALONE) {printStandaloneStartupBanner({ version: PACKAGE_VERSION, color: shouldColorize() });+ await prepareCodeModeSocketParent({ path: configuration.CODE_MODE_SOCKET_PARENT, logger });+ await ensureLocalSandboxRootParent(configuration.LOCAL_SANDBOX_ROOT_PARENT);+ const { LocalSandboxProvider } = await import('./sandbox/local/provider/LocalSandboxProvider');+ const support = await LocalSandboxProvider.isSupported({+ codeModeSocketParentPath: configuration.CODE_MODE_SOCKET_PARENT,+ });+ setCachedLocalSandboxSupport(support);+ if (support.supported) {+ logger.info('Local sandbox fallback is available', {+ platform: support.platform,+ shell: support.shell,+ python: support.python,+ });+ } else {+ logger.warn('Local sandbox fallback is unavailable', {+ reason: support.reason,+ ...(support.platform === undefined ? {} : { platform: support.platform }),+ ...(support.attempts === undefined ? {} : { attempts: support.attempts }),+ });+ }} else {logger.info('TrueForge starting', { mode: 'distributed' });}@@ -342,6 +368,11 @@ try {await redis?.close().catch((error: unknown) => {logger.warn('[Redis] Error closing client during shutdown', extractErrorLogFields(error));});+ if (configuration.STANDALONE) {+ await removeCodeModeSocketParent(configuration.CODE_MODE_SOCKET_PARENT).catch((error: unknown) => {+ logger.warn('Error removing Code Mode socket parent during shutdown', extractErrorLogFields(error));+ });+ }await destroyDb();process.exit(0);};diff --git a/packages/trueforge/src/routes/turnRoutes.ts b/packages/trueforge/src/routes/turnRoutes.tsindex 7bf74ab23..07359e9f5 100644--- a/packages/trueforge/src/routes/turnRoutes.ts+++ b/packages/trueforge/src/routes/turnRoutes.ts@@ -109,7 +109,7 @@ export const downloadSandboxFileRoute = createRoute({},403: {content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Caller is not the session creator, or sandbox belongs to another tenant.',+ description: 'Caller is not the session creator.',},404: {content: { 'application/json': { schema: RequestErrorResponseSchema } },diff --git a/packages/trueforge/src/runtime/sessionResources.ts b/packages/trueforge/src/runtime/sessionResources.tsindex 6ba8600bd..ee97d7246 100644--- a/packages/trueforge/src/runtime/sessionResources.ts+++ b/packages/trueforge/src/runtime/sessionResources.ts@@ -13,6 +13,7 @@ import {type VercelAIProviderConfig,} from '@truefoundry/trueforge-core/core';import { HTTPException } from 'hono/http-exception';+import { join } from 'node:path';import type { Logger } from 'winston';import configuration from '../config';import type { IMcpServerStore, McpServerRecord } from '../db/mcpServerStore';@@ -21,6 +22,8 @@ import type { ISandboxProviderStore } from '../db/sandboxProviderStore';import type { ISkillStore } from '../db/skillStore';import { isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';import type { IOAuthTokenStore } from '../mcp/auth/types';+import { LocalSandboxProvider } from '../sandbox/local/provider/LocalSandboxProvider';+import { getCachedLocalSandboxSupport, isLocalSandboxFallbackEnabled } from '../sandbox/localRuntime';import { toDaytonaSandboxProvider } from '../sandbox/providerUtils';import { resolveConfiguredMcpRequestHeaders } from '../schemas/mcpServer';@@ -205,35 +208,58 @@ export async function resolveGitSkills({}/**- * Build a runtime SandboxProvider from the configured store row, or undefined- * when no provider is configured. Builds a fresh Daytona client per call (no network I/O).+ * Build a runtime SandboxProvider from the configured store row, or the+ * in-memory local fallback when standalone + the cached probe is supported.+ * Builds a fresh Daytona client per call (no network I/O).*/+/** Single path segment under the sandboxes parent (`_` when sessionId is missing or unsafe). */+export function localSandboxSessionSegment(sessionId: string | undefined): string {+ if (sessionId === undefined || sessionId.length === 0 || sessionId.includes('/') || sessionId.includes('..')) {+ return '_';+ }+ return sessionId;+}+export async function resolveSandboxProvider({tenant_id,store,logger,+ sessionId,}: {tenant_id: string;store: ISandboxProviderStore;logger: Logger;+ sessionId: string;}): Promise<SandboxProvider | undefined> {const record = await store.getSandboxProvider(tenant_id);- if (record === undefined) {+ if (record !== undefined) {+ // Clone from the snapshot that was actually built (persisted build_ref), not a name+ // derived from the current image — otherwise an image bump breaks creation until rebuild.+ return toDaytonaSandboxProvider({+ manifest: record.manifest,+ tenant_id,+ logger,+ build_metadata: record.build_metadata,+ });+ }+ if (!configuration.STANDALONE) {+ return undefined;+ }+ const support = getCachedLocalSandboxSupport();+ if (support?.supported !== true) {return undefined;}- // Clone from the snapshot that was actually built (persisted build_ref), not a name- // derived from the current image — otherwise an image bump breaks creation until rebuild.- return toDaytonaSandboxProvider({- manifest: record.manifest,- tenant_id,+ return new LocalSandboxProvider({+ sandboxRootPathParent: join(configuration.LOCAL_SANDBOX_ROOT_PARENT, localSandboxSessionSegment(sessionId)),+ codeModeSocketParentPath: configuration.CODE_MODE_SOCKET_PARENT,+ support,+ fileMaxBytesForDownload: configuration.SANDBOX_FILE_MAX_BYTES_FOR_DOWNLOAD,logger,- build_metadata: record.build_metadata,});}/*** Builds a Sandbox for one turn from a resolved provider and git mounts.- * `tenantName` must match the name given to DaytonaSandboxProvider (ownership check).*/export function buildTurnSandbox(input: {provider: SandboxProvider;@@ -242,7 +268,6 @@ export function buildTurnSandbox(input: {fileDownloadEnabled: boolean;existingSandboxId?: string | undefined;tracing: AgentTracing;- tenantName: string;}): Sandbox {const skillMounter = input.gitSkills.length > 0 ? new SkillMounter([...input.gitSkills]) : undefined;return new Sandbox({@@ -252,7 +277,6 @@ export function buildTurnSandbox(input: {blockDestructiveToolsInCodeMode: true,mcpRequestTimeoutMs: configuration.MCP_REQUEST_TIMEOUT_MS,mcpConnectTimeoutMs: configuration.MCP_CONNECT_TIMEOUT_MS,- tenantName: input.tenantName,...(skillMounter ? { skillMounter } : {}),tracing: input.tracing,logger: input.logger,@@ -339,7 +363,7 @@ export async function validateAgentSpec({const hasSkills = requestedSkills.length > 0;if (wantsSandbox || hasSkills) {const record = await sandboxProviderStore.getSandboxProvider(tenant_id);- if (record === undefined) {+ if (record === undefined && !isLocalSandboxFallbackEnabled()) {throw new HTTPException(422, {message: hasSkills? 'skills require a sandbox provider — configure via PUT /settings/sandbox-providers'diff --git a/packages/local-sandbox/src/core/CodeModeUdsTransport.ts b/packages/trueforge/src/sandbox/local/core/CodeModeUdsTransport.tssimilarity index 71%rename from packages/local-sandbox/src/core/CodeModeUdsTransport.tsrename to packages/trueforge/src/sandbox/local/core/CodeModeUdsTransport.tsindex 03d20badb..376c73031 100644--- a/packages/local-sandbox/src/core/CodeModeUdsTransport.ts+++ b/packages/trueforge/src/sandbox/local/core/CodeModeUdsTransport.ts@@ -4,10 +4,12 @@** 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.+ * connect; after listen the sock is chmod 0600. Same-UID isolation is still SRT path policy:+ * hostRun grants the parent in allowRead (Linux) / allowUnixSockets (macOS), not host /tmp.* The caller owns that parent directory's lifetime; this transport unlinks the sock it creates.*/import type {+ CodeModeClientInstall,CodeModeDispatcher,CodeModeReply,CodeModeRequest,@@ -15,24 +17,46 @@ import type {} 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 { chmod, mkdir, rm, symlink, unlink, writeFile } from 'node:fs/promises';import { createServer, type Server, type Socket } from 'node:net';-import { isAbsolute, join, resolve } from 'node:path';+import { dirname, isAbsolute, join, resolve } from 'node:path';import { ulid } from 'ulid';+import { sandboxScripts } from '../sandboxScripts.gen.js';import { encodeJsonMessage, JsonMessageReader, MAX_MESSAGE_BYTES } from './frame.js';-import { registerCodeModeSocketPath, unregisterCodeModeSocketPath } from './hostRun.js';-const MAX_CODE_MODE_SOCKET_PARENT_BYTES = 60;+/**+ * Max realpath bytes for the sock parent. Full path is `parent/ulid` (26-char name).+ * 63 was too tight after macOS `/private` realpath; 65 leaves headroom under sun_path.+ */+export const MAX_CODE_MODE_SOCKET_PARENT_BYTES = 65;const CODE_MODE_SOCKET_PARENT_MODE = 0o700;const CODE_MODE_SOCKET_MODE = 0o600;+/** Install layout for local Code Mode MCP client (sandboxId = absolute sandbox root). */+export function localMcpClientRemotePath(sandboxId: string): string {+ return join(sandboxId, 'mcp-client', 'mcp_client.py');+}++/** Install the local Code Mode MCP client into the sandbox (same layout as Sandbox.init). */+export async function installMcpFixture(sandboxRootPath: string): Promise<{ remotePath: string }> {+ const remotePath = localMcpClientRemotePath(sandboxRootPath);+ const binLink = join(dirname(remotePath), 'bin', 'mcp-client');+ await mkdir(dirname(binLink), { recursive: true, mode: 0o700 });+ await writeFile(remotePath, sandboxScripts.mcpClientLocal, { encoding: 'utf8', mode: 0o555 });+ await rm(binLink, { force: true });+ await symlink(remotePath, binLink);+ return { remotePath };+}+export interface CodeModeUdsTransportOptions {/**- * Absolute existing directory for Code Mode UDS files (≤60 bytes, mode 0700).+ * Absolute existing directory for Code Mode UDS files (≤65 bytes after realpath, mode 0700).* Socket path is `join(parent, ulid)`; sock is chmod 0600 after listen.*/codeModeSocketParentPath: string;maxMessageBytes?: number | undefined;+ /** Provider-owned MCP client module path (cwd-relative under the sandbox root). */+ clientRemotePath: (sandboxId: string) => string;/** Optional: observe inbound protocol failures (oversized / malformed). */onProtocolError?: ((message: string) => void) | undefined;}@@ -52,7 +76,7 @@ export function assertCodeModeSocketParentPath(path: string): string {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)})`,+ `codeModeSocketParentPath (${real}) 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.@@ -64,10 +88,42 @@ export function assertCodeModeSocketParentPath(path: string): string {return real;}+/**+ * Bind+close a ULID-named sock under `parentPath`. Surfaces ENAMETOOLONG / EINVAL+ * that the byte-length check alone can miss (sun_path, realpath).+ */+export async function probeCodeModeUnixSocket(parentPath: string): Promise<{ sockPath: string }> {+ const realParent = assertCodeModeSocketParentPath(parentPath);+ const sockPath = join(realParent, ulid().toLowerCase());+ await unlink(sockPath).catch(() => undefined);+ const server = createServer();+ try {+ await new Promise<void>((resolveListen, reject) => {+ server.once('error', reject);+ server.listen(sockPath, () => {+ server.off('error', reject);+ resolveListen();+ });+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(`listen ${sockPath} (${String(Buffer.byteLength(sockPath))} bytes): ${message}`, { cause: error });+ } finally {+ await new Promise<void>(resolveClose => {+ server.close(() => {+ resolveClose();+ });+ });+ await unlink(sockPath).catch(() => undefined);+ }+ return { sockPath };+}+export class CodeModeUdsTransport implements CodeModeTransport {private readonly codeModeSocketParentPath: string;private readonly maxMessageBytes: number;private readonly onProtocolError: ((message: string) => void) | undefined;+ private readonly clientRemotePath: (sandboxId: string) => string;private sessionPromise: Promise<{ env: Record<string, string> }> | undefined;private server: Server | undefined;@@ -79,6 +135,14 @@ export class CodeModeUdsTransport implements CodeModeTransport {this.codeModeSocketParentPath = assertCodeModeSocketParentPath(options.codeModeSocketParentPath);this.maxMessageBytes = options.maxMessageBytes ?? MAX_MESSAGE_BYTES;this.onProtocolError = options.onProtocolError;+ this.clientRemotePath = options.clientRemotePath;+ }++ getClientInstall(params: { sandboxId: string }): CodeModeClientInstall {+ return {+ content: sandboxScripts.mcpClientLocal,+ remotePath: this.clientRemotePath(params.sandboxId),+ };}start(params: {@@ -118,7 +182,6 @@ export class CodeModeUdsTransport implements CodeModeTransport {});}if (sockPath !== undefined) {- unregisterCodeModeSocketPath(sockPath);await unlink(sockPath).catch(() => undefined);}}@@ -133,7 +196,6 @@ export class CodeModeUdsTransport implements CodeModeTransport {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) => {@@ -146,7 +208,6 @@ export class CodeModeUdsTransport implements CodeModeTransport {// 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;diff --git a/packages/local-sandbox/src/core/frame.ts b/packages/trueforge/src/sandbox/local/core/frame.tssimilarity index 100%rename from packages/local-sandbox/src/core/frame.tsrename to packages/trueforge/src/sandbox/local/core/frame.tsdiff --git a/packages/local-sandbox/src/core/hostRun.ts b/packages/trueforge/src/sandbox/local/core/hostRun.tssimilarity index 67%rename from packages/local-sandbox/src/core/hostRun.tsrename to packages/trueforge/src/sandbox/local/core/hostRun.tsindex ae469bd39..2453713fc 100644--- a/packages/local-sandbox/src/core/hostRun.ts+++ b/packages/trueforge/src/sandbox/local/core/hostRun.ts@@ -9,32 +9,14 @@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 { realpathSync } from 'node:fs';+import { 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(@@ -53,6 +35,12 @@ export type LocalSandboxPlatform = 'darwin' | 'linux';/** Cached from {@link initSrt}; cleared by {@link resetSrt}. Used by session policy helpers after init. */let activePlatform: LocalSandboxPlatform | undefined;+/** Realpath of the Code Mode UDS parent; Linux allowRead + macOS allowUnixSockets. */+let codeModeSocketParentPath: string | undefined;++function codeModeSocketParentAllow(): string[] {+ return codeModeSocketParentPath === undefined ? [] : [codeModeSocketParentPath];+}function requireActivePlatform(): LocalSandboxPlatform {if (activePlatform === undefined) {@@ -65,14 +53,89 @@ function requireActivePlatform(): LocalSandboxPlatform {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',+ darwin: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin',+ linux: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin',} as const satisfies Record<LocalSandboxPlatform, string>;export function commandPath(platform: LocalSandboxPlatform): string {return COMMAND_PATH_BY_PLATFORM[platform];}+/** Cwd-relative venv created at local sandbox init (host `python -m venv`). */+export const SANDBOX_VENV_DIR = '.venv';++function sandboxVenvPath(sandboxRootPath: string): string {+ return join(sandboxRootPath, SANDBOX_VENV_DIR);+}++/**+ * HTTPS hosts the SRT proxy may reach. `*.example.com` does not match the apex.+ * Concrete hosts plus wildcards so pip (index + wheel CDN) and git clone work.+ */+export const LOCAL_SANDBOX_ALLOWED_DOMAINS = [+ 'pypi.org',+ '*.pypi.org',+ 'pythonhosted.org',+ 'files.pythonhosted.org',+ '*.pythonhosted.org',+ 'github.com',+ 'api.github.com',+ 'codeload.github.com',+ '*.github.com',+ 'githubusercontent.com',+ 'raw.githubusercontent.com',+ 'objects.githubusercontent.com',+ '*.githubusercontent.com',+] as const;++function allowedNetworkDomains(): string[] {+ return [...LOCAL_SANDBOX_ALLOWED_DOMAINS];+}++/**+ * macOS seatbelt blocks mDNSResponder, so `getaddrinfo("localhost")` fails inside+ * the sandbox. SRT injects `HTTP_PROXY=...@localhost:PORT`; rewrite to 127.0.0.1+ * before outbound tools (pip, curl, …) run.+ */+export function darwinSandboxNetworkShellPreamble(): string {+ return [+ 'if [ -n "${HTTP_PROXY:-}" ]; then export HTTP_PROXY="${HTTP_PROXY//localhost/127.0.0.1}"; fi',+ 'if [ -n "${HTTPS_PROXY:-}" ]; then export HTTPS_PROXY="${HTTPS_PROXY//localhost/127.0.0.1}"; fi',+ 'if [ -n "${http_proxy:-}" ]; then export http_proxy="${http_proxy//localhost/127.0.0.1}"; fi',+ 'if [ -n "${https_proxy:-}" ]; then export https_proxy="${https_proxy//localhost/127.0.0.1}"; fi',+ 'if [ -n "${ALL_PROXY:-}" ]; then export ALL_PROXY="${ALL_PROXY//localhost/127.0.0.1}"; fi',+ 'if [ -n "${all_proxy:-}" ]; then export all_proxy="${all_proxy//localhost/127.0.0.1}"; fi',+ 'if [ -n "${GRPC_PROXY:-}" ]; then export GRPC_PROXY="${GRPC_PROXY//localhost/127.0.0.1}"; fi',+ 'if [ -n "${grpc_proxy:-}" ]; then export grpc_proxy="${grpc_proxy//localhost/127.0.0.1}"; fi',+ ].join('; ');+}++function wrapSandboxCommand(params: { platform: LocalSandboxPlatform; command: string }): string {+ if (params.platform !== 'darwin') {+ return params.command;+ }+ return `${darwinSandboxNetworkShellPreamble()}; ${params.command}`;+}++/**+ * Host binaries SRT execs outside the wrap (same set as SandboxManager.checkDependencies).+ * Linux: bwrap + socat + rg (deny-path scan). macOS seatbelt takes glob denies, so no rg.+ */+export const SRT_HOST_BINARIES_BY_PLATFORM = {+ linux: ['bwrap', 'socat', 'rg'],+ darwin: [],+} as const satisfies Record<LocalSandboxPlatform, readonly string[]>;++export function srtHostBinaryNames(platform: LocalSandboxPlatform): readonly string[] {+ return SRT_HOST_BINARIES_BY_PLATFORM[platform];+}++/** SRT's own host-dep check (bwrap/socat/rg on Linux). Does not require initSrt. */+export async function checkSrtHostDependencies(): Promise<{ errors: string[]; warnings: string[] }> {+ const result = await SandboxManager.checkDependenciesAsync();+ return { errors: [...result.errors], warnings: [...result.warnings] };+}+/*** 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).@@ -80,11 +143,14 @@ export function commandPath(platform: LocalSandboxPlatform): string {export async function resolveCommandOnHost(params: {platform: LocalSandboxPlatform;name: string;+ /** Defaults to the sandbox PATH for this platform. Host SRT tools use process PATH. */+ pathEnv?: string | undefined;}): 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);+ const pathEnv =+ params.pathEnv !== undefined && params.pathEnv.length > 0 ? params.pathEnv : commandPath(params.platform);try {const { stdout } = await execFileAsync('/bin/sh', ['-c', `command -v -- ${params.name}`], {env: { PATH: pathEnv },@@ -100,6 +166,30 @@ export async function resolveCommandOnHost(params: {}}+/**+ * Resolve the real interpreter on the host before running it under seatbelt.+ * Apple's `/usr/bin/python3` is an xcode-select stub; python.org / Homebrew+ * leave `sys.executable` as a PATH symlink (`/usr/local/bin/python3`).+ */+export async function resolvePythonExecutableOnHost(params: { commandPath: string }): Promise<string | undefined> {+ if (!isAbsolute(params.commandPath)) {+ return undefined;+ }+ try {+ const { stdout } = await execFileAsync(params.commandPath, ['-c', 'import sys; print(sys.executable)'], {+ encoding: 'utf8',+ timeout: 5_000,+ });+ const executable = stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);+ if (executable === undefined || executable.length === 0 || !isAbsolute(executable)) {+ return undefined;+ }+ return realpathSync(executable);+ } catch {+ return undefined;+ }+}+export interface SessionResult {stdoutText: string;stderrText: string;@@ -122,6 +212,7 @@ function denySharedDefaultWritePaths(): string[] {const ALLOW_READ_BY_PLATFORM = {darwin: ['/opt/homebrew/bin',+ '/usr/local','/usr/bin','/bin','/usr/sbin',@@ -133,6 +224,13 @@ const ALLOW_READ_BY_PLATFORM = {'/private/var/select','/opt/homebrew','/dev',+ // Darwin `/etc` is a symlink to `/private/etc`. SRT refuses that realpath as+ // "outside boundary" and keeps `(subpath "/etc")`. Seatbelt still checks the+ // resolved path, so Apple LibreSSL's fopen(`/private/etc/ssl/openssl.cnf`)+ // needs `/private/etc` listed too. Do not use a `[/]etc/**` glob: SRT treats+ // that as cwd-relative (`path.isAbsolute('[/]…')` is false).+ '/etc',+ '/private/etc',],linux: ['/usr/bin',@@ -148,7 +246,6 @@ const ALLOW_READ_BY_PLATFORM = {'/dev','/proc','/sys',- '/tmp',SRT_VENDOR,],} as const satisfies Record<LocalSandboxPlatform, readonly string[]>;@@ -171,7 +268,7 @@ function filesystemPolicy(params: { sandboxRootPath: string; platform: LocalSandallowWrite: [params.sandboxRootPath],denyWrite: denySharedDefaultWritePaths(),denyRead: ['/'],- allowRead: [params.sandboxRootPath, ...codeModeSocketPaths, ...platformAllowRead(params.platform)],+ allowRead: [params.sandboxRootPath, ...codeModeSocketParentAllow(), ...platformAllowRead(params.platform)],};}@@ -183,12 +280,16 @@ function commandEnv(params: {}): Record<string, string> {const tmp = join(params.sandboxRootPath, '.tmp');const home = join(params.sandboxRootPath, '.home');+ const venvDir = sandboxVenvPath(params.sandboxRootPath);const locked = {HOME: home,TMPDIR: tmp,TMP: tmp,TEMP: tmp,- PATH: commandPath(params.platform),+ VIRTUAL_ENV: venvDir,+ // Cwd-relative layout dirs (not host-absolute). Absolute paths under+ // `Application Support` break PATH lookup (`mcp-client: command not found`).+ PATH: `${join(SANDBOX_VENV_DIR, 'bin')}:mcp-client/bin:${commandPath(params.platform)}`,};return {...params.extra,@@ -208,15 +309,16 @@ function sessionFilesystem(platform: LocalSandboxPlatform): {allowWrite,denyWrite: denySharedDefaultWritePaths(),denyRead: ['/'],- allowRead: platformAllowRead(platform),+ allowRead: [...platformAllowRead(platform), ...codeModeSocketParentAllow()],};}/*** AF_UNIX policy is session-scoped only (wrap customConfig cannot set it).- * - Linux: allowAllUnixSockets; pathname connect still needs FS allowRead (bwrap).+ * - Linux: allowAllUnixSockets; pathname connect still needs FS allowRead (bwrap)+ * of the Code Mode socket parent (not host /tmp).* - macOS: allowAllUnixSockets does NOT consult allowRead for connect — use- * allowUnixSockets subpath, synced at sandbox create/remove.+ * allowUnixSockets subpath (sandbox roots + Code Mode parent).*/function sessionNetwork(params: { platform: LocalSandboxPlatform; unixSockets?: string[] }):| {@@ -230,7 +332,7 @@ function sessionNetwork(params: { platform: LocalSandboxPlatform; unixSockets?:allowAllUnixSockets: false;allowUnixSockets: string[];} {- const allowedDomains: string[] = [];+ const allowedDomains = allowedNetworkDomains();const deniedDomains: string[] = [];if (params.platform === 'linux') {return {@@ -249,15 +351,13 @@ function sessionNetwork(params: { platform: LocalSandboxPlatform; 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];+ return [...darwinUnixSocketSandboxRoots, ...codeModeSocketParentAllow()];}function syncDarwinUnixSockets(): void {- // No-op until initSrt: register/unregister may run from transport-only tests.+ // No-op until initSrt: create/remove sandbox may run from tests before initialize.if (SandboxManager.getConfig() === undefined) {return;}@@ -268,7 +368,7 @@ function syncDarwinUnixSockets(): void {SandboxManager.updateConfig(buildSessionConfig(platform));}-/** Single source for process-scoped SRT session config (init + sock register/unregister). */+/** Single source for process-scoped SRT session config (init + sandbox create/remove). */function buildSessionConfig(platform: LocalSandboxPlatform): {network: ReturnType<typeof sessionNetwork>;filesystem: ReturnType<typeof sessionFilesystem>;@@ -279,25 +379,16 @@ function buildSessionConfig(platform: LocalSandboxPlatform): {};}-/** 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);+ // Seatbelt allowWrite matches real paths (/private/var/... on macOS).+ const realRoot = realpathSync(sandboxRootPath);+ darwinUnixSocketSandboxRoots.add(realRoot);syncDarwinUnixSockets();- return sandboxRootPath;+ return realRoot;}export async function removeSandbox(sandboxRootPath: string): Promise<void> {@@ -310,13 +401,19 @@ export async function removeSandbox(sandboxRootPath: string): Promise<void> {* 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> {+export async function initSrt(params: {+ platform: LocalSandboxPlatform;+ /** Dedicated Code Mode UDS parent (realpath); grant this path, not host /tmp. */+ codeModeSocketParentPath?: string | undefined;+}): Promise<void> {activePlatform = params.platform;+ codeModeSocketParentPath =+ params.codeModeSocketParentPath === undefined ? undefined : realpathSync(params.codeModeSocketParentPath);await SandboxManager.initialize(buildSessionConfig(params.platform));}export async function resetSrt(): Promise<void> {- codeModeSocketPaths.clear();+ codeModeSocketParentPath = undefined;activePlatform = undefined;await SandboxManager.reset();}@@ -370,7 +467,7 @@ export async function runSupervisorSession(params: {}): Promise<SessionResult> {const {sandboxRootPath,- command,+ command: rawCommand,shell,platform,cwd = sandboxRootPath,@@ -379,6 +476,7 @@ export async function runSupervisorSession(params: {onChildSpawn,timeoutMs,} = params;+ const command = wrapSandboxCommand({ platform, command: rawCommand });const wrap = await SandboxManager.wrapWithSandboxArgv(command,@@ -386,7 +484,7 @@ export async function runSupervisorSession(params: {{filesystem: filesystemPolicy({ sandboxRootPath, platform }),network: {- allowedDomains: [],+ allowedDomains: allowedNetworkDomains(),deniedDomains: [],},},@@ -512,10 +610,3 @@ export async function runSupervisorSession(params: {});});}--/** 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/trueforge/src/sandbox/local/index.ts b/packages/trueforge/src/sandbox/local/index.tsnew file mode 100644index 000000000..641653428--- /dev/null+++ b/packages/trueforge/src/sandbox/local/index.ts@@ -0,0 +1,15 @@+export {+ CodeModeUdsTransport,+ MAX_CODE_MODE_SOCKET_PARENT_BYTES,+ installMcpFixture,+ localMcpClientRemotePath,+ probeCodeModeUnixSocket,+} 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,+ LocalSandboxSupportProbeAttempt,+ LocalSandboxSupportResult,+} from './provider/LocalSandboxProvider.js';diff --git a/packages/trueforge/src/sandbox/local/provider/LocalSandboxProvider.ts b/packages/trueforge/src/sandbox/local/provider/LocalSandboxProvider.tsnew file mode 100644index 000000000..a82c6e635--- /dev/null+++ b/packages/trueforge/src/sandbox/local/provider/LocalSandboxProvider.ts@@ -0,0 +1,750 @@+/**+ * 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 {+ absolutizeRelativeExecEnv,+ SandboxFileNotFoundError,+ SandboxFileTooLargeError,+ SandboxNotAvailableError,+ SandboxPathIsDirectoryError,+ shellEscape,+ validateNoPathTraversal,+} from '@truefoundry/trueforge-core/core';+import { execFile } from 'node:child_process';+import { existsSync, realpathSync, statSync } from 'node:fs';+import { mkdir, mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';+import { promisify } from 'node:util';+import { ulid } from 'ulid';+import type { Logger } from 'winston';+import {+ assertCodeModeSocketParentPath,+ CodeModeUdsTransport,+ probeCodeModeUnixSocket,+} from '../core/CodeModeUdsTransport.js';+import {+ checkSrtHostDependencies,+ createSandbox,+ initSrt,+ isSrtInitialized,+ removeSandbox,+ resetSrt,+ resolveCommandOnHost,+ resolvePythonExecutableOnHost,+ runSupervisorSession,+ SANDBOX_VENV_DIR,+ srtHostBinaryNames,+ type LocalSandboxPlatform,+ type SessionResult,+} from '../core/hostRun.js';+import { XferFileInfoSchema, type XferFileInfo } from '../schemas/xferFileInfo.js';++const execFileAsync = promisify(execFile);++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;+const VENV_CREATE_TIMEOUT_MS = 60_000;+const VENV_PIP_TIMEOUT_MS = 120_000;+/** Same pin as the Daytona image / git_downloader.py PEP 723 header. */+const VENV_PYDANTIC_PIN = 'pydantic>=2.0.0,<3.0.0';++/** 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 };++/** One host/socket/shell/python candidate tried by {@link LocalSandboxProvider.isSupported}. */+export interface LocalSandboxSupportProbeAttempt {+ kind: 'host' | 'socket' | 'shell' | 'python';+ name: string;+ resolved: string | undefined;+ executable?: string | undefined;+ exitCode?: number | undefined;+ stdout?: string | undefined;+ stderr?: string | undefined;+ protocolError?: string | undefined;+ timedOut?: boolean | undefined;+}++export type LocalSandboxSupportResult =+ | { supported: true; platform: LocalSandboxPlatform; shell: string; python: string }+ | {+ supported: false;+ reason: string;+ platform?: LocalSandboxPlatform | undefined;+ attempts?: readonly LocalSandboxSupportProbeAttempt[] | undefined;+ };++export function formatLocalSandboxSupportReason(params: {+ summary: string;+ attempts: readonly LocalSandboxSupportProbeAttempt[];+}): string {+ const details = params.attempts.map(formatLocalSandboxSupportAttempt).join('; ');+ return details.length === 0 ? params.summary : `${params.summary}: ${details}`;+}++function formatLocalSandboxSupportAttempt(attempt: LocalSandboxSupportProbeAttempt): string {+ if (attempt.resolved === undefined) {+ return attempt.kind === 'host' ? `${attempt.name}: not on PATH` : `${attempt.name}: not on sandbox PATH`;+ }+ const parts = [`${attempt.name}: resolved=${attempt.resolved}`];+ if (attempt.executable !== undefined && attempt.executable !== attempt.resolved) {+ parts.push(`executable=${attempt.executable}`);+ }+ if (attempt.protocolError !== undefined) {+ parts.push(`protocolError=${attempt.protocolError}`);+ }+ if (attempt.exitCode !== undefined) {+ parts.push(`exit=${String(attempt.exitCode)}`);+ }+ if (attempt.timedOut === true) {+ parts.push('timedOut');+ }+ if (attempt.stderr !== undefined && attempt.stderr.length > 0) {+ parts.push(`stderr=${JSON.stringify(attempt.stderr)}`);+ }+ if (attempt.stdout !== undefined && attempt.stdout.length > 0) {+ parts.push(`stdout=${JSON.stringify(attempt.stdout)}`);+ }+ return parts.join(' ');+}++function probeAttemptFromSession(params: {+ kind: 'shell' | 'python';+ name: string;+ resolved: string;+ executable?: string | undefined;+ session: SessionResult;+}): LocalSandboxSupportProbeAttempt {+ return {+ kind: params.kind,+ name: params.name,+ resolved: params.resolved,+ ...(params.executable === undefined ? {} : { executable: params.executable }),+ exitCode: params.session.exitCode,+ stdout: params.session.stdoutText,+ stderr: params.session.stderrText,+ ...(params.session.protocolError === undefined ? {} : { protocolError: params.session.protocolError }),+ timedOut: params.session.timedOut,+ };+}++function unsupported(params: {+ reason: string;+ platform?: LocalSandboxPlatform | undefined;+ attempts?: readonly LocalSandboxSupportProbeAttempt[] | undefined;+}): Extract<LocalSandboxSupportResult, { supported: false }> {+ return {+ supported: false,+ reason: params.reason,+ ...(params.platform === undefined ? {} : { platform: params.platform }),+ ...(params.attempts === undefined ? {} : { attempts: params.attempts }),+ };+}++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 (≤65 bytes after realpath, 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;+ logger: Logger;+}++/** Sandbox-relative path for sandboxed commands (avoids /var vs /private/var seatbelt mismatches). */+function toSandboxRelativePath(params: { sandboxRootPath: string; absolutePath: string }): string {+ const rel = relative(params.sandboxRootPath, params.absolutePath);+ return rel === '' ? '.' : rel;+}++/** True when `descendant` is a real path strictly inside `ancestor` (not equal, not a sibling prefix). */+function isStrictDescendant(params: { ancestor: string; descendant: string }): boolean {+ const rel = relative(params.ancestor, params.descendant);+ return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);+}++function execFileErrorDetail(error: unknown): string {+ if (!(error instanceof Error)) {+ return String(error);+ }+ const parts = [error.message];+ if ('stderr' in error && typeof error.stderr === 'string' && error.stderr.length > 0) {+ parts.push(error.stderr);+ }+ if ('stdout' in error && typeof error.stdout === 'string' && error.stdout.length > 0) {+ parts.push(error.stdout);+ }+ return parts.join(' ');+}++function sessionFailDetail(session: SessionResult): string {+ return [session.protocolError, session.stderrText, session.stdoutText]+ .filter(part => part !== undefined && part.length > 0)+ .join(' ');+}++/**+ * In-sandbox upload: create parent, re-open a 0555 file from a prior init, write with+ * `/bin/cat` (jail PATH prefers Homebrew; a stale Cellar `cat` is ENOENT).+ */+export function localSandboxUploadCommand(remotePath: string): string {+ const parent = dirname(remotePath);+ return [+ `mkdir -p ${shellEscape(parent)}`,+ `{ chmod u+w ${shellEscape(remotePath)} 2>/dev/null || true; }`,+ `/bin/cat > ${shellEscape(remotePath)}`,+ ].join(' && ');+}++export class LocalSandboxProvider implements SandboxProvider {+ readonly type = 'local';+ private readonly sandboxRootPathParent: string;+ private readonly codeModeSocketParentPath: string;+ private readonly support: LocalSandboxSupported;+ private readonly fileMaxBytesForDownload: number;+ private readonly defaultExecTimeoutSeconds: number;+ private srtInitialized = false;+ private readonly logger: Logger;++ /** 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 + Code Mode UDS listen + SRT host binaries + in-sandbox shell + Python 3).+ * On success, returns platform/shell/python to pass into the constructor as `support`.+ */+ static async isSupported(params?: { codeModeSocketParentPath?: string }): Promise<LocalSandboxSupportResult> {+ if (process.platform !== 'darwin' && process.platform !== 'linux') {+ return unsupported({+ reason: `LocalSandboxProvider supports macOS and Linux only (got ${process.platform})`,+ });+ }+ const platform: LocalSandboxPlatform = process.platform;++ let createdSocketParent: string | undefined;+ const socketParentPath = params?.codeModeSocketParentPath;+ try {+ const parentPath = socketParentPath ?? (await mkdtemp(join('/tmp', 'tfc-')));+ if (socketParentPath === undefined) {+ createdSocketParent = parentPath;+ }+ try {+ await probeCodeModeUnixSocket(parentPath);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return unsupported({+ platform,+ attempts: [{ kind: 'socket', name: 'uds', resolved: parentPath, protocolError: message }],+ reason: `Code Mode UDS listen failed: ${message}`,+ });+ }+ } finally {+ if (createdSocketParent !== undefined) {+ await rm(createdSocketParent, { recursive: true, force: true });+ }+ }++ const hostPath = process.env['PATH'];+ const hostAttempts: LocalSandboxSupportProbeAttempt[] = [];+ for (const name of srtHostBinaryNames(platform)) {+ const resolved = await resolveCommandOnHost({+ platform,+ name,+ ...(hostPath === undefined || hostPath.length === 0 ? {} : { pathEnv: hostPath }),+ });+ hostAttempts.push({ kind: 'host', name, resolved });+ }+ if (hostAttempts.some(attempt => attempt.resolved === undefined)) {+ const required = srtHostBinaryNames(platform).join(', ');+ return unsupported({+ platform,+ attempts: hostAttempts,+ reason: formatLocalSandboxSupportReason({+ summary: `SRT host dependencies missing (${platform}: ${required})`,+ attempts: hostAttempts,+ }),+ });+ }++ const srtDeps = await checkSrtHostDependencies();+ if (srtDeps.errors.length > 0) {+ return unsupported({+ platform,+ attempts: hostAttempts.length === 0 ? undefined : hostAttempts,+ reason: `SRT host dependencies failed: ${srtDeps.errors.join('; ')}`,+ });+ }++ const alreadyInitialized = isSrtInitialized();+ let probeRoot: string | undefined;+ const attempts: LocalSandboxSupportProbeAttempt[] = [...hostAttempts];+ const pythonAttempts: LocalSandboxSupportProbeAttempt[] = [];++ try {+ if (!alreadyInitialized) {+ await initSrt({+ platform,+ ...(socketParentPath === undefined ? {} : { codeModeSocketParentPath: socketParentPath }),+ });+ }++ 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) {+ attempts.push({ kind: 'shell', name, resolved: undefined });+ continue;+ }+ const probe = await runSupervisorSession({+ sandboxRootPath: probeRoot,+ platform,+ shell: resolved,+ command: 'echo shell-ok',+ timeoutMs: SUPPORT_PROBE_TIMEOUT_MS,+ });+ const attempt = probeAttemptFromSession({ kind: 'shell', name, resolved, session: probe });+ if (probe.protocolError === undefined && probe.exitCode === 0 && probe.stdoutText.includes('shell-ok')) {+ shell = resolved;+ break;+ }+ attempts.push(attempt);+ }+ if (shell === undefined) {+ return unsupported({+ platform,+ attempts,+ reason: formatLocalSandboxSupportReason({+ summary: 'No usable shell in sandbox (bash or sh via command -v)',+ attempts,+ }),+ });+ }++ let python: string | undefined;+ for (const name of PYTHON_CANDIDATES) {+ const resolved = await resolveCommandOnHost({ platform, name });+ if (resolved === undefined) {+ pythonAttempts.push({ kind: 'python', name, resolved: undefined });+ continue;+ }+ // Prefer the host-resolved interpreter so macOS stubs/symlinks are not+ // executed under seatbelt (xcode-select, python.org /usr/local/bin).+ const executable = (await resolvePythonExecutableOnHost({ commandPath: resolved })) ?? resolved;+ const probe = await runSupervisorSession({+ sandboxRootPath: probeRoot,+ platform,+ shell,+ command: `${shellEscape(executable)} -c ${shellEscape(+ 'import sys; raise SystemExit(0 if sys.version_info[0] == 3 else 1)',+ )}`,+ timeoutMs: SUPPORT_PROBE_TIMEOUT_MS,+ });+ const attempt = probeAttemptFromSession({+ kind: 'python',+ name,+ resolved,+ executable,+ session: probe,+ });+ if (probe.protocolError === undefined && probe.exitCode === 0) {+ python = executable;+ break;+ }+ pythonAttempts.push(attempt);+ }+ if (python === undefined) {+ return unsupported({+ platform,+ attempts: pythonAttempts,+ reason: formatLocalSandboxSupportReason({+ summary: 'No usable Python 3 interpreter in sandbox (python3 or python via command -v)',+ attempts: pythonAttempts,+ }),+ });+ }++ return { supported: true, platform, shell, python };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ const seen = [...attempts, ...pythonAttempts];+ return unsupported({+ platform,+ attempts: seen.length === 0 ? undefined : seen,+ reason:+ seen.length === 0+ ? message+ : `${message}: ${formatLocalSandboxSupportReason({ summary: 'probe aborted', attempts: seen })}`,+ });+ } 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);+ const resolvedParent = resolve(options.sandboxRootPathParent);+ this.sandboxRootPathParent =+ existsSync(resolvedParent) && statSync(resolvedParent).isDirectory()+ ? realpathSync(resolvedParent)+ : resolvedParent;+ // Same validation as CodeModeUdsTransport (absolute, exists, ≤65 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;+ this.logger = options.logger.child({ module: 'LocalSandboxProvider' });+ }++ 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,+ codeModeSocketParentPath: this.codeModeSocketParentPath,+ });+ this.srtInitialized = true;+ }++ /** Missing, non-directory, or not a child of this provider's parent → recreate path in Sandbox. */+ private ensureSandboxRoot(sandboxRootPath: string): void {+ if (!isAbsolute(sandboxRootPath)) {+ throw new SandboxNotAvailableError(sandboxRootPath);+ }+ const resolved = resolve(sandboxRootPath);+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {+ throw new SandboxNotAvailableError(sandboxRootPath);+ }+ const parentReal = existsSync(this.sandboxRootPathParent)+ ? realpathSync(this.sandboxRootPathParent)+ : this.sandboxRootPathParent;+ const realRoot = realpathSync(resolved);+ if (!isStrictDescendant({ ancestor: parentReal, descendant: realRoot })) {+ throw new SandboxNotAvailableError(sandboxRootPath);+ }+ }++ /**+ * Host `python -m venv` (stdlib only), then sandboxed pip for pydantic.+ * Idempotent: skip create when `.venv/bin/python` exists; skip pip when import works.+ */+ private async ensureVenv(sandboxRootPath: string): Promise<void> {+ const venvDir = join(sandboxRootPath, SANDBOX_VENV_DIR);+ const venvPython = join(venvDir, 'bin', 'python');+ if (!existsSync(venvPython)) {+ try {+ await execFileAsync(this.support.python, ['-m', 'venv', venvDir], { timeout: VENV_CREATE_TIMEOUT_MS });+ } catch (error) {+ throw new Error(`Failed to create sandbox ${SANDBOX_VENV_DIR}: ${execFileErrorDetail(error)}`, {+ cause: error,+ });+ }+ }++ const relPython = join(SANDBOX_VENV_DIR, 'bin', 'python');+ const relPip = join(SANDBOX_VENV_DIR, 'bin', 'pip');+ const check = await runSupervisorSession({+ sandboxRootPath,+ platform: this.support.platform,+ shell: this.support.shell,+ command: `${shellEscape(relPython)} -c ${shellEscape('import pydantic')}`,+ timeoutMs: SUPPORT_PROBE_TIMEOUT_MS,+ });+ if (check.protocolError !== undefined) {+ throw new Error(`Sandbox venv pydantic check failed: ${check.protocolError}`);+ }+ if (check.exitCode === 0) {+ return;+ }++ const install = await runSupervisorSession({+ sandboxRootPath,+ platform: this.support.platform,+ shell: this.support.shell,+ command: `${shellEscape(relPip)} install --trusted-host pypi.org --trusted-host files.pythonhosted.org ${shellEscape(VENV_PYDANTIC_PIN)}`,+ timeoutMs: VENV_PIP_TIMEOUT_MS,+ });+ if (install.protocolError !== undefined || install.exitCode !== 0 || install.timedOut) {+ throw new Error(+ `Failed to pip install ${VENV_PYDANTIC_PIN} into sandbox ${SANDBOX_VENV_DIR}: ${sessionFailDetail(install)}`,+ );+ }+ }++ 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()));+ this.logger.info('LocalSandboxProvider created sandbox', {+ sandboxId,+ shell: this.support.shell,+ python: this.support.python,+ });+ await mkdir(join(sandboxId, this.getToolResultDumpDir()), { recursive: true, mode: 0o700 });+ await mkdir(join(sandboxId, this.getFileUploadsDir()), { recursive: true, mode: 0o700 });+ await mkdir(join(sandboxId, this.getSkillsDir()), { recursive: true, mode: 0o700 });+ await this.ensureVenv(sandboxId);+ return { sandboxId };+ }++ async exec(params: SandboxExecParams): Promise<ExecResult> {+ this.ensureSandboxRoot(params.sandboxId);+ try {+ await this.ensureSrt();+ await this.ensureVenv(params.sandboxId);+ const sandboxRootPath = params.sandboxId;+ const cwd =+ params.cwd === undefined || params.cwd === ''+ ? sandboxRootPath+ : this.resolveInSandboxRoot(sandboxRootPath, params.cwd);+ const timeoutSeconds = params.timeoutSeconds ?? this.defaultExecTimeoutSeconds;+ const env =+ params.env === undefined ? undefined : absolutizeRelativeExecEnv({ root: sandboxRootPath, env: params.env });+ const session = await runSupervisorSession({+ sandboxRootPath,+ platform: this.support.platform,+ shell: this.support.shell,+ command: params.command,+ cwd,+ ...(env === undefined ? {} : { 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) {+ if (error instanceof SandboxNotAvailableError) {+ throw 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}.`,+ '- A Python virtualenv lives at .venv. `python` and `pip` on PATH are that environment; packages you `pip install` persist in this sandbox.',+ '- uploads, skills, and tool-results live in the sandbox working directory.',+ '- ALL file creation and writes MUST stay within the sandbox working directory.',+ '- The Agent must NOT write outside the working directory (including host home and /tmp).',+ ].join('\n');+ }++ // Cwd-relative: SRT cwd is the sandbox root. Init mkdir/ln and the agent prompt must not use+ // host-absolute paths — those contain spaces under macOS Application Support and lose quoting.+ // uploads, skills, tool-results, git_downloader.py, .git-credentials, .venv+ // mcp-client/mcp_client.py+ getToolResultDumpDir(): string {+ return 'tool-results';+ }++ getGitCredentialsPath(): string {+ return '.git-credentials';+ }++ getFileUploadsDir(): string {+ return 'uploads';+ }++ getSkillsDir(): string {+ return 'skills';+ }++ getGitDownloaderPath(): string {+ return 'git_downloader.py';+ }++ async downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer> {+ this.ensureSandboxRoot(params.sandboxId);+ await this.ensureSrt();+ await this.ensureVenv(params.sandboxId);+ const sandboxRootPath = params.sandboxId;+ const absolutePath = this.resolveInSandboxRoot(sandboxRootPath, params.path);+ const relPath = toSandboxRelativePath({ sandboxRootPath, absolutePath });+ 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> {+ this.ensureSandboxRoot(params.sandboxId);+ await this.ensureSrt();+ await this.ensureVenv(params.sandboxId);+ 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.+ const absolutePath = this.resolveInSandboxRoot(sandboxRootPath, params.remotePath);+ const remotePath = toSandboxRelativePath({ sandboxRootPath, absolutePath });+ const result = await this.runSandboxCommand({+ sandboxRootPath,+ command: localSandboxUploadCommand(remotePath),+ stdin: params.content,+ });+ if (result.exitCode !== 0) {+ const detail = [result.stderrText, result.stdoutText].filter(part => part.length > 0).join(' ');+ throw new Error(+ detail.length > 0+ ? `upload ${params.remotePath} failed (exit ${String(result.exitCode)}): ${detail}`+ : `upload ${params.remotePath} failed (exit ${String(result.exitCode)})`,+ );+ }+ }++ createCodeModeTransport(): CodeModeTransport {+ return new CodeModeUdsTransport({+ codeModeSocketParentPath: this.codeModeSocketParentPath,+ clientRemotePath: () => join('mcp-client', 'mcp_client.py'),+ });+ }++ /** 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/trueforge/src/sandbox/local/schemas/jsonMessage.tssimilarity index 100%rename from packages/local-sandbox/src/schemas/jsonMessage.tsrename to packages/trueforge/src/sandbox/local/schemas/jsonMessage.tsdiff --git a/packages/local-sandbox/src/schemas/xferFileInfo.ts b/packages/trueforge/src/sandbox/local/schemas/xferFileInfo.tssimilarity index 100%rename from packages/local-sandbox/src/schemas/xferFileInfo.tsrename to packages/trueforge/src/sandbox/local/schemas/xferFileInfo.tsdiff --git a/packages/trueforge/src/sandbox/local/scripts/mcp_client_local.py b/packages/trueforge/src/sandbox/local/scripts/mcp_client_local.pynew file mode 100644index 000000000..0a1eb1af4--- /dev/null+++ b/packages/trueforge/src/sandbox/local/scripts/mcp_client_local.py@@ -0,0 +1,277 @@+#!/usr/bin/env python3+"""Code Mode UDS client — same public surface as product mcp_client.py, stdlib only.++Authoritative reference (do not diverge on API/CLI/policy semantics):+ packages/trueforge-core/src/core/sandbox/scripts/mcp_client.py++Inlined into TypeScript via scripts/generate-local-sandbox-scripts.mjs+(src/sandbox/local/sandboxScripts.gen.ts), same pattern as core sandboxScripts.+"""++from __future__ import annotations++import argparse+import asyncio+import base64+import json+import logging+import os+import socket+import sys+import time+from pathlib import Path+from typing import Any, TypedDict++logger = logging.getLogger(__name__)++MAX_MESSAGE_BYTES = 64 * 1024 * 1024+_TOOLS_CACHE_TTL_SECONDS = 600+++class _ServerConfig(TypedDict):+ allowed_tools: list[str]+++_inflight_list_tools: dict[str, asyncio.Task[list[dict[str, Any]]]] = {}++_raw_servers = os.environ.get("TFY_MCP_SERVERS")+_servers_map: dict[str, _ServerConfig] = (+ json.loads(base64.b64decode(_raw_servers).decode()) if _raw_servers else {}+)+_enable_agent_approvals = os.environ.get("TFY_ENABLE_AGENT_APPROVALS", "true").lower() == "true"+++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 _check_tool_allowed(server: str, tool_name: str) -> None:+ server_config = _servers_map.get(server)+ if server_config is None:+ raise RuntimeError(f"Access denied: MCP server '{server}' is not available for this agent") from None+ server_tools = server_config.get("allowed_tools") or []+ if len(server_tools) > 0 and tool_name not in server_tools:+ raise RuntimeError(f"Access denied: tool '{tool_name}' is not enabled on server '{server}'") from None+++def _cache_path(server: str) -> Path:+ return Path(__file__).parent / f"{server}.tools.json"+++def _read_tools_cache(server: str) -> list[dict[str, Any]] | None:+ p = _cache_path(server)+ if not p.exists():+ return None+ try:+ raw = json.loads(p.read_text(encoding="utf-8"))+ if not isinstance(raw, dict):+ raise ValueError("cache root must be object")+ fetched_at = raw.get("fetched_at")+ tools = raw.get("tools")+ if not isinstance(fetched_at, (int, float)) or not isinstance(tools, list):+ raise ValueError("cache shape invalid")+ if time.time() - float(fetched_at) > _TOOLS_CACHE_TTL_SECONDS:+ p.unlink(missing_ok=True)+ return None+ return [t for t in tools if isinstance(t, dict)]+ except Exception:+ logger.exception("_read_tools_cache")+ p.unlink(missing_ok=True)+ return None+++def _write_tools_cache(server: str, tools: list[dict[str, Any]]) -> None:+ try:+ payload = {"fetched_at": time.time(), "tools": tools}+ _cache_path(server).write_text(json.dumps(payload), encoding="utf-8")+ except Exception:+ logger.exception("_write_tools_cache")+++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 _uds_request_sync(payload: dict[str, Any]) -> Any:+ """Connect → JSON request → write-close → JSON reply (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}")+ ok = reply.get("ok")+ if ok is not True:+ 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 _uds_request(payload: dict[str, Any]) -> Any:+ return await asyncio.to_thread(_uds_request_sync, payload)+++async def _fetch_tools(server: str) -> list[dict[str, Any]]:+ result = await _uds_request({"op": "list_tools", "server": server})+ if not isinstance(result, dict):+ raise RuntimeError(f"list_tools '{server}' returned unexpected shape: {result!r}") from None+ tools = result.get("tools", [])+ if not isinstance(tools, list):+ raise RuntimeError(f"list_tools '{server}' tools is not a list: {tools!r}") from None+ return [t for t in tools if isinstance(t, dict)]+++async def _fetch_and_cache_tools(server: str) -> list[dict[str, Any]]:+ tools = await _fetch_tools(server)+ _write_tools_cache(server, tools)+ return tools+++async def _get_tools(server: str) -> list[dict[str, Any]]:+ cached = _read_tools_cache(server)+ if cached is not None:+ return cached+ task = _inflight_list_tools.get(server)+ if task is None:+ task = asyncio.create_task(_fetch_and_cache_tools(server))+ _inflight_list_tools[server] = task+ task.add_done_callback(lambda _t: _inflight_list_tools.pop(server, None))+ return await task+++async def _get_tool(server: str, tool_name: str) -> dict[str, Any] | None:+ for t in await _get_tools(server):+ if t.get("name") == tool_name:+ return t+ return None+++def _is_destructive(tool: dict[str, Any]) -> bool:+ annotations = tool.get("annotations")+ if annotations is None:+ return False+ if not isinstance(annotations, dict):+ return False+ destructive = annotations.get("destructiveHint")+ read_only = annotations.get("readOnlyHint")+ return bool(destructive) or (not read_only and read_only is not None)+++async def _ensure_non_destructive(server: str, tool_name: str) -> None:+ tool = await _get_tool(server, tool_name)+ if tool is None:+ raise RuntimeError(f"Tool '{tool_name}' not found on MCP server '{server}'") from None+ if _is_destructive(tool):+ raise RuntimeError(+ f"Tool '{tool_name}' on MCP server '{server}' is destructive and cannot be called in Code Mode; "+ f"call it directly so it can go through the user approval flow"+ ) from None+++def _project_call_tool_result(server: str, tool: str, result: Any) -> Any:+ """Project an MCP-wire CallToolResult-shaped object into the user-facing Python value."""+ if not isinstance(result, dict):+ raise RuntimeError(f"call_tool reply for '{server}/{tool}' is malformed: expected object") from None++ if result.get("isError"):+ content = result.get("content")+ text_parts: list[str] = []+ if isinstance(content, list):+ for c in content:+ if isinstance(c, dict) and c.get("type") == "text":+ text = c.get("text")+ if isinstance(text, str) and text:+ text_parts.append(text)+ msg = "; ".join(text_parts) if text_parts else "tool returned an error"+ raise RuntimeError(f"MCP tool error (server={server}, tool={tool}): {msg}") from None++ if result.get("structuredContent") is not None:+ return result["structuredContent"]++ content = result.get("content")+ if isinstance(content, list) and len(content) == 1:+ first = content[0]+ if isinstance(first, dict) and first.get("type") == "text":+ text = first.get("text")+ if isinstance(text, str) and text:+ try:+ return json.loads(text)+ except Exception:+ pass+ if isinstance(content, list) and content:+ return content+ return None+++async def call_tool(server: str, tool: str, body: dict[str, Any]) -> Any:+ _check_tool_allowed(server, tool)+ if _enable_agent_approvals:+ await _ensure_non_destructive(server, tool)++ raw = await _uds_request(+ {+ "op": "call_tool",+ "server": server,+ "tool": tool,+ "arguments": body,+ },+ )+ return _project_call_tool_result(server, tool, raw)+++_USAGE = "mcp_client_local.py call-tool <server> <tool> <args-json>"+++def _build_arg_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(prog="mcp_client_local.py", usage=_USAGE)+ sub = parser.add_subparsers(dest="cmd", required=True)++ call_tool_p = sub.add_parser("call-tool", help="Invoke an MCP tool")+ call_tool_p.add_argument("server")+ call_tool_p.add_argument("tool")+ call_tool_p.add_argument("args_json", metavar="args-json", type=json.loads)++ return parser+++async def _main() -> None:+ args = _build_arg_parser().parse_args()+ try:+ if args.cmd == "call-tool":+ result = await call_tool(args.server, args.tool, args.args_json)+ print(json.dumps(result, default=str))+ except RuntimeError as e:+ sys.exit(str(e))+++if __name__ == "__main__":+ asyncio.run(_main())diff --git a/packages/trueforge/src/sandbox/localLifecycle.ts b/packages/trueforge/src/sandbox/localLifecycle.tsnew file mode 100644index 000000000..89618ae3f--- /dev/null+++ b/packages/trueforge/src/sandbox/localLifecycle.ts@@ -0,0 +1,22 @@+import { existsSync } from 'node:fs';+import { mkdir, rm } from 'node:fs/promises';+import type { Logger } from 'winston';++const SOCKET_PARENT_MODE = 0o700;++/** Exists → warn, then rm + mkdir 0700. Reliability path for leftover UDS files (including watch restarts). */+export async function prepareCodeModeSocketParent(params: { path: string; logger: Logger }): Promise<void> {+ if (existsSync(params.path)) {+ params.logger.warn('Removing leftover Code Mode socket parent', { path: params.path });+ await rm(params.path, { recursive: true, force: true });+ }+ await mkdir(params.path, { recursive: true, mode: SOCKET_PARENT_MODE });+}++export async function removeCodeModeSocketParent(socketParentPath: string): Promise<void> {+ await rm(socketParentPath, { recursive: true, force: true });+}++export async function ensureLocalSandboxRootParent(sandboxRootPathParent: string): Promise<void> {+ await mkdir(sandboxRootPathParent, { recursive: true, mode: SOCKET_PARENT_MODE });+}diff --git a/packages/trueforge/src/sandbox/localRuntime.ts b/packages/trueforge/src/sandbox/localRuntime.tsnew file mode 100644index 000000000..1b63eb84e--- /dev/null+++ b/packages/trueforge/src/sandbox/localRuntime.ts@@ -0,0 +1,21 @@+/**+ * Process-scoped local-sandbox probe cache. `isSupported()` inits SRT and+ * creates a temp sandbox — run once at standalone boot, never per request.+ */+import configuration from '../config';+import type { LocalSandboxSupportResult } from './local/provider/LocalSandboxProvider';++let cachedSupport: LocalSandboxSupportResult | undefined;++export function setCachedLocalSandboxSupport(support: LocalSandboxSupportResult | undefined): void {+ cachedSupport = support;+}++export function getCachedLocalSandboxSupport(): LocalSandboxSupportResult | undefined {+ return cachedSupport;+}++/** Standalone + cached probe succeeded. No DB row required. */+export function isLocalSandboxFallbackEnabled(): boolean {+ return configuration.STANDALONE && cachedSupport?.supported === true;+}diff --git a/packages/local-sandbox/test/smoke.test.ts b/packages/trueforge/tests/sandbox/local/smoke.test.tssimilarity index 92%rename from packages/local-sandbox/test/smoke.test.tsrename to packages/trueforge/tests/sandbox/local/smoke.test.tsindex eeab2a57e..9c01b5907 100644--- a/packages/local-sandbox/test/smoke.test.ts+++ b/packages/trueforge/tests/sandbox/local/smoke.test.ts@@ -14,21 +14,23 @@ 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 { createLogger } from 'winston';+import {+ CodeModeUdsTransport,+ installMcpFixture,+ localMcpClientRemotePath,+} from '../../../src/sandbox/local/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';+} from '../../../src/sandbox/local/core/hostRun.js';+import { LocalSandboxProvider } from '../../../src/sandbox/local/provider/LocalSandboxProvider.js';-const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+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';@@ -41,6 +43,10 @@ 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()}`;+/** Product-shaped allowlist for smoke Code Mode client (demo/ping only). */+const TFY_MCP_SERVERS_DEMO = Buffer.from(JSON.stringify({ demo: { allowed_tools: ['ping'] } }), 'utf8').toString(+ 'base64',+);// 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')),@@ -65,91 +71,88 @@ function sleep(ms: number): Promise<void> {}/**- * Direct check: after initSrt, registerCodeModeSocketPath → updateConfig must- * allow a sandboxed client to connect to that exact sock (and unregister revoke it).+ * After initSrt grants the Code Mode parent, a sock under that parent is+ * connectable; a leftover host /tmp sock outside the parent is not.*/-async function smokeLiveSrtUnixSocketAllowlistUpdate(params: {+async function smokeCodeModeSocketParentAllow(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 allowedSock = join(parent, ulid().toLowerCase());+ const leftoverSock = join('/tmp', `tfy-srt-leak-${ulid().toLowerCase().slice(0, 10)}`);+ await unlink(allowedSock).catch(() => undefined);+ await unlink(leftoverSock).catch(() => undefined);- const server = createServer();- await new Promise<void>((resolve, reject) => {- server.once('error', reject);- server.listen(sockPath, () => {- server.off('error', reject);- resolve();+ const listen = async (path: string): Promise<{ close: () => Promise<void> }> => {+ const server = createServer();+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(path, () => {+ 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,+ server.on('connection', socket => {+ socket.end();});- assert.notEqual(before.exitCode, 0, 'connect must fail before register/updateConfig');- assert.ok(!before.stdoutText.includes('connected'));+ return {+ close: async () => {+ await new Promise<void>(resolve => {+ server.close(() => {+ resolve();+ });+ });+ await unlink(path).catch(() => undefined);+ },+ };+ };- registerCodeModeSocketPath(sockPath);+ const connectCmd = (path: string): string =>+ [+ "python3 - <<'PY'",+ 'import socket, sys',+ `path = ${JSON.stringify(path)}`,+ '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');- const afterRegister = await runSupervisorSession({+ const allowed = await listen(allowedSock);+ const leftover = await listen(leftoverSock);+ try {+ const ok = await runSupervisorSession({sandboxRootPath: params.sandboxRootPath,shell: params.shell,platform: params.platform,- command: connectCmd,+ command: connectCmd(allowedSock),timeoutMs: 10_000,});- assert.equal(afterRegister.exitCode, 0, afterRegister.stderrText);- assert.match(afterRegister.stdoutText, /connected/);+ assert.equal(ok.exitCode, 0, ok.stderrText);+ assert.match(ok.stdoutText, /connected/);- unregisterCodeModeSocketPath(sockPath);-- const afterUnregister = await runSupervisorSession({+ const blocked = await runSupervisorSession({sandboxRootPath: params.sandboxRootPath,shell: params.shell,platform: params.platform,- command: connectCmd,+ command: connectCmd(leftoverSock),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)');+ assert.notEqual(blocked.exitCode, 0, 'connect to leftover /tmp sock must fail');+ assert.ok(!blocked.stdoutText.includes('connected'));+ console.log('ok: SRT allows Code Mode parent UDS and denies leftover host /tmp sock');} finally {- unregisterCodeModeSocketPath(sockPath);- await new Promise<void>(resolve => {- server.close(() => {- resolve();- });- });- await unlink(sockPath).catch(() => undefined);+ await allowed.close();+ await leftover.close();}}@@ -212,6 +215,7 @@ function makeDemoToolSet(params: { onRequest?: () => void }): IToolSet {async function withCodeModeTransport(params: {codeModeSocketParentPath: string;+ sandboxRootPath: string;maxMessageBytes?: number;onProtocolError?: (message: string) => void;onRequest?: () => void;@@ -219,6 +223,7 @@ async function withCodeModeTransport(params: {}): Promise<void> {const transport = new CodeModeUdsTransport({codeModeSocketParentPath: params.codeModeSocketParentPath,+ clientRemotePath: localMcpClientRemotePath,...(params.maxMessageBytes === undefined ? {} : { maxMessageBytes: params.maxMessageBytes }),...(params.onProtocolError === undefined ? {} : { onProtocolError: params.onProtocolError }),});@@ -226,13 +231,19 @@ async function withCodeModeTransport(params: {toolSets: [makeDemoToolSet({ onRequest: params.onRequest })],logger: makeSilentCodeModeLogger(),});+ const install = transport.getClientInstall({ sandboxId: params.sandboxRootPath });try {const { env } = await transport.start({codeModeDispatcher: dispatcher,- sandboxId: 'smoke',+ sandboxId: params.sandboxRootPath,requestTimeoutSeconds: 60,});- await params.run(env);+ await params.run({+ ...env,+ PYTHONPATH: dirname(install.remotePath),+ TFY_MCP_SERVERS: TFY_MCP_SERVERS_DEMO,+ TFY_ENABLE_AGENT_APPROVALS: 'true',+ });} finally {dispatcher.close();await transport.stop();@@ -250,6 +261,7 @@ async function smokeCodeMode(params: {await withCodeModeTransport({codeModeSocketParentPath: params.codeModeSocketParentPath,+ sandboxRootPath: params.sandboxRootPath,onRequest: () => {toolRequests += 1;},@@ -266,18 +278,20 @@ async function smokeCodeMode(params: {);console.log('ok: Code Mode UDS parent 0700 + sock 0600');- const list = await runSupervisorSession({+ const call = await runSupervisorSession({sandboxRootPath: params.sandboxRootPath,shell: params.shell,platform: params.platform,- command: 'python3 mcp_pipe_client.py list-tools --server demo',+ command: `mcp-client call-tool demo ping '${JSON.stringify({ message: 'poc' })}'`,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)');+ assert.equal(call.protocolError, undefined, call.protocolError);+ assert.equal(call.exitCode, 0, call.stderrText);+ const callJson: unknown = JSON.parse(call.stdoutText.trim().split(/\r?\n/).filter(Boolean).at(-1) ?? '');+ assert.ok(callJson !== null && typeof callJson === 'object');+ assert.ok('echo' in callJson);+ console.log('ok: Code Mode call-tool (UDS)');},});@@ -285,6 +299,7 @@ async function smokeCodeMode(params: {let oversizeError: string | undefined;await withCodeModeTransport({codeModeSocketParentPath: params.codeModeSocketParentPath,+ sandboxRootPath: params.sandboxRootPath,maxMessageBytes: oversizeCap,onProtocolError: message => {oversizeError = message;@@ -317,6 +332,7 @@ async function smokeCodeMode(params: {let badJsonError: string | undefined;await withCodeModeTransport({codeModeSocketParentPath: params.codeModeSocketParentPath,+ sandboxRootPath: params.sandboxRootPath,onProtocolError: message => {badJsonError = message;},@@ -347,6 +363,7 @@ async function smokeCodeMode(params: {await withCodeModeTransport({codeModeSocketParentPath: params.codeModeSocketParentPath,+ sandboxRootPath: params.sandboxRootPath,onRequest: () => {toolRequests += 1;},@@ -355,7 +372,20 @@ async function smokeCodeMode(params: {sandboxRootPath: params.sandboxRootPath,shell: params.shell,platform: params.platform,- command: 'python3 mcp_pipe_client.py multiplex --server demo --count 2',+ command: [+ "python3 - <<'PY'",+ 'import asyncio, json, time',+ 'from mcp_client import call_tool',+ 'async def main():',+ ' started = time.monotonic()',+ ' results = await asyncio.gather(',+ ' call_tool("demo", "ping", {"message": "m0", "delay_ms": 150}),',+ ' call_tool("demo", "ping", {"message": "m1", "delay_ms": 150}),',+ ' )',+ ' print("multiplex-ok", int((time.monotonic() - started) * 1000), json.dumps(results))',+ 'asyncio.run(main())',+ 'PY',+ ].join('\n'),env,timeoutMs: 15_000,});@@ -372,6 +402,7 @@ async function smokeCodeMode(params: {const beforeMissing = toolRequests;await withCodeModeTransport({codeModeSocketParentPath: params.codeModeSocketParentPath,+ sandboxRootPath: params.sandboxRootPath,onRequest: () => {toolRequests += 1;},@@ -383,7 +414,7 @@ async function smokeCodeMode(params: {command: ['set -euo pipefail','unset TFY_MCP_SOCK',- 'if python3 mcp_pipe_client.py list-tools --server demo; then',+ `if mcp-client call-tool demo ping '${JSON.stringify({ message: 'x' })}'; then`,' echo "expected missing-sock failure" >&2',' exit 1','fi',@@ -403,6 +434,7 @@ async function smokeCodeMode(params: {let holdPid: number | undefined;await withCodeModeTransport({codeModeSocketParentPath: params.codeModeSocketParentPath,+ sandboxRootPath: params.sandboxRootPath,onRequest: () => {hostInjected += 1;},@@ -1594,10 +1626,15 @@ async function main(): Promise<void> {if (!support.supported) {throw new Error(support.reason);}- const provider = new LocalSandboxProvider({ sandboxRootPathParent, codeModeSocketParentPath, support });+ const provider = new LocalSandboxProvider({+ sandboxRootPathParent,+ codeModeSocketParentPath,+ support,+ logger: createLogger({ silent: true }),+ });const instructions = provider.getAdditionalInstructions();assert.match(instructions, /sandbox shell: \S+/);- assert.match(instructions, /Python 3 is available as: \S+/);+ assert.match(instructions, /virtualenv lives at \.venv/);console.log('ok: getAdditionalInstructions names shell and python');await prepareHostProbeFiles();let codeModeSandboxRootPath: string | undefined;@@ -1615,7 +1652,19 @@ async function main(): Promise<void> {assert.equal(printf.response.result, 'poc-ok\n');console.log('ok: provider exec printf');- await smokeLiveSrtUnixSocketAllowlistUpdate({+ if (support.platform === 'darwin') {+ const opensslCnf = await provider.exec({+ sandboxId,+ command: "python3 -c \"p=open('/etc/ssl/openssl.cnf'); p.read(); p.close(); print('openssl-cnf-ok')\"",+ });+ assert.equal(opensslCnf.success, true);+ if (!opensslCnf.success) throw new Error('unreachable');+ assert.equal(opensslCnf.response.exitCode, 0, opensslCnf.response.result);+ assert.match(opensslCnf.response.result, /openssl-cnf-ok/);+ console.log('ok: darwin can read /etc/ssl/openssl.cnf (LibreSSL symlink spelling)');+ }++ await smokeCodeModeSocketParentAllow({sandboxRootPath: sandboxId,codeModeSocketParentPath,shell: support.shell,@@ -1901,8 +1950,8 @@ async function main(): Promise<void> {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$/);+ assert.match(provider.getToolResultDumpDir(), /tool-results$/);+ assert.match(provider.getGitCredentialsPath(), /\.git-credentials$/);console.log('ok: dump/git credential paths');codeModeSandboxRootPath = await createSandbox(join(sandboxRootPathParent, `codemode-${Date.now()}`));diff --git a/packages/trueforge/tests/unit/apis/capabilities.test.ts b/packages/trueforge/tests/unit/apis/capabilities.test.tsindex 6bdee7d53..78856454f 100644--- a/packages/trueforge/tests/unit/apis/capabilities.test.ts+++ b/packages/trueforge/tests/unit/apis/capabilities.test.ts@@ -12,6 +12,7 @@ import type { OIDCConfig } from '../../../src/config';import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';import { createSqliteDb } from '../../../src/db/sqlite/client';import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';+import { setCachedLocalSandboxSupport } from '../../../src/sandbox/localRuntime';import { checkSnapshotStatus } from '../../../src/sandbox/providerUtils';import type { SandboxBuildStatus, SandboxStatus } from '../../../src/schemas/sandboxProvider';@@ -55,6 +56,11 @@ describe('capabilities routers', () => {beforeEach(() => {mockStatus.mockReset();mockStatus.mockResolvedValue(undefined);+ setCachedLocalSandboxSupport(undefined);+ });++ afterEach(() => {+ setCachedLocalSandboxSupport(undefined);});function makeRouter(): OpenAPIHono {@@ -87,6 +93,28 @@ describe('capabilities routers', () => {});});+ it('reports sandbox + skill enabled when local fallback is cached and no image status exists', async () => {+ disableOidcAuth();+ mockStatus.mockResolvedValue(undefined);+ setCachedLocalSandboxSupport({+ supported: true,+ platform: 'darwin',+ shell: '/bin/bash',+ python: '/usr/bin/python3',+ });+ const router = makeRouter();++ const response = await router.request('/');+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({+ data: {+ sandbox: { enabled: true },+ skill: { enabled: true },+ settings: { enabled: true },+ },+ });+ });+it('reports sandbox + skill enabled only when the image is ready', async () => {disableOidcAuth();mockStatus.mockResolvedValue(buildWithStatus('ready'));diff --git a/packages/trueforge/tests/unit/runtime/sessionResources.test.ts b/packages/trueforge/tests/unit/runtime/sessionResources.test.tsindex 2101b8eaf..4822a13f0 100644--- a/packages/trueforge/tests/unit/runtime/sessionResources.test.ts+++ b/packages/trueforge/tests/unit/runtime/sessionResources.test.ts@@ -7,10 +7,26 @@ import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/Sqimport { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';-import { getModelDetails, validateAgentSpec } from '../../../src/runtime/sessionResources';+import { getModelDetails, localSandboxSessionSegment, validateAgentSpec } from '../../../src/runtime/sessionResources';+import { setCachedLocalSandboxSupport } from '../../../src/sandbox/localRuntime';import type { ReasoningEffort } from '../../../src/schemas/modelProvider';+describe('localSandboxSessionSegment', () => {+ it('keeps a single-segment session id and rejects missing or unsafe values', () => {+ expect(localSandboxSessionSegment('sess_1')).toBe('sess_1');+ expect(localSandboxSessionSegment(undefined)).toBe('_');+ expect(localSandboxSessionSegment('')).toBe('_');+ expect(localSandboxSessionSegment('a/b')).toBe('_');+ expect(localSandboxSessionSegment('..')).toBe('_');+ expect(localSandboxSessionSegment('foo..bar')).toBe('_');+ });+});+describe('validateAgentSpec', () => {+ afterEach(() => {+ setCachedLocalSandboxSupport(undefined);+ });+async function setup(options?: { reasoningEfforts?: ReasoningEffort[] | undefined }) {const db = createSqliteDb(':memory:');await migrateSqliteToLatest(db);@@ -245,4 +261,26 @@ describe('validateAgentSpec', () => {}),).resolves.toBeUndefined();});++ it('admits sandbox.enabled when local fallback is cached and the store is empty', async () => {+ const stores = await setup();+ setCachedLocalSandboxSupport({+ supported: true,+ platform: 'darwin',+ shell: '/bin/bash',+ python: '/usr/bin/python3',+ });+ await expect(+ validateAgentSpec({+ spec: AgentSpecSchema.parse({+ model: { name: 'test-provider/test-model' },+ instructions: 'test',+ config: { sandbox: { enabled: true } },+ }),+ tenant_id: TENANT_ID,+ ...stores,+ }),+ ).resolves.toBeUndefined();+ expect(await stores.sandboxProviderStore.getSandboxProvider(TENANT_ID)).toBeUndefined();+ });});diff --git a/packages/local-sandbox/test/codeModeUdsTransport.contract.test.ts b/packages/trueforge/tests/unit/sandbox/local/codeModeUdsTransport.contract.test.tssimilarity index 91%rename from packages/local-sandbox/test/codeModeUdsTransport.contract.test.tsrename to packages/trueforge/tests/unit/sandbox/local/codeModeUdsTransport.contract.test.tsindex 1d269c924..b0b6ece1b 100644--- a/packages/local-sandbox/test/codeModeUdsTransport.contract.test.ts+++ b/packages/trueforge/tests/unit/sandbox/local/codeModeUdsTransport.contract.test.ts@@ -1,6 +1,5 @@/**- * Node UDS binder for the harness Code Mode transport contract suite.- * Lives in local-sandbox only — no product/server import of this package.+ * Node UDS binder for the Code Mode transport contract suite.*/import {CodeModeDispatcher,@@ -16,9 +15,9 @@ import { join } from 'node:path';import {runCodeModeTransportContractSuite,type CodeModeTransportContractFixture,-} from '../../trueforge-core/tests/core/sandbox/codeMode/codeModeTransportContractSuite';-import { CodeModeUdsTransport } from '../src/core/CodeModeUdsTransport.js';-import { encodeJsonMessage, JsonMessageReader, MAX_MESSAGE_BYTES } from '../src/core/frame.js';+} from '../../../../../trueforge-core/tests/core/sandbox/codeMode/codeModeTransportContractSuite';+import { CodeModeUdsTransport } from '../../../../src/sandbox/local/core/CodeModeUdsTransport.js';+import { encodeJsonMessage, JsonMessageReader, MAX_MESSAGE_BYTES } from '../../../../src/sandbox/local/core/frame.js';function makeSilentLogger() {const logger = {@@ -129,6 +128,7 @@ runCodeModeTransportContractSuite(async (): Promise<CodeModeTransportContractFixawait mkdir(codeModeSocketParentPath, { recursive: true, mode: 0o700 });const transport = new CodeModeUdsTransport({codeModeSocketParentPath,+ clientRemotePath: sandboxId => join(sandboxId, 'mcp-client', 'mcp_client.py'),});const dispatcher = new CodeModeDispatcher({toolSets: [makeDemoToolSet()],diff --git a/packages/trueforge/tests/unit/sandbox/local/core/codeModeSocket.test.ts b/packages/trueforge/tests/unit/sandbox/local/core/codeModeSocket.test.tsnew file mode 100644index 000000000..2a84d8516--- /dev/null+++ b/packages/trueforge/tests/unit/sandbox/local/core/codeModeSocket.test.ts@@ -0,0 +1,67 @@+import { realpathSync } from 'node:fs';+import { mkdir, rm } from 'node:fs/promises';+import { join } from 'node:path';+import {+ MAX_CODE_MODE_SOCKET_PARENT_BYTES,+ assertCodeModeSocketParentPath,+ probeCodeModeUnixSocket,+} from '../../../../../src/sandbox/local/core/CodeModeUdsTransport';+import { LocalSandboxProvider } from '../../../../../src/sandbox/local/provider/LocalSandboxProvider';++async function mkdirWithRealpathBytes(bytes: number): Promise<string> {+ const prefix = '/tmp';+ const realPrefix = realpathSync(prefix);+ const nameLen = bytes - Buffer.byteLength(realPrefix) - 1;+ if (nameLen < 1) {+ throw new Error(`cannot build a ${String(bytes)}-byte path under ${realPrefix}`);+ }+ const dir = join(prefix, 's'.repeat(nameLen));+ await mkdir(dir, { recursive: true, mode: 0o700 });+ if (Buffer.byteLength(realpathSync(dir)) !== bytes) {+ await rm(dir, { recursive: true, force: true });+ throw new Error(`realpath of ${dir} is not ${String(bytes)} bytes`);+ }+ return dir;+}++describe('Code Mode UDS parent length', () => {+ it('allows a 65-byte realpath parent and listens', async () => {+ const dir = await mkdirWithRealpathBytes(MAX_CODE_MODE_SOCKET_PARENT_BYTES);+ try {+ expect(assertCodeModeSocketParentPath(dir)).toBe(realpathSync(dir));+ const { sockPath } = await probeCodeModeUnixSocket(dir);+ expect(sockPath.startsWith(realpathSync(dir))).toBe(true);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });++ it('rejects a 66-byte realpath parent', async () => {+ const dir = await mkdirWithRealpathBytes(MAX_CODE_MODE_SOCKET_PARENT_BYTES + 1);+ try {+ expect(() => assertCodeModeSocketParentPath(dir)).toThrow(/at most 65 bytes/);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });+});++describe('LocalSandboxProvider.isSupported socket probe', () => {+ it('returns unsupported when the configured parent is over the byte limit', async () => {+ if (process.platform !== 'darwin' && process.platform !== 'linux') {+ return;+ }+ const dir = await mkdirWithRealpathBytes(MAX_CODE_MODE_SOCKET_PARENT_BYTES + 1);+ try {+ const support = await LocalSandboxProvider.isSupported({ codeModeSocketParentPath: dir });+ expect(support.supported).toBe(false);+ if (support.supported) {+ return;+ }+ expect(support.reason).toContain('Code Mode UDS listen failed');+ expect(support.reason).toContain('65 bytes');+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });+});diff --git a/packages/trueforge/tests/unit/sandbox/local/core/darwinSandboxNetworkShellPreamble.test.ts b/packages/trueforge/tests/unit/sandbox/local/core/darwinSandboxNetworkShellPreamble.test.tsnew file mode 100644index 000000000..fdbd409c1--- /dev/null+++ b/packages/trueforge/tests/unit/sandbox/local/core/darwinSandboxNetworkShellPreamble.test.ts@@ -0,0 +1,10 @@+import { darwinSandboxNetworkShellPreamble } from '../../../../../src/sandbox/local/core/hostRun';++describe('darwinSandboxNetworkShellPreamble', () => {+ it('rewrites localhost to 127.0.0.1 in SRT proxy env vars', () => {+ const preamble = darwinSandboxNetworkShellPreamble();+ expect(preamble).toMatch(/HTTP_PROXY="\$\{HTTP_PROXY\/\/localhost\/127\.0\.0\.1\}"/);+ expect(preamble).toMatch(/HTTPS_PROXY="\$\{HTTPS_PROXY\/\/localhost\/127\.0\.0\.1\}"/);+ expect(preamble).toMatch(/ALL_PROXY="\$\{ALL_PROXY\/\/localhost\/127\.0\.0\.1\}"/);+ });+});diff --git a/packages/trueforge/tests/unit/sandbox/local/core/resolvePythonExecutableOnHost.test.ts b/packages/trueforge/tests/unit/sandbox/local/core/resolvePythonExecutableOnHost.test.tsnew file mode 100644index 000000000..0712b3174--- /dev/null+++ b/packages/trueforge/tests/unit/sandbox/local/core/resolvePythonExecutableOnHost.test.ts@@ -0,0 +1,50 @@+import { existsSync, realpathSync } from 'node:fs';+import {+ commandPath,+ platformAllowRead,+ resolvePythonExecutableOnHost,+} from '../../../../../src/sandbox/local/core/hostRun';++function pathCoveredByAllowRead(params: { path: string; allowRead: readonly string[] }): boolean {+ return params.allowRead.some(root => params.path === root || params.path.startsWith(`${root}/`));+}++describe('resolvePythonExecutableOnHost', () => {+ it('unwraps the macOS /usr/bin/python3 xcode-select stub', async () => {+ if (process.platform !== 'darwin') {+ return;+ }+ const executable = await resolvePythonExecutableOnHost({ commandPath: '/usr/bin/python3' });+ expect(executable).toEqual(expect.stringMatching(/^\/.+/));+ expect(executable).not.toBe('/usr/bin/python3');+ });++ it('realpath-unwraps python.org /usr/local/bin/python3 when present', async () => {+ if (process.platform !== 'darwin' || !existsSync('/usr/local/bin/python3')) {+ return;+ }+ const executable = await resolvePythonExecutableOnHost({ commandPath: '/usr/local/bin/python3' });+ expect(executable).toBe(realpathSync('/usr/local/bin/python3'));+ expect(executable).not.toBe('/usr/local/bin/python3');+ });+});++describe('sandbox PATH vs allowRead', () => {+ it.each(['darwin', 'linux'] as const)('every %s PATH directory is under an allowRead root', platform => {+ const allowRead = platformAllowRead(platform);+ for (const dir of commandPath(platform).split(':')) {+ expect(pathCoveredByAllowRead({ path: dir, allowRead })).toBe(true);+ }+ });++ it('does not grant host /tmp on linux (Code Mode parent is allowRead separately)', () => {+ expect(platformAllowRead('linux')).not.toContain('/tmp');+ });++ it('grants /etc and /private/etc on darwin (symlink + resolved spelling)', () => {+ expect(platformAllowRead('linux')).toContain('/etc');+ expect(platformAllowRead('linux')).not.toContain('/private/etc');+ expect(platformAllowRead('darwin')).toContain('/etc');+ expect(platformAllowRead('darwin')).toContain('/private/etc');+ });+});diff --git a/packages/trueforge/tests/unit/sandbox/local/provider/missingRoot.test.ts b/packages/trueforge/tests/unit/sandbox/local/provider/missingRoot.test.tsnew file mode 100644index 000000000..783245a5d--- /dev/null+++ b/packages/trueforge/tests/unit/sandbox/local/provider/missingRoot.test.ts@@ -0,0 +1,92 @@+import { SandboxNotAvailableError } from '@truefoundry/trueforge-core/core';+import { mkdir, mkdtemp, rm, symlink } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createLogger } from 'winston';+import { LocalSandboxProvider } from '../../../../../src/sandbox/local/provider/LocalSandboxProvider';++async function makeProvider(sandboxRootPathParent: string): Promise<LocalSandboxProvider> {+ const codeModeSocketParentPath = join(tmpdir(), 'cm');+ await mkdir(codeModeSocketParentPath, { recursive: true, mode: 0o700 });+ return new LocalSandboxProvider({+ sandboxRootPathParent,+ codeModeSocketParentPath,+ support: { supported: true, platform: 'darwin', shell: '/bin/bash', python: '/usr/bin/python3' },+ logger: createLogger({ silent: true }),+ });+}++describe('LocalSandboxProvider missing root', () => {+ it('throws SandboxNotAvailableError when the sandbox root does not exist', async () => {+ const sandboxRootPathParent = await mkdtemp(join(tmpdir(), 'tfy-local-missing-'));+ const provider = await makeProvider(sandboxRootPathParent);+ try {+ await expect(+ provider.exec({ sandboxId: join(sandboxRootPathParent, 'does-not-exist'), command: 'true' }),+ ).rejects.toBeInstanceOf(SandboxNotAvailableError);+ } finally {+ await rm(sandboxRootPathParent, { recursive: true, force: true });+ }+ });++ it('throws SandboxNotAvailableError when the id is the parent itself', async () => {+ const sandboxRootPathParent = await mkdtemp(join(tmpdir(), 'tfy-local-parent-id-'));+ const provider = await makeProvider(sandboxRootPathParent);+ try {+ await expect(provider.exec({ sandboxId: sandboxRootPathParent, command: 'true' })).rejects.toBeInstanceOf(+ SandboxNotAvailableError,+ );+ } finally {+ await rm(sandboxRootPathParent, { recursive: true, force: true });+ }+ });++ it('throws SandboxNotAvailableError when the id is outside the parent', async () => {+ const sandboxRootPathParent = await mkdtemp(join(tmpdir(), 'tfy-local-jail-'));+ const outside = await mkdtemp(join(tmpdir(), 'tfy-local-outside-'));+ const provider = await makeProvider(sandboxRootPathParent);+ try {+ await expect(provider.exec({ sandboxId: outside, command: 'true' })).rejects.toBeInstanceOf(+ SandboxNotAvailableError,+ );+ } finally {+ await rm(sandboxRootPathParent, { recursive: true, force: true });+ await rm(outside, { recursive: true, force: true });+ }+ });++ it('throws SandboxNotAvailableError when a child path is a symlink out of the parent', async () => {+ const sandboxRootPathParent = await mkdtemp(join(tmpdir(), 'tfy-local-symlink-'));+ const outside = await mkdtemp(join(tmpdir(), 'tfy-local-symlink-target-'));+ const alias = join(sandboxRootPathParent, 'alias');+ await symlink(outside, alias);+ const provider = await makeProvider(sandboxRootPathParent);+ try {+ await expect(provider.exec({ sandboxId: alias, command: 'true' })).rejects.toBeInstanceOf(+ SandboxNotAvailableError,+ );+ } finally {+ await rm(sandboxRootPathParent, { recursive: true, force: true });+ await rm(outside, { recursive: true, force: true });+ }+ });++ it('layout paths are cwd-relative (not host-absolute)', async () => {+ const sandboxRootPathParent = await mkdtemp(join(tmpdir(), 'tfy-local-layout-'));+ const provider = await makeProvider(sandboxRootPathParent);+ try {+ expect(provider.getToolResultDumpDir()).toBe('tool-results');+ expect(provider.getGitCredentialsPath()).toBe('.git-credentials');+ expect(provider.getFileUploadsDir()).toBe('uploads');+ expect(provider.getSkillsDir()).toBe('skills');+ expect(provider.getGitDownloaderPath()).toBe('git_downloader.py');+ const install = provider.createCodeModeTransport().getClientInstall({+ sandboxId: join(sandboxRootPathParent, 'x'),+ });+ expect(install.remotePath).toBe(join('mcp-client', 'mcp_client.py'));+ expect(install.remotePath.startsWith('/')).toBe(false);+ } finally {+ await rm(sandboxRootPathParent, { recursive: true, force: true });+ }+ });+});diff --git a/packages/local-sandbox/test/provider/contract.test.ts b/packages/trueforge/tests/unit/sandbox/local/provider/provider.contract.test.tssimilarity index 65%rename from packages/local-sandbox/test/provider/contract.test.tsrename to packages/trueforge/tests/unit/sandbox/local/provider/provider.contract.test.tsindex 4b0f55944..de6dacde1 100644--- a/packages/local-sandbox/test/provider/contract.test.ts+++ b/packages/trueforge/tests/unit/sandbox/local/provider/provider.contract.test.ts@@ -1,23 +1,28 @@import { mkdir, mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { runSandboxProviderContractSuite } from '../../../trueforge-core/tests/core/sandbox/provider/sandboxProviderContractSuite';-import { LocalSandboxProvider } from '../../src/provider/LocalSandboxProvider';+import { createLogger } from 'winston';+import { runSandboxProviderContractSuite } from '../../../../../../trueforge-core/tests/core/sandbox/provider/sandboxProviderContractSuite';+import { LocalSandboxProvider } from '../../../../../src/sandbox/local/provider/LocalSandboxProvider';describe('LocalSandboxProvider (SandboxProvider contract)', () => {runSandboxProviderContractSuite(async () => {const support = await LocalSandboxProvider.isSupported();+ if (!support.supported) {+ pending(`Local sandbox not supported: ${support.reason}`);+ }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.+ // Short path: macOS tmpdir ~48 bytes; keep parent ≤65 for Code Mode UDS.const codeModeSocketParentPath = join(tmpdir(), 'cm');await mkdir(codeModeSocketParentPath, { recursive: true, mode: 0o700 });const provider = new LocalSandboxProvider({sandboxRootPathParent,codeModeSocketParentPath,support,+ logger: createLogger({ silent: true }),});return {provider,diff --git a/packages/trueforge/tests/unit/sandbox/local/provider/supportReason.test.ts b/packages/trueforge/tests/unit/sandbox/local/provider/supportReason.test.tsnew file mode 100644index 000000000..93f6d2d82--- /dev/null+++ b/packages/trueforge/tests/unit/sandbox/local/provider/supportReason.test.ts@@ -0,0 +1,47 @@+import { srtHostBinaryNames } from '../../../../../src/sandbox/local/core/hostRun';+import { formatLocalSandboxSupportReason } from '../../../../../src/sandbox/local/provider/LocalSandboxProvider';++describe('SRT host binaries', () => {+ it('requires bwrap, socat, and rg on Linux', () => {+ expect(srtHostBinaryNames('linux')).toEqual(['bwrap', 'socat', 'rg']);+ });++ it('requires no extra host binaries on macOS (seatbelt, no rg scan)', () => {+ expect(srtHostBinaryNames('darwin')).toEqual([]);+ });+});++describe('formatLocalSandboxSupportReason', () => {+ it('reports missing host SRT binaries on PATH', () => {+ expect(+ formatLocalSandboxSupportReason({+ summary: 'SRT host dependencies missing (linux: bwrap, socat, rg)',+ attempts: [+ { kind: 'host', name: 'bwrap', resolved: undefined },+ { kind: 'host', name: 'socat', resolved: '/usr/bin/socat' },+ { kind: 'host', name: 'rg', resolved: undefined },+ ],+ }),+ ).toBe(+ 'SRT host dependencies missing (linux: bwrap, socat, rg): bwrap: not on PATH; socat: resolved=/usr/bin/socat; rg: not on PATH',+ );+ });++ it('includes the UDS listen error', () => {+ expect(+ formatLocalSandboxSupportReason({+ summary: 'Code Mode UDS listen failed',+ attempts: [+ {+ kind: 'socket',+ name: 'uds',+ resolved: '/private/tmp/tf_cms',+ protocolError: 'listen /private/tmp/tf_cms/01h (90 bytes): listen EADDRINUSE',+ },+ ],+ }),+ ).toBe(+ 'Code Mode UDS listen failed: uds: resolved=/private/tmp/tf_cms protocolError=listen /private/tmp/tf_cms/01h (90 bytes): listen EADDRINUSE',+ );+ });+});diff --git a/packages/trueforge/tests/unit/sandbox/local/provider/uploadCommand.test.ts b/packages/trueforge/tests/unit/sandbox/local/provider/uploadCommand.test.tsnew file mode 100644index 000000000..227a1526f--- /dev/null+++ b/packages/trueforge/tests/unit/sandbox/local/provider/uploadCommand.test.ts@@ -0,0 +1,9 @@+import { localSandboxUploadCommand } from '../../../../../src/sandbox/local/provider/LocalSandboxProvider';++describe('localSandboxUploadCommand', () => {+ it('creates the parent, reopens a prior 0555 file, and writes with /bin/cat', () => {+ expect(localSandboxUploadCommand('mcp-client/mcp_client.py')).toBe(+ "mkdir -p 'mcp-client' && { chmod u+w 'mcp-client/mcp_client.py' 2>/dev/null || true; } && /bin/cat > 'mcp-client/mcp_client.py'",+ );+ });+});diff --git a/packages/trueforge/tests/unit/tsconfig.json b/packages/trueforge/tests/unit/tsconfig.jsonindex e8486b199..5383d43d2 100644--- a/packages/trueforge/tests/unit/tsconfig.json+++ b/packages/trueforge/tests/unit/tsconfig.json@@ -3,5 +3,6 @@// AgentPassthroughEventSchemaMap, which widens SessionEventItem and breaks the// route handler types of any server source pulled in alongside it."extends": "../../tsconfig.json",- "include": ["**/*"]+ "include": ["**/*"],+ "exclude": ["**/*.contract.test.ts"]}diff --git a/packages/trueforge/tsup.config.ts b/packages/trueforge/tsup.config.tsindex 9ea6ba650..6156c2f75 100644--- a/packages/trueforge/tsup.config.ts+++ b/packages/trueforge/tsup.config.ts@@ -41,6 +41,8 @@ export default defineConfig([...migrationEntries('postgres'),...migrationEntries('sqlite'),},+ // SRT vendor helpers must resolve from node_modules at runtime (createRequire).+ external: ['@anthropic-ai/sandbox-runtime'],},{...shared,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a594ff06e..8570eddcb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -110,42 +110,11 @@ importers:specifier: ^2.0.2version: 2.0.2([email protected])- packages/local-sandbox:+ packages/trueforge:dependencies:'@anthropic-ai/sandbox-runtime':specifier: 0.0.71version: 0.0.71- '@truefoundry/trueforge-core':- specifier: workspace:*- version: link:../trueforge-core- 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/trueforge:- dependencies:'@daytona/sdk':specifier: ^0.204.1