From 506d7b99ffb8fef4018de43eb25b2ae2c6f6344a Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 3 Oct 2026 18:52:24 +0200 Subject: [PATCH 1/5] fix(sandbox): refresh and harden all bundled harnesses --- .agents/repo.md | 8 +- .../system/harnesses/gemini/harness.yml | 16 +- .../system/harnesses/opencode/harness.yml | 12 +- .../platform/system/harnesses/pi/harness.yml | 4 +- .../harnesses/gemini-settings-build.test.ts | 30 +++ .../tests/guards/turbo-inputs.guard.test.ts | 4 + .../container-sandbox-runtime-test.ts | 179 ++++++++++++++---- .../tests/manual/reference/automation.md | 4 +- services/platform/turbo.json | 1 + services/sandbox-runtime/Dockerfile | 42 ++-- .../sandbox-runtime/Dockerfile.dockerignore | 14 ++ services/sandbox-runtime/README.md | 44 +++++ .../sandbox-runtime/build-gemini-settings.ts | 98 ++++++++++ .../daemon/src/gemini-settings-test-helper.ts | 55 ++++++ .../daemon/src/gemini-settings.test.ts | 150 +++++++++++++++ .../daemon/src/harness-wrapper-cancel.test.ts | 25 ++- .../daemon/src/tale-hermes-run.test.ts | 35 ++++ .../daemon/src/tale-openclaw-run.test.ts | 31 ++- services/sandbox-runtime/daemon/turbo.json | 3 + services/sandbox-runtime/tale-gemini-run | 99 ++++++---- services/sandbox-runtime/tale-hermes-run | 17 +- services/sandbox-runtime/tale-openclaw-run | 4 +- services/sandbox-runtime/tale-pi-run | 2 +- services/sandbox-runtime/tale-qwen-run | 2 +- 24 files changed, 757 insertions(+), 122 deletions(-) create mode 100644 services/platform/lib/harnesses/gemini-settings-build.test.ts create mode 100644 services/sandbox-runtime/build-gemini-settings.ts create mode 100644 services/sandbox-runtime/daemon/src/gemini-settings-test-helper.ts create mode 100644 services/sandbox-runtime/daemon/src/gemini-settings.test.ts diff --git a/.agents/repo.md b/.agents/repo.md index 74befef1ef..37126e86b8 100644 --- a/.agents/repo.md +++ b/.agents/repo.md @@ -551,7 +551,7 @@ xlsx,odt}.ts`) still reach the catch-all as `failed` + `indexer_error` and are r harness YAML declares `capabilities.resume: false`: every later kick of a task, every automatic retry and every answered ask starts a fresh conversation over the preserved workspace with the brief and the earlier rounds restated, where the other harnesses hand the exec the announced - handle (2026-10). Paying it down means a sandbox-runtime pin that carries the upstream fix — - which first needs root-owned system-settings staging in `tale-gemini-run`, as the - `GEMINI_CLI_VERSION` note in `services/sandbox-runtime/Dockerfile` says — then flipping the - flag and restoring the `resume` argv slot (the schema holds the two coherent). + handle (2026-10). The runtime now bakes root-owned system settings for Gemini 0.62.0; + the resume bug remains open. Paying it down means a sandbox-runtime pin that carries + the upstream fix, then flipping the flag and restoring the `resume` argv slot (the schema + holds the two coherent). diff --git a/configs/platform/system/harnesses/gemini/harness.yml b/configs/platform/system/harnesses/gemini/harness.yml index 3d4eb2eff5..c59f02e4af 100644 --- a/configs/platform/system/harnesses/gemini/harness.yml +++ b/configs/platform/system/harnesses/gemini/harness.yml @@ -5,10 +5,12 @@ # # Prompt + instructions + settings travel as ONE JSON object on stdin, never # argv: process lists leak argv, and a prompt starting with '-' would parse -# as a flag. The wrapper reads to EOF, stages the settings as a per-exec -# SYSTEM settings file (GEMINI_CLI_SYSTEM_SETTINGS_PATH — system scope wins +# as a flag. The wrapper reads to EOF, selects immutable image settings +# derived from this harness and the existing interpreter at image build +# (GEMINI_CLI_SYSTEM_SETTINGS_PATH — system scope wins # over any repo .gemini/settings.json, so a run is reproducible regardless -# of repo contents), stages the instructions as a per-exec context file +# of repo contents, with the root ownership Gemini 0.60+ requires), refuses +# an image/settings mismatch, stages the instructions as a per-exec context file # under ~/.gemini/ added to `context.fileName` alongside GEMINI.md (appended # to the model context every turn WITHOUT replacing the CLI's core system # prompt — GEMINI_SYSTEM_MD would replace it and drop the defaults), then @@ -45,8 +47,7 @@ capabilities: # FRESH conversation over the preserved workspace (the planners read this # flag; the exec builder refuses a handle). Flip to true and restore the # `resume: { flag: '--resume' }` argv slot once the pin carries the - # upstream fix — see the GEMINI_CLI_VERSION note in the sandbox-runtime - # Dockerfile for what a bump past 0.59.0 needs first. + # upstream fix (still open on the pinned 0.62.0). resume: false parser: gemini-stream exec: @@ -93,7 +94,10 @@ exec: # no rule for unchanged — on both lanes, so a byo Google # `gemini-3-flash` is not silently promoted either. Upstream # narrowed the rewrite to its own aliases in 0.61.0 - # (isPromotableFlashModel). The runtime image test drives the + # (isPromotableFlashModel). Keep the supported setting during + # rolling upgrades: older platform images still send it, and + # the runtime verifies the complete policy before launching. + # The runtime image test drives the # pinned CLI through the wrapper with these settings and # asserts the request path keeps a flash-suffixed id. - set: diff --git a/configs/platform/system/harnesses/opencode/harness.yml b/configs/platform/system/harnesses/opencode/harness.yml index 64056f1331..a36554f4e9 100644 --- a/configs/platform/system/harnesses/opencode/harness.yml +++ b/configs/platform/system/harnesses/opencode/harness.yml @@ -1,7 +1,7 @@ # Sandbox harness — OpenCode (`opencode run`). Managed only: its provider # config points at the platform gateway and authenticates with the session -# virtual key; there is no bring-your-own path. The prompt rides argv — the -# CLI has no stdin prompt channel. `opencode run` has no turn-cap flag; the +# virtual key; there is no bring-your-own path. The prompt rides argv for +# compatibility with existing runtime images. `opencode run` has no turn-cap flag; the # runaway backstop is the platform runner. # # Config is injected via OPENCODE_CONFIG_CONTENT (the envDoc below) so @@ -39,11 +39,9 @@ exec: - model: flag: '-m' value: 'tale/${model}' - # Prompt as the trailing positional (argv element — no shell). Unlike - # the stdin contract the other harnesses honor, `opencode run` only - # accepts the prompt as a positional `[message..]` argument — it has no - # stdin/`-` prompt source — so it cannot honor the argv-leak guard. This - # is the CLI's documented surface, not a leak we can avoid here. + # Keep the trailing positional for older runtime images during a roll. + # OpenCode 1.18.34 also accepts piped stdin; moving this adapter to that + # channel requires a separately verified platform/runtime transition. - prompt: {} stdin: mode: none diff --git a/configs/platform/system/harnesses/pi/harness.yml b/configs/platform/system/harnesses/pi/harness.yml index a899558718..cd44d4e072 100644 --- a/configs/platform/system/harnesses/pi/harness.yml +++ b/configs/platform/system/harnesses/pi/harness.yml @@ -1,8 +1,8 @@ # Sandbox harness — Pi, driven through the tale-pi-run wrapper (prompt + # per-exec config as one JSON object on stdin, staged to disk before the CLI # starts — process lists leak argv, and a prompt starting with '-' would -# parse as a flag). Pi has no MCP support at all, so no MCP-delivered -# tooling (browser server, connector bridge) reaches it. Its +# parse as a flag). This adapter does not stage Pi's MCP configuration, so +# MCP-delivered tooling (browser server, connector bridge) is unavailable. Its # bring-your-own backend is commonly OpenRouter-style and speaks the # catalog's vendor-prefixed ids, so refs resolve in the catalog dialect. # diff --git a/services/platform/lib/harnesses/gemini-settings-build.test.ts b/services/platform/lib/harnesses/gemini-settings-build.test.ts new file mode 100644 index 0000000000..0d63ce8232 --- /dev/null +++ b/services/platform/lib/harnesses/gemini-settings-build.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest'; + +import { + geminiPolicies, + GEMINI_BRIDGE_URL, + GEMINI_CONTEXT_FILE, +} from '../../../sandbox-runtime/build-gemini-settings'; +import { loadHarnesses } from '../../backend/core/lib/providers/load_system_config'; +import { buildHarnessExec } from './exec-builder'; +import { batteryFor } from './test-helpers'; + +describe('Gemini image policy coverage', () => { + const fact = loadHarnesses().find((entry) => entry.slug === 'gemini')!; + const policies = [...geminiPolicies(fact).values()]; + it.each(batteryFor(fact))( + 'covers the complete settings of $name', + ({ spec }) => { + const envelope = JSON.parse(buildHarnessExec(fact, spec).stdin!); + const settings = envelope.settings; + if (settings.mcpServers?.connectors) { + settings.mcpServers.connectors.env.TALE_CONNECTORS_URL = + GEMINI_BRIDGE_URL; + } + expect(policies).toContainEqual({ + ...settings, + context: { fileName: ['GEMINI.md', GEMINI_CONTEXT_FILE] }, + }); + }, + ); +}); diff --git a/services/platform/tests/guards/turbo-inputs.guard.test.ts b/services/platform/tests/guards/turbo-inputs.guard.test.ts index 6a7ff010ec..597e32fc85 100644 --- a/services/platform/tests/guards/turbo-inputs.guard.test.ts +++ b/services/platform/tests/guards/turbo-inputs.guard.test.ts @@ -131,6 +131,10 @@ const OUTSIDE_READS = [ path: 'services/sandbox-llm-gateway/docker-entrypoint.sh', readers: 'backend/core/node_only/sandbox/gateway_setup_token.test.ts', }, + { + path: 'services/sandbox-runtime/build-gemini-settings.ts', + readers: 'lib/harnesses/gemini-settings-build.test.ts', + }, { // Its engine install RUN, run under /bin/sh with recording doubles. path: 'services/sandbox-runtime/Dockerfile', diff --git a/services/platform/tests/integration/container-sandbox-runtime-test.ts b/services/platform/tests/integration/container-sandbox-runtime-test.ts index 012a30c17d..6dd8e81016 100644 --- a/services/platform/tests/integration/container-sandbox-runtime-test.ts +++ b/services/platform/tests/integration/container-sandbox-runtime-test.ts @@ -225,11 +225,105 @@ const { chromium } = require('/opt/agents/lib/node_modules/@playwright/mcp/node_ NODEEOF`, ); } -// Pinned versions resolve (a broken install would non-zero here). -await assertOk('claude --version runs', 10001, 'claude --version'); -await assertOk('opencode --version runs', 10001, 'opencode --version'); -await assertOk('hermes --version runs', 10001, 'hermes --version'); -await assertOk('codex --version runs', 10001, 'codex --version'); +// Every bundled harness must start offline from an empty HOME as the agent, +// report its exact source pin, and finish within a generous cold-start bound. +// Print timings so upgrades expose startup regressions without a noisy +// machine-speed microbenchmark. Separate homes prevent one CLI warming another. +{ + const dockerfile = readFileSync( + join(PROJECT_ROOT, 'services/sandbox-runtime/Dockerfile'), + 'utf8', + ); + const harnessPins = [ + ['claude-code', 'claude', 'CLAUDE_CODE_VERSION'], + ['codex', 'codex', 'CODEX_VERSION'], + ['cursor', 'agent', 'CURSOR_AGENT_VERSION'], + ['gemini', 'gemini', 'GEMINI_CLI_VERSION'], + ['hermes', 'hermes', 'HERMES_AGENT_VERSION'], + ['openclaw', 'openclaw', 'OPENCLAW_VERSION'], + ['opencode', 'opencode', 'OPENCODE_VERSION'], + ['pi', 'pi', 'PI_CODING_AGENT_VERSION'], + ['qwen-code', 'qwen', 'QWEN_CODE_VERSION'], + ] as const; + const registrySlugs = readdirSync( + join(PROJECT_ROOT, 'configs/platform/system/harnesses'), + { withFileTypes: true }, + ) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort(); + if ( + JSON.stringify(registrySlugs) !== + JSON.stringify(harnessPins.map(([slug]) => slug)) + ) { + fail('every registry harness has an exact-version startup probe'); + } + const probes: { slug: string; binary: string; version: string }[] = + harnessPins.map(([slug, binary, pin]) => { + const version = dockerfile.match( + new RegExp(`^ARG ${pin}=([^\\s]+)$`, 'm'), + )?.[1]; + if (!version) throw new Error(`Missing exact image pin ${pin}`); + return { slug, binary, version }; + }); + const nodeVersion = dockerfile.match( + /COPY --from=node:([\d.]+)-bookworm-slim/, + )?.[1]; + if (!nodeVersion) throw new Error('Missing exact Node image pin'); + probes.unshift({ slug: 'node', binary: 'node', version: nodeVersion }); + const probeScript = String.raw` +import json, os, re, signal, subprocess, sys, time + +failures = 0 +for probe in json.loads(sys.argv[1]): + home = '/workspace/' + probe['slug'] + os.mkdir(home) + env = dict(os.environ, HOME=home, XDG_CACHE_HOME=home + '/.cache', + XDG_CONFIG_HOME=home + '/.config', XDG_DATA_HOME=home + '/.local/share') + started = time.monotonic() + proc = subprocess.Popen([probe['binary'], '--version'], cwd=home, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, start_new_session=True) + try: + output, _ = proc.communicate(timeout=60) + pattern = r'(?`, which the gateway forwards upstream as `X-Tale-Cache-Affinity`), keeping any header the harness already sends; a Claude model, an exec without an id and a bring-your-own credential send none | 🔶 backend | `lib/harnesses/exec-builder.test.ts`; whether a multi-replica balancer keeps the turn on one replica is a deployment check | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed harness turn that ends cleanly with nothing at all from its model (no text, no tool call, no output tokens: the empty 200 a serving cluster answers when it fails mid-prefill) settles failed with “The model returned an empty answer, so the agent did nothing this turn.”: an automation `agent` node as a retryable `harness_error`, a task run on the retryable `empty_turn` path with its conversation handle kept, and a resumed task start is not taken for a dead handle. A turn that only called tools (the operator question included) or only reported output tokens (a reasoning-only turn, for one) is not empty; Claude Code's turn totals come from its result | 🔶 backend | `backend/core/chat/external_turn_shared.test.ts`, `lib/harnesses/parsers/claude-stream-json.test.ts` (the pinned-CLI `empty-answer-turn`, `token-only-turn` and `thinking-only-turn` captures), `backend/core/automations/agent_host.empty_answer.test.ts`, `backend/core/tasks/agent_run_host.empty_answer.test.ts`; a live empty answer from a failing model server stays a deployment check | -| [projects](../suites/projects.md) | Runtime image carries every managed harness (Qwen Code included); Codex runs as its native binary, without the npm launcher's Node process as its parent for the whole run | ✅ automated | `tests/integration/container-sandbox-runtime-test.ts` (registry-driven: every `managed: true` harness's exec binary on the agent PATH; `codex` is the direct launcher and runs), `services/sandbox-runtime/daemon/src/tale-qwen-run.test.ts`, `tale-hermes-run.test.ts` (returned SDK failures end as errors; resume restores the stored conversation) | +| [projects](../suites/projects.md) | Runtime image carries every harness at its exact Dockerfile pin, with bounded offline startup from an empty home as a non-root user; Codex runs as its native binary, without the npm launcher's Node parent | ✅ automated | `tests/integration/container-sandbox-runtime-test.ts` (registry-complete exact version checks, per-harness 60-second deadline and timing, no network, read-only root, all capabilities dropped; managed exec binaries on PATH; direct native Codex launcher), `services/sandbox-runtime/daemon/src/tale-qwen-run.test.ts`, `tale-hermes-run.test.ts` (SDK diagnostics cannot corrupt NDJSON; tool delay disabled; returned failures; resumed conversation), `tale-openclaw-run.test.ts` (structured errors fail the execution even after CLI exit 0) | | [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A managed agent turn that never opens a browser never starts the Playwright MCP server (a Node process holding ~100 MB), whichever harness runs it: the launcher answers `initialize` — as the server would for every protocol version MCP has named, the server's latest for one it does not speak — `tools/list`, `ping`, and `prompts/list`, `resources/list` and `resources/templates/list` with the server's own `-32601 Method not found` while the recorded capabilities lack prompts or resources (Qwen Code asks every server for both at the start of every turn), from manifests the image build records for the platform's argument sets, with the server file it recorded them from; it starts the server on the first other request, replaying the client's start under an id of its own (a server that does not answer it within two minutes is ended, and the launcher exits with it), logs a started server that speaks another protocol version than the client was told, and passes every message through both ways (a server request and the client's answer included); unknown arguments or protocol versions, a server on PATH other than the recorded one (a session's own install), `PLAYWRIGHT_MCP_*` settings in the environment and `TALE_PLAYWRIGHT_MCP_EAGER=1` start the server at once; the platform's argument sets and the image's record are held equal | ✅ automated | `services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts` (a stand-in server: the build's manifest and its server file, the start answered without it, Qwen Code's discovery answered without it, a list the recorded capabilities advertise left to the server, the start replayed on the first tool call, a start that never answers ended at the deadline, the version check against what the client was told, a roots request round trip, an unknown version, `PLAYWRIGHT_MCP_*` settings, a session's own server and the eager switch, the exit status, the proxy flags), `tests/integration/container-sandbox-runtime-test.ts` (the image's own server, for every argument set: not running after `tools/list` and Qwen Code's discovery, the tool list and the prompt and resource list answers equal to the server's; a `browser_navigate` through the server started then), `lib/harnesses/exec-builder.test.ts` (the argument sets) | | [settings](../suites/settings.md) / [tasks](../suites/tasks.md) | An exec's leftover processes are ended: what its command backgrounded (`cmd &`, `nohup`, a descendant in a session of its own) gets SIGTERM, then SIGKILL, when the command exits — or, while another exec of the session still runs, when the session's last running exec ends — and at once on a cancel or at the deadline (what an exited exec left waiting included, and the group SIGKILL while the exec's own process runs even when no process there shows the tag); leftovers that wait keep their output pipes; the exit is reported without waiting out the drain grace; each process is signalled once (the group as a whole, on its own only a tagged process that left it), and a group whose tagged processes all left is never signalled later; a dropped attach releases its subscriber and its active operation; a session stop passes SIGTERM on to every live exec and to what exited execs left waiting; a group known to be the exec's gets its signal before the process table is read, a scan answers with what it read after two seconds and skips a process whose read never came back, and runnerd ends itself by SIGKILL while such a read is out; a leftover that stayed in the exec's group without the tag is still reached through the group's recorded processes (pid and start time) once it waited, and by the SIGKILL after an exec that ended alone; a steer's restart cancels the old exec as a rotation (`?leftovers=keep`, passed on by the spawner): only its own group ends, what it left outside is held until an exec started after it ends (a later cancel of the old exec leaves it held; with no successor within ten minutes the hold lifts), and a Stop or a crash still ends everything; a cancelled Gemini, Qwen or Pi turn removes its staged settings and context file, and a second signal does not cut that cleanup short; every exec runs under the subreaper shim (`tale-exec-shim`), so a process that left the exec's group and session and replaced its environment is still found below it and ended, and a round whose every exec still has its shim reads `stat` alone; the shim's status pipe gives the command's group, its exit status (128 + N for signal N) or why it could not run, the shim's own exit standing in only when the pipe ended without one; a cancel that comes before the shim named the group signals the group once it does; a refused subreaper is logged once and the exec falls back to group and tag | ✅ automated | `services/sandbox-runtime/daemon/src/exec-manager.test.ts` (exec tag in the environment, background child ended at exit and on cancel, one SIGTERM per cancel, an untagged leader still SIGKILLed, leftovers kept while another exec runs and keeping their pipes, a cancel during the drain, the daemon's stop of live and waiting execs, the leftover prune, a `setsid` descendant found by its tag on Linux, a dropped consumer settles its attach), `process-reaper.test.ts` (tag and process-group match, one signal per process, no stale group, one scan per round, init and runnerd never, a known group signalled before a hanging read, the scan deadline and the skipped stalled read, the stat-only group record, a recorded member's proof and a reused pid's none, a shim's descendants whatever their group, session or tag, a stat-only scan while every shim runs, the tag again once a shim has exited, an unreadable environment still walked through), `exec-shim.test.ts` (on Linux the shim built from its source: output and exit status, 128 + N for a signal, a spawn error, a `setsid env -i` escapee ended with its exec, while another exec runs and after a rotation, and out of reach without the shim, a cancel before the group is named; everywhere, stand-in shims for the status pipe: its exit over the shim's, a killed shim, a spawn error, a refused subreaper said once), `tests/integration/container-sandbox-runtime-test.ts` (the image's runnerd names its shim and ends an escapee), `daemon-exit.test.ts` (the SIGKILL exit while a read is out, under Node), `main.test.ts` (`?leftovers=keep` over HTTP on Linux), `harness-wrapper-cancel.test.ts` (each wrapper's staged files removed after one and after two signals); the rotation in `exec-manager.test.ts` (the group ended, the held server ended once the next exec ends, a hold outlasting an earlier exec and a late cancel, a `setsid` server on Linux) and the untagged in-group leftover after a deferral and after an exec that ended alone (Linux); `services/sandbox/src/server.test.ts` + `services/sandbox/src/session/session-routes.test.ts` (the flag reaches runnerd); `backend/core/node_only/sandbox/helpers/session_client.test.ts` (the query) and `backend/core/tasks/agent_run_host.reap.test.ts` (the restart lane rotates, a Stop and a crash cancel in full) | -| [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A Gemini CLI agent on a model whose id ends in "flash" (`deepseek-flash`, `glm-5.3-flash`, `qwen3.6-flash`, OpenRouter `google/gemini-3.5-flash`, …) requests that model, not the CLI's own gemini-3.5-flash | ✅ automated | `lib/harnesses/exec-builder.test.ts` (the gemini exec carries `experimental.dynamicModelConfiguration` on both lanes and passes `--model` verbatim), `lib/harnesses/golden-exec.test.ts`, `tests/integration/container-sandbox-runtime-test.ts` (the pinned CLI through `tale-gemini-run` against a loopback gateway stand-in keeps a flash-suffixed id in the request path; the control run without the setting still shows the rewrite) | +| [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A Gemini CLI agent on a model whose id ends in "flash" (`deepseek-flash`, `glm-5.3-flash`, `qwen3.6-flash`, OpenRouter `google/gemini-3.5-flash`, …) requests that model, not the CLI's own gemini-3.5-flash | ✅ automated | `lib/harnesses/exec-builder.test.ts` (the gemini exec carries `experimental.dynamicModelConfiguration` on both lanes and passes `--model` verbatim), `lib/harnesses/golden-exec.test.ts`, `tests/integration/container-sandbox-runtime-test.ts` (the pinned CLI through `tale-gemini-run` against a loopback gateway stand-in keeps a flash-suffixed id in the request path; immutable system policy survives conflicting repository settings and its files and ancestors are root-owned and not writable by the agent) | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | `TASK-F35` (the image half): runnerd links every built-in skill baked into the runtime image into each harness's native user-level skill directory (`.claude/skills`, `.agents/skills`, `.hermes/skills`), keeping a directory or live link of someone's own; before every exec it withdraws the link beside a same-named skill the workspace repository ships in `.claude/skills` or `.agents/skills`, and restores it once the repository drops it. Every managed harness names `visual-aspect-analyzer` in its first model request, and with a repository copy in both directories lists that copy (Hermes, which reads no project skills, keeps the baked one) | 🔶 image + stub model | `services/sandbox-runtime/daemon/src/baked-skills.test.ts`, `exec-manager.test.ts` (the reconcile runs before each spawn), `tests/integration/container-sandbox-runtime-test.ts` (every registry harness has a directory; each managed harness's golden exec through runnerd against a request-recording stub; links withdrawn and restored); a live model reading and running the skill stays `TASK-F35` | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | OpenCode tool calls remain visible with their name, input and result when the CLI emits only a completed tool part; a running phase followed by completion renders one call, and a failed call retains its error text | ✅ automated | `lib/harnesses/parsers/opencode-jsonl.test.ts` (`completed-tool-turn` and failed-read shape captured from a real CLI against an isolated synthetic gateway; chunked parsing and the running/completed fixture) | | [settings](../suites/settings.md) | A harness subscription badge is usable only when the harness accepts bring-your-own credentials and declares a subscription delivery channel; every managed harness is checked against the shipped facts | ✅ automated | `backend/core/lib/providers/harness_status.test.ts`; the runtime enforces the same delivery requirement in `backend/core/lib/providers/agent_serving.test.ts` | diff --git a/services/platform/turbo.json b/services/platform/turbo.json index f4f0655cec..38eb7b29c8 100644 --- a/services/platform/turbo.json +++ b/services/platform/turbo.json @@ -24,6 +24,7 @@ "$TURBO_ROOT$/services/db/migrations/knowledge-db/**", "$TURBO_ROOT$/services/sandbox-llm-gateway/docker-entrypoint.sh", "$TURBO_ROOT$/services/sandbox-runtime/Dockerfile", + "$TURBO_ROOT$/services/sandbox-runtime/build-gemini-settings.ts", "$TURBO_ROOT$/services/sandbox-runtime/daemon/src/file-ops.ts", "$TURBO_ROOT$/services/sandbox-runtime/daemon/src/protocol.ts", "$TURBO_ROOT$/services/sandbox-runtime/playwright-mcp-args.json", diff --git a/services/sandbox-runtime/Dockerfile b/services/sandbox-runtime/Dockerfile index f4f507f784..695c4ee0fc 100644 --- a/services/sandbox-runtime/Dockerfile +++ b/services/sandbox-runtime/Dockerfile @@ -23,6 +23,15 @@ WORKDIR /build COPY services/sandbox-runtime/daemon/ ./ RUN bun build --target=node src/main.ts --outfile /runnerd.mjs +# Gemini's system settings must be immutable and root-owned. Derive them +# from the platform's existing harness interpreter, without a package install. +FROM oven/bun:1 AS gemini-settings-build +WORKDIR /build +COPY services/platform/lib/harnesses/ services/platform/lib/harnesses/ +COPY configs/platform/system/harnesses/gemini/harness.yml configs/platform/system/harnesses/gemini/harness.yml +COPY services/sandbox-runtime/build-gemini-settings.ts services/sandbox-runtime/build-gemini-settings.ts +RUN bun services/sandbox-runtime/build-gemini-settings.ts /gemini-settings + # --- exec shim build stage: the subreaper runnerd runs every exec under ----- # Everything an exec starts stays the shim's descendant, so runnerd ends what # the exec left even after it moved to a session of its own and dropped the @@ -42,22 +51,21 @@ FROM python:3.12-slim-bookworm # 2.x required: the claude_code adapter passes --include-partial-messages, # which 1.0.x rejects (exit 1 before the agent even starts). 2.1.280 is the # first release that knows Claude Opus 5.5 (2.1.257: Claude Fable 5.1). -ARG CLAUDE_CODE_VERSION=2.1.283 -ARG OPENCODE_VERSION=1.17.3 -ARG CURSOR_AGENT_VERSION=2026.03.20-44cb435 -ARG HERMES_AGENT_VERSION=0.18.0 -# 0.59.0 is the last release tale-gemini-run can drive unchanged: from -# 0.60.0 the CLI refuses a system settings file (and every ancestor -# directory) that is not root-owned and free of group/other write, while -# the wrapper stages that file per exec as `agent` under a temp dir. A bump -# needs root-owned staging first. The harness YAML also keeps +ARG CLAUDE_CODE_VERSION=2.1.285 +ARG OPENCODE_VERSION=1.18.34 +ARG CURSOR_AGENT_VERSION=2026.10.01-e373342 +ARG HERMES_AGENT_VERSION=0.19.0 +# Since 0.60.0 the CLI requires root-owned system settings and ancestors. +# The build stage derives immutable policy files; the non-root wrapper +# selects one by its settings hash and supplies only per-exec string values +# through env expansion. The harness YAML keeps # `capabilities.resume: false` until a release carries the resume fix # (google-gemini/gemini-cli#29365). -ARG GEMINI_CLI_VERSION=0.59.0 -ARG CODEX_VERSION=0.142.5 -ARG PI_CODING_AGENT_VERSION=0.80.3 -ARG OPENCLAW_VERSION=2026.6.11 -ARG QWEN_CODE_VERSION=0.23.3 +ARG GEMINI_CLI_VERSION=0.62.0 +ARG CODEX_VERSION=0.160.0 +ARG PI_CODING_AGENT_VERSION=1.0.1 +ARG OPENCLAW_VERSION=2026.9.8 +ARG QWEN_CODE_VERSION=0.24.7 ARG PLAYWRIGHT_MCP_VERSION=0.0.41 ARG GH_VERSION=2.62.0 ARG PILLOW_VERSION=12.3.0 @@ -159,8 +167,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ # uv — fast Python package installer/resolver. See https://github.com/astral-sh/uv COPY --from=ghcr.io/astral-sh/uv:0.5 /uv /usr/local/bin/uv -# Node 24 LTS. Copy /usr/local from node:24-bookworm-slim into /opt/node. -COPY --from=node:24-bookworm-slim /usr/local /opt/node +# Node 24 LTS. OpenClaw requires at least 24.16.0; pin the verified LTS patch +# so a cached floating image cannot silently leave the upgraded CLI unusable. +COPY --from=node:24.21.0-bookworm-slim /usr/local /opt/node # bun — many JS/TS projects (Tale included) use it for install/test/scripts, so # an in-sandbox coding agent needs it on PATH. Reuse the daemon-build stage's @@ -357,6 +366,7 @@ RUN npm install -g --prefix /opt/agents "@google/gemini-cli@${GEMINI_CLI_VERSION && npm cache clean --force \ && gemini --version COPY services/sandbox-runtime/tale-gemini-run /usr/local/bin/tale-gemini-run +COPY --from=gemini-settings-build /gemini-settings/ /usr/local/share/tale/gemini-settings/ RUN chmod +x /usr/local/bin/tale-gemini-run # OpenAI Codex CLI (pinned npm). Driven headlessly by the platform's codex diff --git a/services/sandbox-runtime/Dockerfile.dockerignore b/services/sandbox-runtime/Dockerfile.dockerignore index d4aeddd49f..17223bbee9 100644 --- a/services/sandbox-runtime/Dockerfile.dockerignore +++ b/services/sandbox-runtime/Dockerfile.dockerignore @@ -119,6 +119,20 @@ compose.*.yml services/db/ services/docs/ services/platform/ +# Only the pure harness interpreter and its runtime imports feed the Gemini +# policy build stage. No platform app, tests, server or dependencies are copied. +!services/platform/ +services/platform/* +!services/platform/lib/ +services/platform/lib/* +!services/platform/lib/harnesses/ +services/platform/lib/harnesses/* +!services/platform/lib/harnesses/exec-builder.ts +!services/platform/lib/harnesses/types.ts +!services/platform/lib/harnesses/jsonl.ts +!services/platform/lib/harnesses/parsers/ +services/platform/lib/harnesses/parsers/* +!services/platform/lib/harnesses/parsers/claude-stream-json.ts services/proxy/ services/sandbox/ services/sandbox-egress/ diff --git a/services/sandbox-runtime/README.md b/services/sandbox-runtime/README.md index 9c0def00c3..459fad5e22 100644 --- a/services/sandbox-runtime/README.md +++ b/services/sandbox-runtime/README.md @@ -146,6 +146,50 @@ rationale. docker build -f services/sandbox-runtime/Dockerfile . ``` +### Harness upgrades + +The Dockerfile pins every bundled harness and the Node patch version. Refresh +the complete set together after checking each upstream's supported release +channel and runtime requirements. Claude uses its `stable` channel; Hermes uses +the PyPI distribution, whose version can differ from the GitHub release. Keep +installs at image build time so a new agent never downloads or updates its CLI +during startup. An image update does not add models to the platform catalog; +deploy the matching platform release before selecting newly supported models. + +Run the wrapper regression tests and the real image conformance suite before +shipping a refresh: + +```bash +bun run --filter @tale/sandbox-runtime-daemon test +bun run docker:test:sandbox-runtime +``` + +To test a previously built image, set `IMAGE=` and `SKIP_BUILD=true` on +the second command. The image suite checks every registry harness against its +exact Dockerfile pin, from separate empty homes with networking disabled, a +read-only root and all capabilities dropped. Each version probe has a +60-second cold-start deadline and reports its elapsed time. It also exercises +the real wrapper flags and SDK signatures, managed executions against a stub +model, baked skills, process cleanup, and lazy browser startup. These checks +need no provider credentials; live subscription authentication still requires +verification after rollout. CI runs the image conformance gate on amd64. + +Hermes keeps SDK diagnostics on stderr so stdout remains NDJSON and disables +the SDK's artificial delay between tool calls. Provider retry and backoff stay +enabled. OpenClaw's wrapper treats a structured error as a failed execution +even when the CLI itself exits successfully. + +Gemini requires its system settings and every ancestor directory to be owned +by root and not writable by group or others. The image generates immutable +policy files from the platform's existing harness interpreter; the wrapper +selects the file matching the incoming settings and supplies only the bridge +URL and a unique context filename through environment substitution. Repository +settings cannot override that system policy. A platform/image policy mismatch +fails before the CLI starts and asks for a runtime update. Agent execution +remains non-root, and cancellation removes the private per-execution context +file. Keep the harness catalog and runtime image aligned when changing Gemini +settings. + ### Built-in skills The image bakes Tale's built-in skills under `/opt/agents/skills/` — today diff --git a/services/sandbox-runtime/build-gemini-settings.ts b/services/sandbox-runtime/build-gemini-settings.ts new file mode 100644 index 0000000000..180d235008 --- /dev/null +++ b/services/sandbox-runtime/build-gemini-settings.ts @@ -0,0 +1,98 @@ +// Gemini 0.60+ accepts only root-owned system settings. Bake the finite +// settings shapes emitted by our existing interpreter into the image; the +// wrapper selects their content hash, so an old image never silently drops a +// new policy. Only the bridge URL and context filename vary per execution. +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +import type { HarnessDefinition } from '@tale/shared/schemas/providers'; + +import { buildHarnessExec } from '../platform/lib/harnesses/exec-builder'; +import type { HarnessCredential } from '../platform/lib/harnesses/types'; + +export const GEMINI_BRIDGE_URL = '${TALE_GEMINI_BRIDGE_URL}'; +export const GEMINI_CONTEXT_FILE = '${TALE_GEMINI_CONTEXT_FILE}'; + +function sortedJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(sortedJson).join(',')}]`; + if (value !== null && typeof value === 'object') { + return `{${Object.entries(value) + .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) + .map(([key, child]) => `${JSON.stringify(key)}:${sortedJson(child)}`) + .join(',')}}`; + } + return JSON.stringify(value); +} + +export function geminiPolicies(fact: HarnessDefinition) { + const policies = new Map>(); + for (const managed of [false, true]) { + const credential: HarnessCredential = managed + ? { + mode: 'managed', + gateway: { + baseUrl: 'http://build.invalid', + token: 'build-placeholder', + streamIdleTimeoutMs: 600_000, + requestTimeoutMs: 600_000, + }, + } + : { mode: 'byo', env: {} }; + for (const browser of [false, true]) { + for (const bridge of managed ? [false, true] : [false]) { + const exec = buildHarnessExec(fact, { + workdir: '/agent/workspace', + prompt: 'Build Gemini settings', + credential, + mcp: { + ...(browser ? { browser: 'headless' as const } : {}), + ...(bridge ? { bridgeUrl: GEMINI_BRIDGE_URL } : {}), + }, + }); + const payload: unknown = JSON.parse(exec.stdin ?? '{}'); + if ( + payload === null || + typeof payload !== 'object' || + !('settings' in payload) || + payload.settings === null || + typeof payload.settings !== 'object' || + Array.isArray(payload.settings) + ) { + throw new Error('Gemini harness must emit a settings object'); + } + const settings = payload.settings; + const hash = createHash('sha256') + .update(sortedJson(settings)) + .digest('hex'); + policies.set(`${hash}.json`, { + ...settings, + context: { fileName: ['GEMINI.md', GEMINI_CONTEXT_FILE] }, + }); + } + } + } + return policies; +} + +if (import.meta.main) { + const destination = process.argv[2]; + if (!destination) throw new Error('Pass the policy output directory'); + // This is the repository's trusted source file. The catalog/schema and + // golden exec tests validate it; no dependency install is needed at build. + const fact = Bun.YAML.parse( + readFileSync( + resolve( + import.meta.dir, + '../../configs/platform/system/harnesses/gemini/harness.yml', + ), + 'utf8', + ), + ) as HarnessDefinition; + mkdirSync(destination, { recursive: true, mode: 0o755 }); + for (const [name, policy] of geminiPolicies(fact)) { + writeFileSync(join(destination, name), `${JSON.stringify(policy)}\n`, { + mode: 0o644, + }); + } +} diff --git a/services/sandbox-runtime/daemon/src/gemini-settings-test-helper.ts b/services/sandbox-runtime/daemon/src/gemini-settings-test-helper.ts new file mode 100644 index 0000000000..b6de217bcf --- /dev/null +++ b/services/sandbox-runtime/daemon/src/gemini-settings-test-helper.ts @@ -0,0 +1,55 @@ +import { spawnSync } from 'node:child_process'; +import { copyFileSync, mkdirSync, readFileSync, readdirSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +export function geminiPayload( + prefix: string, + options: { + managed?: boolean; + browser?: boolean; + bridgeUrl?: string; + prompt?: string; + instructions?: string | null; + } = {}, +): string { + const dir = join(prefix, 'share/tale/gemini-settings'); + for (const name of readdirSync(dir)) { + const settings = JSON.parse(readFileSync(join(dir, name), 'utf8')); + if ( + Boolean(settings.security) !== (options.managed ?? false) || + Boolean(settings.mcpServers?.playwright) !== (options.browser ?? false) || + Boolean(settings.mcpServers?.connectors) !== Boolean(options.bridgeUrl) + ) + continue; + delete settings.context; + if (options.bridgeUrl) + settings.mcpServers.connectors.env.TALE_CONNECTORS_URL = + options.bridgeUrl; + return JSON.stringify({ + prompt: options.prompt ?? 'p', + system_prompt: + options.instructions === undefined ? 'be brief' : options.instructions, + settings, + }); + } + throw new Error('Missing generated Gemini policy'); +} + +/** Install the wrapper and run the real image policy generator into a test + * prefix. The image test owns root ownership/CLI precedence. A subprocess + * also keeps the platform's types out of the daemon's stricter type project. */ +export function installGeminiWrapper(prefix: string): string { + const bin = join(prefix, 'bin'); + const policies = join(prefix, 'share/tale/gemini-settings'); + mkdirSync(bin, { recursive: true }); + const wrapper = join(bin, 'tale-gemini-run'); + copyFileSync(resolve(import.meta.dir, '../../tale-gemini-run'), wrapper); + const built = spawnSync( + process.execPath, + [resolve(import.meta.dir, '../../build-gemini-settings.ts'), policies], + { encoding: 'utf8' }, + ); + if (built.status !== 0) + throw new Error(`Gemini policy build failed: ${built.stderr}`); + return wrapper; +} diff --git a/services/sandbox-runtime/daemon/src/gemini-settings.test.ts b/services/sandbox-runtime/daemon/src/gemini-settings.test.ts new file mode 100644 index 0000000000..b106828889 --- /dev/null +++ b/services/sandbox-runtime/daemon/src/gemini-settings.test.ts @@ -0,0 +1,150 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { + geminiPayload, + installGeminiWrapper, +} from './gemini-settings-test-helper'; + +const pyTest = spawnSync('python3', ['-V']).status === 0 ? test : test.skip; +let root: string; +let wrapper: string; + +const FAKE_CLI = `#!/usr/bin/env python3 +import json, os, pathlib, stat, sys +p = pathlib.Path(os.environ["GEMINI_CLI_SYSTEM_SETTINGS_PATH"]) +context = pathlib.Path(os.environ["HOME"]) / ".gemini" / os.environ["TALE_GEMINI_CONTEXT_FILE"] +print(json.dumps({"settings": json.loads(p.read_text()), "path": str(p), "prompt": sys.stdin.read(), "argv": sys.argv[1:], "bridge": os.environ.get("TALE_GEMINI_BRIDGE_URL"), "context": context.read_text() if context.exists() else None, "mode": stat.S_IMODE(context.stat().st_mode) if context.exists() else None})) +sys.exit(int(os.environ.get("FAKE_EXIT", "0"))) +`; + +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), 'tale-gemini-settings-'))); + for (const dir of ['workspace', 'home']) mkdirSync(join(root, dir)); + wrapper = installGeminiWrapper(root); + writeFileSync(join(root, 'bin/gemini'), FAKE_CLI); + chmodSync(join(root, 'bin/gemini'), 0o755); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +function run(payload: string, exit = '0') { + return spawnSync('python3', [wrapper, '--workdir', join(root, 'workspace')], { + input: payload, + encoding: 'utf8', + env: { + ...process.env, + PATH: `${join(root, 'bin')}:${process.env.PATH ?? ''}`, + HOME: join(root, 'home'), + FAKE_EXIT: exit, + }, + }); +} + +describe('Gemini immutable system settings', () => { + test('derives six distinct policy shapes from the existing harness interpreter', () => { + const dir = join(root, 'share/tale/gemini-settings'); + expect(readdirSync(dir).length).toBe(6); + for (const name of readdirSync(dir)) { + const policy = JSON.parse(readFileSync(join(dir, name), 'utf8')); + expect(name).toMatch(/^[a-f\d]{64}\.json$/); + expect(policy).toMatchObject({ + model: { maxSessionTurns: 200 }, + context: { fileName: ['GEMINI.md', '${TALE_GEMINI_CONTEXT_FILE}'] }, + }); + } + }); + + pyTest( + 'keeps managed policy immutable while passing only per-exec strings through env', + () => { + const bridge = 'https://platform.invalid/bridge?q="ü"'; + const result = run( + geminiPayload(root, { + prompt: '-private prompt', + instructions: 'private instructions', + managed: true, + browser: true, + bridgeUrl: bridge, + }), + ); + expect(result.status).toBe(0); + expect(result.stderr).toBe(''); + const observed = JSON.parse(result.stdout); + expect(observed).toMatchObject({ + prompt: '-private prompt', + context: 'private instructions', + mode: 0o600, + bridge, + settings: { + security: { auth: { selectedType: 'gemini-api-key' } }, + tools: { exclude: ['google_web_search', 'web_fetch'] }, + mcpServers: { + connectors: { + env: { + TALE_CONNECTORS_URL: '${TALE_GEMINI_BRIDGE_URL}', + TALE_CONNECTORS_TOKEN: '${TALE_GATEWAY_TOKEN}', + }, + }, + }, + }, + }); + expect(observed.path).toStartWith( + join(root, 'share/tale/gemini-settings/'), + ); + expect(observed.argv).not.toContain('-private prompt'); + expect(result.stdout).not.toContain('private-token'); + expect(readdirSync(join(root, 'home/.gemini'))).toEqual([]); + }, + ); + + pyTest('leaves BYO native tools and authentication inference intact', () => { + const result = run(geminiPayload(root, { instructions: null })); + expect(result.status).toBe(0); + const observed = JSON.parse(result.stdout); + expect(observed.settings).not.toHaveProperty('security'); + expect(observed.settings).not.toHaveProperty('tools'); + expect(observed.settings).not.toHaveProperty('mcpServers'); + expect(observed.context).toBeNull(); + }); + + pyTest.each([ + { model: { maxSessionTurns: -1 } }, + { tools: { exclude: [] } }, + { + mcpServers: { + connectors: { + command: 'untrusted', + env: { TALE_CONNECTORS_URL: 'https://wrong.invalid' }, + }, + }, + }, + ])('refuses policy drift before launching the CLI: %j', (override) => { + const payload = JSON.parse(geminiPayload(root)); + Object.assign(payload.settings, override); + const result = run(JSON.stringify(payload)); + expect(result.status).toBe(1); + expect(result.stdout).toContain('settings do not match this sandbox image'); + expect(result.stdout).not.toContain('"argv"'); + }); + + pyTest( + 'returns the CLI exit code and cleans private context after failure', + () => { + const result = run(geminiPayload(root), '53'); + expect(result.status).toBe(53); + expect(readdirSync(join(root, 'home/.gemini'))).toEqual([]); + }, + ); +}); diff --git a/services/sandbox-runtime/daemon/src/harness-wrapper-cancel.test.ts b/services/sandbox-runtime/daemon/src/harness-wrapper-cancel.test.ts index 49bb03c401..ee5ea329b7 100644 --- a/services/sandbox-runtime/daemon/src/harness-wrapper-cancel.test.ts +++ b/services/sandbox-runtime/daemon/src/harness-wrapper-cancel.test.ts @@ -1,4 +1,4 @@ -// The gemini, qwen and pi wrappers stage settings (and a context file) on +// The gemini, qwen and pi wrappers stage settings and/or a context file on // disk before their CLI starts, and must remove them however the exec ends — // runnerd ends a cancelled, timed-out or exited exec with a SIGTERM to its // process group, and Python's default SIGTERM runs no `finally`. A second @@ -20,6 +20,11 @@ import { import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; +import { + geminiPayload, + installGeminiWrapper, +} from './gemini-settings-test-helper'; + const hasPython = spawnSync('python3', ['-V']).status === 0; const pyTest = hasPython ? test : test.skip; @@ -55,13 +60,13 @@ async function cancelMidRun( writeFileSync(fake, FAKE_CLI); chmodSync(fake, 0o755); const startedPath = join(root, 'started'); + const wrapperPath = + wrapper.cli === 'gemini' + ? installGeminiWrapper(root) + : resolve(import.meta.dir, '../..', wrapper.name); const child = spawn( 'python3', - [ - resolve(import.meta.dir, '../..', wrapper.name), - '--workdir', - join(root, 'workspace'), - ], + [wrapperPath, '--workdir', join(root, 'workspace')], { detached: true, stdio: ['pipe', 'ignore', 'ignore'], @@ -74,7 +79,11 @@ async function cancelMidRun( }, }, ); - child.stdin?.end(JSON.stringify({ prompt: 'p', system_prompt: 'be brief' })); + child.stdin?.end( + wrapper.cli === 'gemini' + ? geminiPayload(root) + : JSON.stringify({ prompt: 'p', system_prompt: 'be brief' }), + ); const exited = new Promise((r) => child.on('exit', (code) => r(code)), ); @@ -84,7 +93,7 @@ async function cancelMidRun( } expect(existsSync(startedPath)).toBe(true); // Staged before the CLI started. - expect(readdirSync(join(root, 'tmp')).length).toBeGreaterThan(0); + expect(leftBehind(wrapper).length).toBeGreaterThan(0); const group = child.pid; if (group === undefined) throw new Error('the wrapper never started'); for (const signal of signals) process.kill(-group, signal); diff --git a/services/sandbox-runtime/daemon/src/tale-hermes-run.test.ts b/services/sandbox-runtime/daemon/src/tale-hermes-run.test.ts index c41d4a57cf..a85af872b1 100644 --- a/services/sandbox-runtime/daemon/src/tale-hermes-run.test.ts +++ b/services/sandbox-runtime/daemon/src/tale-hermes-run.test.ts @@ -29,12 +29,22 @@ const pyTest = hasPython ? test : test.skip; const FAKE_RUN_AGENT = ` import json, os +if os.environ.get("FAKE_SDK_NOISE"): + print("SDK import notice") + class AIAgent: def __init__(self, **kwargs): self.kwargs = kwargs self.session_id = kwargs.get("session_id") or "fresh-session" + if os.environ.get("FAKE_SDK_NOISE"): + print("SDK initialization notice") def run_conversation(self, user_message, conversation_history=None, **_kw): + if os.environ.get("FAKE_SDK_NOISE"): + print("SDK retry notice despite quiet mode") + self.kwargs["stream_delta_callback"]("streamed reply") + self.kwargs["tool_start_callback"]("call-1", "terminal", "pwd") + self.kwargs["tool_complete_callback"]("call-1", "terminal", "pwd", {}) plain = (str, int, float, bool, type(None)) record = { "ctor": { @@ -123,6 +133,31 @@ const runEnd = (events: RunOutcome['events']) => events.find((event) => event.type === 'run_end'); describe('tale-hermes-run result semantics', () => { + pyTest( + 'keeps SDK notices off the event stream while callbacks still emit', + () => { + const out = runWrapper( + { final_response: 'Done.', completed: true }, + { env: { FAKE_SDK_NOISE: '1' } }, + ); + + expect(out.code).toBe(0); + expect(out.stderr).toContain('SDK import notice'); + expect(out.stderr).toContain('SDK initialization notice'); + expect(out.stderr).toContain('SDK retry notice despite quiet mode'); + expect(out.events.map((event) => event.type)).toEqual([ + 'run_start', + 'text_delta', + 'tool_call_start', + 'tool_call_end', + 'session_id', + 'assistant_message', + 'run_end', + ]); + expect(out.seen?.ctor.tool_delay).toBe(0); + }, + ); + pyTest('ends a returned API failure as an error run', () => { const out = runWrapper({ final_response: 'HTTP 401: review synthetic unauthorized', diff --git a/services/sandbox-runtime/daemon/src/tale-openclaw-run.test.ts b/services/sandbox-runtime/daemon/src/tale-openclaw-run.test.ts index a012da0984..c0806e6c5a 100644 --- a/services/sandbox-runtime/daemon/src/tale-openclaw-run.test.ts +++ b/services/sandbox-runtime/daemon/src/tale-openclaw-run.test.ts @@ -39,6 +39,10 @@ else printf '' > "$FAKE_SEEN" fi if [ "$FAKE_MODE" = "hang" ]; then sleep 60; exit 0; fi +if [ "$FAKE_MODE" = "error" ]; then + printf '%s' '{"payloads":[],"meta":{"error":{"message":"Provider refused the turn"}}}' + exit 0 +fi printf '%s' '{"payloads":[{"text":"hi"}],"meta":{"durationMs":1,"agentMeta":{"sessionId":"s","model":"m","usage":{"input":1,"output":1}}}}' `; @@ -68,7 +72,10 @@ interface RunResult { stderr: string; } -function startWrapper(opts: { mode: 'ok' | 'hang'; systemPrompt?: string }) { +function startWrapper(opts: { + mode: 'ok' | 'hang' | 'error'; + systemPrompt?: string; +}) { const payload: Record = { prompt: 'hello', config: { agents: { defaults: { workspace } } }, @@ -144,6 +151,28 @@ function filesWithContent(dir: string, content: string): string[] { } describe('tale-openclaw-run AGENTS.md safety', () => { + pyTest( + 'a returned error fails the wrapper even when the CLI exits zero', + async () => { + writeFileSync(join(workspace, 'AGENTS.md'), ORIGINAL); + + const res = await startWrapper({ mode: 'error', systemPrompt: PROMPT_V1 }) + .done; + + expect(res.code).toBe(1); + expect(agentsMd()).toBe(ORIGINAL); + const events = res.stdout + .trim() + .split('\n') + .map((line) => JSON.parse(line)); + expect(events.at(-1)).toMatchObject({ + type: 'run_end', + status: 'error', + error: 'Provider refused the turn', + }); + }, + ); + pyTest( 'clean run: the CLI sees the system prompt, the user file comes back', async () => { diff --git a/services/sandbox-runtime/daemon/turbo.json b/services/sandbox-runtime/daemon/turbo.json index fb51027775..de7a07da98 100644 --- a/services/sandbox-runtime/daemon/turbo.json +++ b/services/sandbox-runtime/daemon/turbo.json @@ -6,6 +6,9 @@ "inputs": [ "$TURBO_EXTENDS$", "$TURBO_DEFAULT$", + "$TURBO_ROOT$/services/sandbox-runtime/build-gemini-settings.ts", + "$TURBO_ROOT$/services/platform/lib/harnesses/**", + "$TURBO_ROOT$/configs/platform/system/harnesses/gemini/harness.yml", "$TURBO_ROOT$/services/sandbox-runtime/entrypoint.sh", "$TURBO_ROOT$/services/sandbox-runtime/playwright-mcp-args.json", "$TURBO_ROOT$/services/sandbox-runtime/tale-*" diff --git a/services/sandbox-runtime/tale-gemini-run b/services/sandbox-runtime/tale-gemini-run index d7ae2d26e6..00f7c46349 100755 --- a/services/sandbox-runtime/tale-gemini-run +++ b/services/sandbox-runtime/tale-gemini-run @@ -1,17 +1,20 @@ #!/usr/bin/env python3 -"""Tale sandbox wrapper for Gemini CLI — stages per-exec config, then runs +"""Tale sandbox wrapper for Gemini CLI — selects system config, then runs `gemini --output-format stream-json` (NDJSON on stdout, passed through). -The platform adapter (gemini-cli/adapter.ts) sends ONE JSON object on stdin: - {"prompt": ..., "system_prompt"?: ..., "settings"?: {...}} -and gemini-cli/parse.ts normalizes the CLI's stream-json stdout into -AgentEvent[]. The wrapper exists because two inputs have no CLI flag and must -be ON DISK before the CLI starts (verified @google/gemini-cli 0.59.0): +The platform harness sends ONE JSON object on stdin: + {"prompt": ..., "system_prompt"?: ..., "settings": {...}} +and its stream parser normalizes the CLI's stdout into HarnessEvent[]. +Two inputs have no CLI flag and must be ON DISK before the CLI starts: - settings (auth-type pin, tools.exclude, mcpServers, maxSessionTurns) — - staged to a private per-exec file and pointed at via - GEMINI_CLI_SYSTEM_SETTINGS_PATH (system scope wins over any repo - .gemini/settings.json). + selected from immutable image files generated by build-gemini-settings.ts + from the SAME harness interpreter that builds stdin. Gemini 0.60+ requires + root-owned system settings and ancestors; a private agent-owned temp file + is silently ignored. Content-addressing fails closed on an incompatible + platform/image pair instead of dropping policy. Only string substitutions + (bridge URL and context filename) travel through per-exec environment. + System scope still wins over any repo .gemini/settings.json. - the system-prompt APPEND — staged as a per-exec context file under ~/.gemini/ and added to `context.fileName` alongside GEMINI.md, so it is appended to the model context without replacing the CLI's core system @@ -26,14 +29,50 @@ prompt would parse as a flag). from __future__ import annotations import argparse +import hashlib import json import os -import shutil import signal import subprocess import sys -import tempfile import uuid +from pathlib import Path + + +SETTINGS_DIR = Path(__file__).resolve().parent.parent / "share/tale/gemini-settings" +BRIDGE_URL_VAR = "${TALE_GEMINI_BRIDGE_URL}" + + +def select_settings(settings: dict, env: dict) -> str: + """Select only a policy baked from the platform's harness facts. A repo + cannot replace these root-owned files, and unknown settings fail before + Gemini launches. Never fall back to mutable user settings (lower priority + than a repository's settings).""" + normalized = json.loads(json.dumps(settings)) + servers = normalized.get("mcpServers") + if isinstance(servers, dict) and "connectors" in servers: + bridge = servers["connectors"] + bridge_env = bridge.get("env") if isinstance(bridge, dict) else None + url = ( + bridge_env.get("TALE_CONNECTORS_URL") + if isinstance(bridge_env, dict) + else None + ) + if not isinstance(url, str) or not url: + raise ValueError("connector settings must contain a bridge URL") + env["TALE_GEMINI_BRIDGE_URL"] = url + bridge_env["TALE_CONNECTORS_URL"] = BRIDGE_URL_VAR + fingerprint = hashlib.sha256( + json.dumps( + normalized, sort_keys=True, separators=(",", ":"), ensure_ascii=False + ).encode("utf-8") + ).hexdigest() + path = SETTINGS_DIR / f"{fingerprint}.json" + if not path.is_file(): + raise ValueError( + "Gemini settings do not match this sandbox image; update the runtime image" + ) + return str(path) def emit(event: dict) -> None: @@ -79,7 +118,7 @@ def main() -> int: payload = read_stdin_payload() if payload is None: return fail( - 'stdin must carry {"prompt": ..., "system_prompt"?: ..., "settings"?: ...} as JSON' + 'stdin must carry {"prompt": ..., "system_prompt"?: ..., "settings": {...}} as JSON' ) prompt = payload["prompt"] system_prompt = payload.get("system_prompt") @@ -87,38 +126,32 @@ def main() -> int: system_prompt = None settings = payload.get("settings") if not isinstance(settings, dict): - settings = {} + return fail("stdin settings must be an object") home = os.environ.get("HOME") or os.path.expanduser("~") gemini_dir = os.path.join(home, ".gemini") context_path = None - stage_dir = None try: + env = dict(os.environ) + env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = select_settings(settings, env) + # A unique nonexistent filename also keeps an exec without appended + # instructions from loading another exec's context. + context_name = f"tale-context-{uuid.uuid4().hex}.md" + env["TALE_GEMINI_CONTEXT_FILE"] = context_name if system_prompt is not None: # Per-exec context file: ~/.gemini/ is a global context path - # for every name in context.fileName (verified 0.59.0 + # for every name in context.fileName (verified 0.62.0 # memoryDiscovery). Keep GEMINI.md first so the working repo's own # context files still load. - os.makedirs(gemini_dir, exist_ok=True) - context_name = f"tale-context-{uuid.uuid4().hex}.md" + os.makedirs(gemini_dir, mode=0o700, exist_ok=True) context_path = os.path.join(gemini_dir, context_name) - with open(context_path, "w", encoding="utf-8") as f: + fd = os.open(context_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(system_prompt) - settings.setdefault("context", {}) - if isinstance(settings["context"], dict): - settings["context"]["fileName"] = ["GEMINI.md", context_name] - - stage_dir = tempfile.mkdtemp(prefix="tale-gemini-") - settings_path = os.path.join(stage_dir, "settings.json") - with open(settings_path, "w", encoding="utf-8") as f: - json.dump(settings, f) - - env = dict(os.environ) - env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = settings_path # --approval-mode yolo: fully autonomous — the container is the safety # boundary. --skip-trust: headless folder-trust gate would otherwise - # silently downgrade yolo to interactive approvals (verified 0.59.0). + # silently downgrade yolo to interactive approvals (verified 0.62.0). cmd = [ "gemini", "--output-format", @@ -163,15 +196,13 @@ def main() -> int: print( f"[tale-gemini-run] context cleanup failed: {exc}", file=sys.stderr ) - if stage_dir is not None: - shutil.rmtree(stage_dir, ignore_errors=True) class Cancelled(BaseException): """Raised when runnerd ends the exec (a process-group SIGTERM on cancel, at the exec's deadline or when it exits). Python's default SIGTERM - disposition runs no `finally`, which left the staged settings and the - per-exec context file behind; a BaseException unwinds through them and + disposition runs no `finally`, which left the per-exec context file + behind; a BaseException unwinds through its cleanup and past the generic `except Exception` in main().""" def __init__(self, signum: int) -> None: diff --git a/services/sandbox-runtime/tale-hermes-run b/services/sandbox-runtime/tale-hermes-run index e0fd6b2f23..e2a4befae4 100755 --- a/services/sandbox-runtime/tale-hermes-run +++ b/services/sandbox-runtime/tale-hermes-run @@ -7,7 +7,7 @@ hermes/parse.ts normalizes the stdout lines into AgentEvent[]. All human-oriented Hermes CLI output stays on stderr; stdout is JSONL only. Two SDK facts this wrapper exists to honour (verified on the pinned -hermes-agent 0.18.0): +hermes-agent 0.19.0): - `AIAgent.run_conversation` reports most failures by RETURNING, not raising: a nonretryable API error (401, exhausted retries), a blocked @@ -32,9 +32,14 @@ import re import sys import time import traceback +from contextlib import redirect_stdout from datetime import datetime, timezone from typing import Any +# SDK lifecycle notices can print even in quiet mode. Keep a dedicated event +# sink while all SDK/import/tool diagnostics use stderr instead of our JSONL. +EVENT_OUTPUT = sys.stdout + def _ts() -> str: return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") @@ -43,8 +48,8 @@ def _ts() -> str: def emit(event: dict[str, Any]) -> None: event.setdefault("schema_version", 1) event.setdefault("ts", _ts()) - sys.stdout.write(json.dumps(event, ensure_ascii=False) + "\n") - sys.stdout.flush() + EVENT_OUTPUT.write(json.dumps(event, ensure_ascii=False) + "\n") + EVENT_OUTPUT.flush() def warn(message: str) -> None: @@ -261,6 +266,9 @@ def main() -> int: agent = AIAgent( model=args.model or "", quiet_mode=True, + # The SDK defaults to a one-second pause between tool calls for + # human-readable CLI pacing; provider retry/backoff is separate. + tool_delay=0, max_iterations=args.max_turns, session_id=session_id, session_db=session_db, @@ -331,4 +339,5 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + with redirect_stdout(sys.stderr): + raise SystemExit(main()) diff --git a/services/sandbox-runtime/tale-openclaw-run b/services/sandbox-runtime/tale-openclaw-run index 750801849e..a2373f6e18 100755 --- a/services/sandbox-runtime/tale-openclaw-run +++ b/services/sandbox-runtime/tale-openclaw-run @@ -7,7 +7,7 @@ The platform adapter (openclaw/adapter.ts) sends ONE JSON object on stdin: and openclaw/parse.ts normalizes the stdout lines into AgentEvent[]. All human-oriented OpenClaw output stays on stderr; stdout is JSONL only. -The wrapper exists because (verified openclaw 2026.6.11): +The wrapper exists because (verified openclaw 2026.9.8): - the CLI has NO streaming output headlessly: `--json` reserves stdout for ONE final envelope ({payloads, meta:{durationMs, agentMeta:{sessionId, @@ -390,7 +390,7 @@ def emit_envelope_events( if error_message: run_end["error"] = error_message emit(run_end) - return exit_code if error_message else 0 + return (exit_code or 1) if error_message else 0 def install_cancel_handlers(swap: AgentsMdSwap) -> None: diff --git a/services/sandbox-runtime/tale-pi-run b/services/sandbox-runtime/tale-pi-run index 587e2a1f5d..e93bad5c1e 100755 --- a/services/sandbox-runtime/tale-pi-run +++ b/services/sandbox-runtime/tale-pi-run @@ -6,7 +6,7 @@ The platform adapter (pi/adapter.ts) sends ONE JSON object on stdin: {"prompt": ..., "system_prompt"?: ..., "models"?: {...}, "settings"?: {...}} and pi/parse.ts normalizes the CLI's JSON event stream into AgentEvent[]. The wrapper exists because three inputs have no safe CLI flag and must be ON DISK -before the CLI starts (verified @earendil-works/pi-coding-agent 0.80.3): +before the CLI starts (verified @earendil-works/pi-coding-agent 1.0.1): - models.json (managed gateway provider: baseUrl /openai/v1 + apiKey "$TALE_GATEWAY_TOKEN" env interpolation, so the file never holds diff --git a/services/sandbox-runtime/tale-qwen-run b/services/sandbox-runtime/tale-qwen-run index fe5d0be6a1..93105673ba 100755 --- a/services/sandbox-runtime/tale-qwen-run +++ b/services/sandbox-runtime/tale-qwen-run @@ -5,7 +5,7 @@ The platform adapter sends ONE JSON object on stdin: {"prompt": ..., "system_prompt"?: ..., "settings"?: {...}} Qwen Code is a gemini-cli fork, so this is tale-gemini-run's shape with the -fork's deltas (verified against @qwen-code/qwen-code 0.23.3): +fork's deltas (verified against @qwen-code/qwen-code 0.24.7): - settings (auth-type pin, tools.exclude, mcpServers, maxSessionTurns) — staged to a private per-exec file and pointed at via From ffcc3226ee24617b8d665c9e3bf5a0b7c1b3b1fb Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 3 Oct 2026 19:05:34 +0200 Subject: [PATCH 2/5] test(sandbox): verify native Codex tool execution --- .../container-sandbox-runtime-test.ts | 37 +--- .../tests/integration/lib/codex-round-trip.ts | 190 ++++++++++++++++++ .../tests/manual/reference/automation.md | 2 +- 3 files changed, 201 insertions(+), 28 deletions(-) create mode 100644 services/platform/tests/integration/lib/codex-round-trip.ts diff --git a/services/platform/tests/integration/container-sandbox-runtime-test.ts b/services/platform/tests/integration/container-sandbox-runtime-test.ts index 6dd8e81016..aa87370593 100644 --- a/services/platform/tests/integration/container-sandbox-runtime-test.ts +++ b/services/platform/tests/integration/container-sandbox-runtime-test.ts @@ -21,6 +21,7 @@ import { join } from 'node:path'; import { parse as parseYaml } from 'yaml'; +import { checkCodexRoundTrip } from './lib/codex-round-trip'; import { sleep } from './lib/docker'; import { capture, ok, projectRoot, stdoutOf, stream } from './lib/exec'; import { BOLD, GREEN, NC, RED } from './lib/log'; @@ -336,33 +337,15 @@ await assertOk( 10001, 'test -x /usr/local/bin/tale-qwen-run', ); -// The pinned Codex accepts the managed argv shape and gets as far as its -// own protocol: with its state root present it announces the thread before -// it ever reaches a model (the provider here is unreachable on purpose). -// Without the root it dies on stderr with "Error finding codex home", exit -// 1 and no JSON at all — what every managed Codex run hit while the -// entrypoint never created the directory (2026-09-26 evaluation, C-08). -await assertContains( - 'codex exec starts against its state root and speaks its protocol', - 10001, - '"type":"thread.started"', - // The managed argv of `lib/harnesses/fixtures/exec/codex.yml` (TOML values - // quoted, the prompt on stdin), pointed at a port nothing listens on. - [ - 'mkdir -p /workspace/.codex && cd /workspace && echo ping |', - 'CODEX_HOME=/workspace/.codex TALE_GATEWAY_TOKEN=unused codex exec', - '--json --skip-git-repo-check', - `-c 'approval_policy="never"' -c 'sandbox_mode="danger-full-access"'`, - `-c 'web_search="disabled"' -c 'model_provider="tale"'`, - `-c 'model_providers.tale.name="Tale Gateway"'`, - `-c 'model_providers.tale.base_url="http://127.0.0.1:9/openai/v1"'`, - `-c 'model_providers.tale.env_key="TALE_GATEWAY_TOKEN"'`, - `-c 'model_providers.tale.wire_api="responses"'`, - `-c 'model_providers.tale.request_max_retries=0'`, - `-c 'model_providers.tale.stream_max_retries=0'`, - '-m probe - 2>&1 || true', - ].join(' '), -); +// Exercise startup, native tool execution and completion against a bounded +// loopback Responses server. Codex now waits for network recovery on a refused +// connection, so an unreachable port cannot serve as a terminating probe. +try { + await checkCodexRoundTrip(IMAGE); + pass('codex completes a native tool round trip with parsed text and usage'); +} catch (error) { + fail(`codex native tool round trip: ${String(error)}`); +} // The entrypoint creates every harness state root a harness.yml points at // under HOME, or the harness refuses to start (Codex above). Registry and // entrypoint are pinned to each other here, in the lane that cannot run diff --git a/services/platform/tests/integration/lib/codex-round-trip.ts b/services/platform/tests/integration/lib/codex-round-trip.ts new file mode 100644 index 0000000000..3b40234314 --- /dev/null +++ b/services/platform/tests/integration/lib/codex-round-trip.ts @@ -0,0 +1,190 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { harnessDefinitionSchema } from '@tale/shared/schemas/providers'; +import { parse as parseYaml } from 'yaml'; + +import { buildHarnessExec } from '../../../lib/harnesses/exec-builder'; +import { createParser } from '../../../lib/harnesses/parsers/codex-jsonl'; +import { capture, projectRoot } from './exec'; + +// Codex 0.160.0 advertises native code-mode tools in input.additional_tools. +// Exercise that actual protocol, including the second request carrying the +// command's output; a first-request refusal cannot prove tool execution works. +const PROBE = String.raw` +import http.server, json, os, signal, subprocess, sys, threading, time + +spec = json.loads(sys.argv[1]) +requests, errors = [], [] +marker = 'CODEX_ROUND_TRIP_OK' +final_text = 'Codex synthetic tool round trip completed.' + +class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + try: + self.respond() + except Exception as error: + errors.append(str(error)) + self.send_error(400, 'Synthetic protocol assertion failed') + + def respond(self): + assert self.path == '/openai/v1/responses', self.path + body = json.loads(self.rfile.read(int(self.headers['Content-Length']))) + requests.append(body) + assert body['model'] == 'gpt-6.1-sol', body['model'] + assert len(requests) <= 2, 'unexpected model request' + if len(requests) == 1: + namespaces = [tool for item in body['input'] + if item.get('type') == 'additional_tools' + for tool in item.get('tools', [])] + assert any(ns.get('name') == 'functions' and + any(tool.get('name') == 'exec' and tool.get('type') == 'custom' + for tool in ns.get('tools', [])) for ns in namespaces), 'native exec tool missing' + source = 'text(await tools.exec_command(' + json.dumps({ + 'cmd': 'printf ' + marker, 'login': False, 'yield_time_ms': 1000, + }) + '));' + item = dict(type='custom_tool_call', id='tool_1', call_id='call_1', + namespace='functions', name='exec', input=source, status='completed') + events = [ + dict(type='response.output_item.added', output_index=0, + item=dict(item, input='', status='in_progress')), + dict(type='response.custom_tool_call_input.delta', item_id=item['id'], + output_index=0, delta=source), + dict(type='response.custom_tool_call_input.done', item_id=item['id'], + output_index=0, input=source), + ] + else: + assert any(item.get('type') == 'custom_tool_call_output' and + item.get('call_id') == 'call_1' and marker in json.dumps(item) + for item in body['input']), 'successful tool output not returned' + part = dict(type='output_text', text=final_text, annotations=[]) + item = dict(type='message', id='message_1', role='assistant', + content=[part], status='completed') + events = [ + dict(type='response.output_item.added', output_index=0, + item=dict(item, content=[], status='in_progress')), + dict(type='response.content_part.added', item_id=item['id'], output_index=0, + content_index=0, part=dict(part, text='')), + dict(type='response.output_text.delta', item_id=item['id'], output_index=0, + content_index=0, delta=final_text), + dict(type='response.output_text.done', item_id=item['id'], output_index=0, + content_index=0, text=final_text), + dict(type='response.content_part.done', item_id=item['id'], output_index=0, + content_index=0, part=part), + ] + response = dict(id='response_' + str(len(requests)), object='response', + created_at=int(time.time()), status='completed', model=body['model'], + output=[item], usage=dict(input_tokens=11, output_tokens=7, + total_tokens=18, input_tokens_details=dict(cached_tokens=0), + output_tokens_details=dict(reasoning_tokens=0))) + events.insert(0, dict(type='response.created', + response=dict(response, status='in_progress', output=[]))) + events.extend([ + dict(type='response.output_item.done', output_index=0, item=item), + dict(type='response.completed', response=response), + ]) + self.send_response(200) + self.send_header('Content-Type', 'text/event-stream') + self.end_headers() + for sequence, event in enumerate(events): + event.update(sequence_number=sequence, response_id=response['id']) + self.wfile.write(('event: ' + event['type'] + '\ndata: ' + + json.dumps(event) + '\n\n').encode()) + self.wfile.flush() + +server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) +threading.Thread(target=server.serve_forever, daemon=True).start() +argv = [arg.replace('http://127.0.0.1:0', 'http://127.0.0.1:' + str(server.server_port)) + for arg in spec['argv']] +env = dict(PATH=os.environ['PATH'], HOME='/agent/.runtime/home', + NO_PROXY='127.0.0.1', **spec['env']) +os.makedirs(env['CODEX_HOME']) +os.makedirs(spec['cwd']) +proc = subprocess.Popen(argv, cwd=spec['cwd'], env=env, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, start_new_session=True) +try: + stdout, stderr = proc.communicate(spec['stdin'], timeout=45) + sys.stdout.write(stdout) + sys.stderr.write(stderr) + assert proc.returncode == 0, f'Codex exited {proc.returncode}' + assert not errors, errors + assert len(requests) == 2, f'expected tool round trip, got {len(requests)} requests' +finally: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + proc.communicate(timeout=5) + server.shutdown() +`; + +/** Offline image proof: real native tool execution through the shipped exec + * builder and stream parser, bounded even if the CLI or server stalls. */ +export async function checkCodexRoundTrip(image: string): Promise { + const fact = harnessDefinitionSchema.parse( + parseYaml( + readFileSync( + join( + projectRoot(), + 'configs/platform/system/harnesses/codex/harness.yml', + ), + 'utf8', + ), + ), + ); + const exec = buildHarnessExec(fact, { + prompt: 'Follow the synthetic local response to complete this probe.', + model: 'gpt-6.1-sol', + credential: { + mode: 'managed', + gateway: { + baseUrl: 'http://127.0.0.1:0', + token: 'synthetic-probe-only', + streamIdleTimeoutMs: 5000, + requestTimeoutMs: 5000, + }, + }, + workdir: '/agent/workspace', + posture: 'act', + }); + const result = await capture([ + 'docker', + 'run', + '--rm', + '--network=none', + '--read-only', + '--cap-drop=ALL', + '--user=10001:10001', + '--tmpfs=/agent:uid=10001,gid=10001', + '--tmpfs=/tmp:mode=1777', + '--entrypoint=timeout', + image, + '60s', + 'python3', + '-c', + PROBE, + JSON.stringify(exec), + ]); + assert.equal(result.exitCode, 0, result.combined.slice(-4000)); + const parser = createParser('codex'); + const events = [...parser.feed(result.stdout), ...parser.end()]; + assert.ok(events.some((event) => event.type === 'turn-started')); + const call = events.find((event) => event.type === 'tool-use'); + assert.equal(call?.toolName, 'Bash'); + const output = events.find((event) => event.type === 'tool-result'); + assert.equal(output?.toolUseId, call?.toolUseId); + assert.equal(output?.isError, false); + assert.deepEqual(output?.output, { + output: 'CODEX_ROUND_TRIP_OK', + exitCode: 0, + }); + const end = events.find((event) => event.type === 'turn-ended'); + assert.equal(end?.status, 'completed'); + assert.equal(end?.finalText, 'Codex synthetic tool round trip completed.'); + assert.deepEqual(end?.usageTotals, { inputTokens: 22, outputTokens: 14 }); +} diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 4cd2d1fad2..1edbd8ccc9 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -189,7 +189,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A Claude Code agent turn on a model that is not Claude drops the CLI's per-request attribution line from its system prompt (`CLAUDE_CODE_ATTRIBUTION_HEADER=0`, beside the disabled thinking levers), so a local server's prefix cache carries the conversation from turn to turn; Claude models keep the line | 🔶 backend | `lib/harnesses/exec-builder.test.ts`, `lib/harnesses/golden-exec.test.ts` (the `managed-model-context-window` golden); the cached-token count per turn on a live local model stays a deployment check | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed Claude Code agent turn on a model that is not Claude names its exec in every request (`ANTHROPIC_CUSTOM_HEADERS: x-bf-eh-x-tale-cache-affinity: `, which the gateway forwards upstream as `X-Tale-Cache-Affinity`), keeping any header the harness already sends; a Claude model, an exec without an id and a bring-your-own credential send none | 🔶 backend | `lib/harnesses/exec-builder.test.ts`; whether a multi-replica balancer keeps the turn on one replica is a deployment check | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed harness turn that ends cleanly with nothing at all from its model (no text, no tool call, no output tokens: the empty 200 a serving cluster answers when it fails mid-prefill) settles failed with “The model returned an empty answer, so the agent did nothing this turn.”: an automation `agent` node as a retryable `harness_error`, a task run on the retryable `empty_turn` path with its conversation handle kept, and a resumed task start is not taken for a dead handle. A turn that only called tools (the operator question included) or only reported output tokens (a reasoning-only turn, for one) is not empty; Claude Code's turn totals come from its result | 🔶 backend | `backend/core/chat/external_turn_shared.test.ts`, `lib/harnesses/parsers/claude-stream-json.test.ts` (the pinned-CLI `empty-answer-turn`, `token-only-turn` and `thinking-only-turn` captures), `backend/core/automations/agent_host.empty_answer.test.ts`, `backend/core/tasks/agent_run_host.empty_answer.test.ts`; a live empty answer from a failing model server stays a deployment check | -| [projects](../suites/projects.md) | Runtime image carries every harness at its exact Dockerfile pin, with bounded offline startup from an empty home as a non-root user; Codex runs as its native binary, without the npm launcher's Node parent | ✅ automated | `tests/integration/container-sandbox-runtime-test.ts` (registry-complete exact version checks, per-harness 60-second deadline and timing, no network, read-only root, all capabilities dropped; managed exec binaries on PATH; direct native Codex launcher), `services/sandbox-runtime/daemon/src/tale-qwen-run.test.ts`, `tale-hermes-run.test.ts` (SDK diagnostics cannot corrupt NDJSON; tool delay disabled; returned failures; resumed conversation), `tale-openclaw-run.test.ts` (structured errors fail the execution even after CLI exit 0) | +| [projects](../suites/projects.md) | Runtime image carries every harness at its exact Dockerfile pin, with bounded offline startup from an empty home as a non-root user; Codex runs as its native binary, without the npm launcher's Node parent, and completes a native tool round trip whose tool result, final text and usage reach the platform parser | ✅ automated | `tests/integration/container-sandbox-runtime-test.ts` (registry-complete exact version checks, per-harness 60-second deadline and timing, no network, read-only root, all capabilities dropped; managed exec binaries on PATH; direct native Codex launcher), `tests/integration/lib/codex-round-trip.ts` (installed CLI and shipped exec builder against a loopback Responses stream; actual shell tool output returned to the next request; normalized successful completion; 60-second deadline), `services/sandbox-runtime/daemon/src/tale-qwen-run.test.ts`, `tale-hermes-run.test.ts` (SDK diagnostics cannot corrupt NDJSON; tool delay disabled; returned failures; resumed conversation), `tale-openclaw-run.test.ts` (structured errors fail the execution even after CLI exit 0) | | [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A managed agent turn that never opens a browser never starts the Playwright MCP server (a Node process holding ~100 MB), whichever harness runs it: the launcher answers `initialize` — as the server would for every protocol version MCP has named, the server's latest for one it does not speak — `tools/list`, `ping`, and `prompts/list`, `resources/list` and `resources/templates/list` with the server's own `-32601 Method not found` while the recorded capabilities lack prompts or resources (Qwen Code asks every server for both at the start of every turn), from manifests the image build records for the platform's argument sets, with the server file it recorded them from; it starts the server on the first other request, replaying the client's start under an id of its own (a server that does not answer it within two minutes is ended, and the launcher exits with it), logs a started server that speaks another protocol version than the client was told, and passes every message through both ways (a server request and the client's answer included); unknown arguments or protocol versions, a server on PATH other than the recorded one (a session's own install), `PLAYWRIGHT_MCP_*` settings in the environment and `TALE_PLAYWRIGHT_MCP_EAGER=1` start the server at once; the platform's argument sets and the image's record are held equal | ✅ automated | `services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts` (a stand-in server: the build's manifest and its server file, the start answered without it, Qwen Code's discovery answered without it, a list the recorded capabilities advertise left to the server, the start replayed on the first tool call, a start that never answers ended at the deadline, the version check against what the client was told, a roots request round trip, an unknown version, `PLAYWRIGHT_MCP_*` settings, a session's own server and the eager switch, the exit status, the proxy flags), `tests/integration/container-sandbox-runtime-test.ts` (the image's own server, for every argument set: not running after `tools/list` and Qwen Code's discovery, the tool list and the prompt and resource list answers equal to the server's; a `browser_navigate` through the server started then), `lib/harnesses/exec-builder.test.ts` (the argument sets) | | [settings](../suites/settings.md) / [tasks](../suites/tasks.md) | An exec's leftover processes are ended: what its command backgrounded (`cmd &`, `nohup`, a descendant in a session of its own) gets SIGTERM, then SIGKILL, when the command exits — or, while another exec of the session still runs, when the session's last running exec ends — and at once on a cancel or at the deadline (what an exited exec left waiting included, and the group SIGKILL while the exec's own process runs even when no process there shows the tag); leftovers that wait keep their output pipes; the exit is reported without waiting out the drain grace; each process is signalled once (the group as a whole, on its own only a tagged process that left it), and a group whose tagged processes all left is never signalled later; a dropped attach releases its subscriber and its active operation; a session stop passes SIGTERM on to every live exec and to what exited execs left waiting; a group known to be the exec's gets its signal before the process table is read, a scan answers with what it read after two seconds and skips a process whose read never came back, and runnerd ends itself by SIGKILL while such a read is out; a leftover that stayed in the exec's group without the tag is still reached through the group's recorded processes (pid and start time) once it waited, and by the SIGKILL after an exec that ended alone; a steer's restart cancels the old exec as a rotation (`?leftovers=keep`, passed on by the spawner): only its own group ends, what it left outside is held until an exec started after it ends (a later cancel of the old exec leaves it held; with no successor within ten minutes the hold lifts), and a Stop or a crash still ends everything; a cancelled Gemini, Qwen or Pi turn removes its staged settings and context file, and a second signal does not cut that cleanup short; every exec runs under the subreaper shim (`tale-exec-shim`), so a process that left the exec's group and session and replaced its environment is still found below it and ended, and a round whose every exec still has its shim reads `stat` alone; the shim's status pipe gives the command's group, its exit status (128 + N for signal N) or why it could not run, the shim's own exit standing in only when the pipe ended without one; a cancel that comes before the shim named the group signals the group once it does; a refused subreaper is logged once and the exec falls back to group and tag | ✅ automated | `services/sandbox-runtime/daemon/src/exec-manager.test.ts` (exec tag in the environment, background child ended at exit and on cancel, one SIGTERM per cancel, an untagged leader still SIGKILLed, leftovers kept while another exec runs and keeping their pipes, a cancel during the drain, the daemon's stop of live and waiting execs, the leftover prune, a `setsid` descendant found by its tag on Linux, a dropped consumer settles its attach), `process-reaper.test.ts` (tag and process-group match, one signal per process, no stale group, one scan per round, init and runnerd never, a known group signalled before a hanging read, the scan deadline and the skipped stalled read, the stat-only group record, a recorded member's proof and a reused pid's none, a shim's descendants whatever their group, session or tag, a stat-only scan while every shim runs, the tag again once a shim has exited, an unreadable environment still walked through), `exec-shim.test.ts` (on Linux the shim built from its source: output and exit status, 128 + N for a signal, a spawn error, a `setsid env -i` escapee ended with its exec, while another exec runs and after a rotation, and out of reach without the shim, a cancel before the group is named; everywhere, stand-in shims for the status pipe: its exit over the shim's, a killed shim, a spawn error, a refused subreaper said once), `tests/integration/container-sandbox-runtime-test.ts` (the image's runnerd names its shim and ends an escapee), `daemon-exit.test.ts` (the SIGKILL exit while a read is out, under Node), `main.test.ts` (`?leftovers=keep` over HTTP on Linux), `harness-wrapper-cancel.test.ts` (each wrapper's staged files removed after one and after two signals); the rotation in `exec-manager.test.ts` (the group ended, the held server ended once the next exec ends, a hold outlasting an earlier exec and a late cancel, a `setsid` server on Linux) and the untagged in-group leftover after a deferral and after an exec that ended alone (Linux); `services/sandbox/src/server.test.ts` + `services/sandbox/src/session/session-routes.test.ts` (the flag reaches runnerd); `backend/core/node_only/sandbox/helpers/session_client.test.ts` (the query) and `backend/core/tasks/agent_run_host.reap.test.ts` (the restart lane rotates, a Stop and a crash cancel in full) | | [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A Gemini CLI agent on a model whose id ends in "flash" (`deepseek-flash`, `glm-5.3-flash`, `qwen3.6-flash`, OpenRouter `google/gemini-3.5-flash`, …) requests that model, not the CLI's own gemini-3.5-flash | ✅ automated | `lib/harnesses/exec-builder.test.ts` (the gemini exec carries `experimental.dynamicModelConfiguration` on both lanes and passes `--model` verbatim), `lib/harnesses/golden-exec.test.ts`, `tests/integration/container-sandbox-runtime-test.ts` (the pinned CLI through `tale-gemini-run` against a loopback gateway stand-in keeps a flash-suffixed id in the request path; immutable system policy survives conflicting repository settings and its files and ancestors are root-owned and not writable by the agent) | From 2b35fd0b58dacdf3c18481e8567d2a1bafdd84ff Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 3 Oct 2026 21:03:10 +0200 Subject: [PATCH 3/5] fix(sandbox): keep build caches out of runtime images --- .../tests/integration/container-image-test.ts | 8 +++++-- .../container-sandbox-runtime-test.ts | 8 +++++++ .../tests/manual/reference/automation.md | 2 +- services/sandbox-runtime/Dockerfile | 23 +++++++++++++------ services/sandbox-runtime/README.md | 7 ++++++ 5 files changed, 38 insertions(+), 10 deletions(-) diff --git a/services/platform/tests/integration/container-image-test.ts b/services/platform/tests/integration/container-image-test.ts index 9bbd6d3444..53d0d417a1 100644 --- a/services/platform/tests/integration/container-image-test.ts +++ b/services/platform/tests/integration/container-image-test.ts @@ -62,8 +62,12 @@ const SIZE_BUDGETS: Record = { // markitdown's file-type model, reportlab, pdfplumber/pypdfium2) and the // Node lock ~130 MB (react-icons alone ~85 MB, docx, pptxgenjs, sharp), // taking amd64 from ~4.87 GB to an estimated ~5.3 GB. - // ~10% headroom over the ~5.3 GB amd64 image. - 'sandbox-runtime': 5900, + // - the October refresh of all nine harnesses: upstream bundles grew + // (OpenClaw ~730 MB, Codex ~380 MB, Pi ~160 MB). CI measured 6166 MB + // before keeping ~120 MB of Bun/node-gyp build caches out of layers. + // ~10% headroom over the refreshed ~6.0 GB amd64 image. Runtime binaries + // and diagnostics stay intact; the image is shared by concurrent sessions. + 'sandbox-runtime': 6600, }; const SERVICES = [ diff --git a/services/platform/tests/integration/container-sandbox-runtime-test.ts b/services/platform/tests/integration/container-sandbox-runtime-test.ts index aa87370593..d9a80322af 100644 --- a/services/platform/tests/integration/container-sandbox-runtime-test.ts +++ b/services/platform/tests/integration/container-sandbox-runtime-test.ts @@ -103,6 +103,14 @@ if (process.env.SKIP_BUILD !== 'true' && !process.env.IMAGE_PREBUILT) { } } +console.log(''); +console.log('--- build-only caches stay outside runtime layers ---'); +await assertOk( + 'Bun package and node-gyp header caches are not baked into the image', + 0, + `python3 -c 'from pathlib import Path; assert not any(p.is_file() for root in ("/root/.bun/install/cache", "/root/.cache/node-gyp") for p in Path(root).rglob("*"))'`, +); + console.log(''); console.log('--- default session profile (uid 65534) ---'); await assertContains('python3 present', 65534, 'Python 3', 'python3 --version'); diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 1edbd8ccc9..43d2c08e33 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -189,7 +189,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A Claude Code agent turn on a model that is not Claude drops the CLI's per-request attribution line from its system prompt (`CLAUDE_CODE_ATTRIBUTION_HEADER=0`, beside the disabled thinking levers), so a local server's prefix cache carries the conversation from turn to turn; Claude models keep the line | 🔶 backend | `lib/harnesses/exec-builder.test.ts`, `lib/harnesses/golden-exec.test.ts` (the `managed-model-context-window` golden); the cached-token count per turn on a live local model stays a deployment check | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed Claude Code agent turn on a model that is not Claude names its exec in every request (`ANTHROPIC_CUSTOM_HEADERS: x-bf-eh-x-tale-cache-affinity: `, which the gateway forwards upstream as `X-Tale-Cache-Affinity`), keeping any header the harness already sends; a Claude model, an exec without an id and a bring-your-own credential send none | 🔶 backend | `lib/harnesses/exec-builder.test.ts`; whether a multi-replica balancer keeps the turn on one replica is a deployment check | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed harness turn that ends cleanly with nothing at all from its model (no text, no tool call, no output tokens: the empty 200 a serving cluster answers when it fails mid-prefill) settles failed with “The model returned an empty answer, so the agent did nothing this turn.”: an automation `agent` node as a retryable `harness_error`, a task run on the retryable `empty_turn` path with its conversation handle kept, and a resumed task start is not taken for a dead handle. A turn that only called tools (the operator question included) or only reported output tokens (a reasoning-only turn, for one) is not empty; Claude Code's turn totals come from its result | 🔶 backend | `backend/core/chat/external_turn_shared.test.ts`, `lib/harnesses/parsers/claude-stream-json.test.ts` (the pinned-CLI `empty-answer-turn`, `token-only-turn` and `thinking-only-turn` captures), `backend/core/automations/agent_host.empty_answer.test.ts`, `backend/core/tasks/agent_run_host.empty_answer.test.ts`; a live empty answer from a failing model server stays a deployment check | -| [projects](../suites/projects.md) | Runtime image carries every harness at its exact Dockerfile pin, with bounded offline startup from an empty home as a non-root user; Codex runs as its native binary, without the npm launcher's Node parent, and completes a native tool round trip whose tool result, final text and usage reach the platform parser | ✅ automated | `tests/integration/container-sandbox-runtime-test.ts` (registry-complete exact version checks, per-harness 60-second deadline and timing, no network, read-only root, all capabilities dropped; managed exec binaries on PATH; direct native Codex launcher), `tests/integration/lib/codex-round-trip.ts` (installed CLI and shipped exec builder against a loopback Responses stream; actual shell tool output returned to the next request; normalized successful completion; 60-second deadline), `services/sandbox-runtime/daemon/src/tale-qwen-run.test.ts`, `tale-hermes-run.test.ts` (SDK diagnostics cannot corrupt NDJSON; tool delay disabled; returned failures; resumed conversation), `tale-openclaw-run.test.ts` (structured errors fail the execution even after CLI exit 0) | +| [projects](../suites/projects.md) | Runtime image carries every harness at its exact Dockerfile pin, with bounded offline startup from an empty home as a non-root user; Codex runs as its native binary, without the npm launcher's Node parent, and completes a native tool round trip whose tool result, final text and usage reach the platform parser | ✅ automated | `tests/integration/container-sandbox-runtime-test.ts` (Bun/node-gyp build caches absent, registry-complete exact version checks, per-harness 60-second deadline and timing, no network, read-only root, all capabilities dropped; managed exec binaries on PATH; direct native Codex launcher), `tests/integration/lib/codex-round-trip.ts` (installed CLI and shipped exec builder against a loopback Responses stream; actual shell tool output returned to the next request; normalized successful completion; 60-second deadline), `services/sandbox-runtime/daemon/src/tale-qwen-run.test.ts`, `tale-hermes-run.test.ts` (SDK diagnostics cannot corrupt NDJSON; tool delay disabled; returned failures; resumed conversation), `tale-openclaw-run.test.ts` (structured errors fail the execution even after CLI exit 0) | | [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A managed agent turn that never opens a browser never starts the Playwright MCP server (a Node process holding ~100 MB), whichever harness runs it: the launcher answers `initialize` — as the server would for every protocol version MCP has named, the server's latest for one it does not speak — `tools/list`, `ping`, and `prompts/list`, `resources/list` and `resources/templates/list` with the server's own `-32601 Method not found` while the recorded capabilities lack prompts or resources (Qwen Code asks every server for both at the start of every turn), from manifests the image build records for the platform's argument sets, with the server file it recorded them from; it starts the server on the first other request, replaying the client's start under an id of its own (a server that does not answer it within two minutes is ended, and the launcher exits with it), logs a started server that speaks another protocol version than the client was told, and passes every message through both ways (a server request and the client's answer included); unknown arguments or protocol versions, a server on PATH other than the recorded one (a session's own install), `PLAYWRIGHT_MCP_*` settings in the environment and `TALE_PLAYWRIGHT_MCP_EAGER=1` start the server at once; the platform's argument sets and the image's record are held equal | ✅ automated | `services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts` (a stand-in server: the build's manifest and its server file, the start answered without it, Qwen Code's discovery answered without it, a list the recorded capabilities advertise left to the server, the start replayed on the first tool call, a start that never answers ended at the deadline, the version check against what the client was told, a roots request round trip, an unknown version, `PLAYWRIGHT_MCP_*` settings, a session's own server and the eager switch, the exit status, the proxy flags), `tests/integration/container-sandbox-runtime-test.ts` (the image's own server, for every argument set: not running after `tools/list` and Qwen Code's discovery, the tool list and the prompt and resource list answers equal to the server's; a `browser_navigate` through the server started then), `lib/harnesses/exec-builder.test.ts` (the argument sets) | | [settings](../suites/settings.md) / [tasks](../suites/tasks.md) | An exec's leftover processes are ended: what its command backgrounded (`cmd &`, `nohup`, a descendant in a session of its own) gets SIGTERM, then SIGKILL, when the command exits — or, while another exec of the session still runs, when the session's last running exec ends — and at once on a cancel or at the deadline (what an exited exec left waiting included, and the group SIGKILL while the exec's own process runs even when no process there shows the tag); leftovers that wait keep their output pipes; the exit is reported without waiting out the drain grace; each process is signalled once (the group as a whole, on its own only a tagged process that left it), and a group whose tagged processes all left is never signalled later; a dropped attach releases its subscriber and its active operation; a session stop passes SIGTERM on to every live exec and to what exited execs left waiting; a group known to be the exec's gets its signal before the process table is read, a scan answers with what it read after two seconds and skips a process whose read never came back, and runnerd ends itself by SIGKILL while such a read is out; a leftover that stayed in the exec's group without the tag is still reached through the group's recorded processes (pid and start time) once it waited, and by the SIGKILL after an exec that ended alone; a steer's restart cancels the old exec as a rotation (`?leftovers=keep`, passed on by the spawner): only its own group ends, what it left outside is held until an exec started after it ends (a later cancel of the old exec leaves it held; with no successor within ten minutes the hold lifts), and a Stop or a crash still ends everything; a cancelled Gemini, Qwen or Pi turn removes its staged settings and context file, and a second signal does not cut that cleanup short; every exec runs under the subreaper shim (`tale-exec-shim`), so a process that left the exec's group and session and replaced its environment is still found below it and ended, and a round whose every exec still has its shim reads `stat` alone; the shim's status pipe gives the command's group, its exit status (128 + N for signal N) or why it could not run, the shim's own exit standing in only when the pipe ended without one; a cancel that comes before the shim named the group signals the group once it does; a refused subreaper is logged once and the exec falls back to group and tag | ✅ automated | `services/sandbox-runtime/daemon/src/exec-manager.test.ts` (exec tag in the environment, background child ended at exit and on cancel, one SIGTERM per cancel, an untagged leader still SIGKILLed, leftovers kept while another exec runs and keeping their pipes, a cancel during the drain, the daemon's stop of live and waiting execs, the leftover prune, a `setsid` descendant found by its tag on Linux, a dropped consumer settles its attach), `process-reaper.test.ts` (tag and process-group match, one signal per process, no stale group, one scan per round, init and runnerd never, a known group signalled before a hanging read, the scan deadline and the skipped stalled read, the stat-only group record, a recorded member's proof and a reused pid's none, a shim's descendants whatever their group, session or tag, a stat-only scan while every shim runs, the tag again once a shim has exited, an unreadable environment still walked through), `exec-shim.test.ts` (on Linux the shim built from its source: output and exit status, 128 + N for a signal, a spawn error, a `setsid env -i` escapee ended with its exec, while another exec runs and after a rotation, and out of reach without the shim, a cancel before the group is named; everywhere, stand-in shims for the status pipe: its exit over the shim's, a killed shim, a spawn error, a refused subreaper said once), `tests/integration/container-sandbox-runtime-test.ts` (the image's runnerd names its shim and ends an escapee), `daemon-exit.test.ts` (the SIGKILL exit while a read is out, under Node), `main.test.ts` (`?leftovers=keep` over HTTP on Linux), `harness-wrapper-cancel.test.ts` (each wrapper's staged files removed after one and after two signals); the rotation in `exec-manager.test.ts` (the group ended, the held server ended once the next exec ends, a hold outlasting an earlier exec and a late cancel, a `setsid` server on Linux) and the untagged in-group leftover after a deferral and after an exec that ended alone (Linux); `services/sandbox/src/server.test.ts` + `services/sandbox/src/session/session-routes.test.ts` (the flag reaches runnerd); `backend/core/node_only/sandbox/helpers/session_client.test.ts` (the query) and `backend/core/tasks/agent_run_host.reap.test.ts` (the restart lane rotates, a Stop and a crash cancel in full) | | [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A Gemini CLI agent on a model whose id ends in "flash" (`deepseek-flash`, `glm-5.3-flash`, `qwen3.6-flash`, OpenRouter `google/gemini-3.5-flash`, …) requests that model, not the CLI's own gemini-3.5-flash | ✅ automated | `lib/harnesses/exec-builder.test.ts` (the gemini exec carries `experimental.dynamicModelConfiguration` on both lanes and passes `--model` verbatim), `lib/harnesses/golden-exec.test.ts`, `tests/integration/container-sandbox-runtime-test.ts` (the pinned CLI through `tale-gemini-run` against a loopback gateway stand-in keeps a flash-suffixed id in the request path; immutable system policy survives conflicting repository settings and its files and ancestors are root-owned and not writable by the agent) | diff --git a/services/sandbox-runtime/Dockerfile b/services/sandbox-runtime/Dockerfile index 695c4ee0fc..0502c8d484 100644 --- a/services/sandbox-runtime/Dockerfile +++ b/services/sandbox-runtime/Dockerfile @@ -234,7 +234,10 @@ ENV CLAUDE_CODE_MAX_OUTPUT_TOKENS=64000 # --- coding-agent CLIs (pinned) --------------------------------------------- # Claude Code + Playwright MCP via npm into /opt/agents (on PATH above). -RUN npm install -g --prefix /opt/agents \ +# Native-addon build headers stay in BuildKit's cache, never in runtime layers. +# Share by architecture; node-gyp already separates Node versions within it. +RUN --mount=type=cache,id=tale-sandbox-node-gyp-${TARGETARCH},target=/root/.cache/node-gyp,sharing=locked \ + npm install -g --prefix /opt/agents \ @anthropic-ai/claude-code@${CLAUDE_CODE_VERSION} \ @playwright/mcp@${PLAYWRIGHT_MCP_VERSION} \ && npm cache clean --force @@ -275,7 +278,8 @@ RUN PLAYWRIGHT_DOWNLOAD_HOST="${PLAYWRIGHT_DOWNLOAD_HOST}" \ # hoisting, and reusing that install means the skill reuses the MCP's # already-downloaded Chromium revision (no second ~150 MB browser). COPY configs/platform/custom/skills/visual-aspect-analyzer /opt/agents/skills/visual-aspect-analyzer -RUN cd /opt/agents/skills/visual-aspect-analyzer \ +RUN --mount=type=cache,id=tale-sandbox-skill-bun-${TARGETARCH},target=/root/.bun/install/cache,sharing=locked \ + cd /opt/agents/skills/visual-aspect-analyzer \ && bun install --production \ && MCP=/opt/agents/lib/node_modules/@playwright/mcp \ && ln -sfn "$(node -p "require('path').dirname(require.resolve('playwright/package.json',{paths:['$MCP']}))")" node_modules/playwright \ @@ -362,7 +366,8 @@ RUN chmod +x /usr/local/bin/tale-hermes-run # Gemini CLI (pinned npm, into /opt/agents like Claude Code) + Tale wrapper # that stages per-exec settings/context before the headless run. -RUN npm install -g --prefix /opt/agents "@google/gemini-cli@${GEMINI_CLI_VERSION}" \ +RUN --mount=type=cache,id=tale-sandbox-node-gyp-${TARGETARCH},target=/root/.cache/node-gyp,sharing=locked \ + npm install -g --prefix /opt/agents "@google/gemini-cli@${GEMINI_CLI_VERSION}" \ && npm cache clean --force \ && gemini --version COPY services/sandbox-runtime/tale-gemini-run /usr/local/bin/tale-gemini-run @@ -376,7 +381,8 @@ RUN chmod +x /usr/local/bin/tale-gemini-run # PATH execs the binary directly instead (codex-launcher.in), resolved the way # that launcher resolves it. COPY services/sandbox-runtime/codex-launcher.in /tmp/codex-launcher.in -RUN npm install -g --prefix /opt/agents "@openai/codex@${CODEX_VERSION}" \ +RUN --mount=type=cache,id=tale-sandbox-node-gyp-${TARGETARCH},target=/root/.cache/node-gyp,sharing=locked \ + npm install -g --prefix /opt/agents "@openai/codex@${CODEX_VERSION}" \ && npm cache clean --force \ && codex_root="$(realpath /opt/agents/lib/node_modules/@openai/codex)" \ && codex_bin="$(node -e ' \ @@ -400,7 +406,8 @@ RUN npm install -g --prefix /opt/agents "@openai/codex@${CODEX_VERSION}" \ # Pi (pinned npm, into /opt/agents like Claude Code) + Tale wrapper that # stages the per-exec config dir (models.json/settings/APPEND_SYSTEM.md) # before the headless run. -RUN npm install -g --prefix /opt/agents "@earendil-works/pi-coding-agent@${PI_CODING_AGENT_VERSION}" \ +RUN --mount=type=cache,id=tale-sandbox-node-gyp-${TARGETARCH},target=/root/.cache/node-gyp,sharing=locked \ + npm install -g --prefix /opt/agents "@earendil-works/pi-coding-agent@${PI_CODING_AGENT_VERSION}" \ && npm cache clean --force \ && pi --version COPY services/sandbox-runtime/tale-pi-run /usr/local/bin/tale-pi-run @@ -409,7 +416,8 @@ RUN chmod +x /usr/local/bin/tale-pi-run # OpenClaw (pinned npm, into /opt/agents like Claude Code) + Tale wrapper # that stages per-exec config/prompt/AGENTS.md and translates the CLI's # single --json envelope into Tale NDJSON lifecycle events. -RUN npm install -g --prefix /opt/agents "openclaw@${OPENCLAW_VERSION}" \ +RUN --mount=type=cache,id=tale-sandbox-node-gyp-${TARGETARCH},target=/root/.cache/node-gyp,sharing=locked \ + npm install -g --prefix /opt/agents "openclaw@${OPENCLAW_VERSION}" \ && npm cache clean --force \ && openclaw --version COPY services/sandbox-runtime/tale-openclaw-run /usr/local/bin/tale-openclaw-run @@ -419,7 +427,8 @@ RUN chmod +x /usr/local/bin/tale-openclaw-run # that stages per-exec settings/context before the headless run — the # gemini-cli fork with OpenAI-compatible auth; its headless stream is the # Claude-style stream-json dialect. -RUN npm install -g --prefix /opt/agents "@qwen-code/qwen-code@${QWEN_CODE_VERSION}" \ +RUN --mount=type=cache,id=tale-sandbox-node-gyp-${TARGETARCH},target=/root/.cache/node-gyp,sharing=locked \ + npm install -g --prefix /opt/agents "@qwen-code/qwen-code@${QWEN_CODE_VERSION}" \ && npm cache clean --force \ && qwen --version COPY services/sandbox-runtime/tale-qwen-run /usr/local/bin/tale-qwen-run diff --git a/services/sandbox-runtime/README.md b/services/sandbox-runtime/README.md index 459fad5e22..106b9f33f7 100644 --- a/services/sandbox-runtime/README.md +++ b/services/sandbox-runtime/README.md @@ -156,6 +156,13 @@ installs at image build time so a new agent never downloads or updates its CLI during startup. An image update does not add models to the platform catalog; deploy the matching platform release before selecting newly supported models. +BuildKit keeps native-addon headers and the built-in skill's Bun package cache +outside runtime layers. The October harness refresh grows the amd64 image to +about 6.0 GB; its image-validation budget is 6,600 MB (roughly 10% headroom). +The complete upstream runtimes and diagnostics ship in the image, which is +shared by concurrent sessions. This increases image pull and base-image disk +cost; it does not duplicate the base image for every worker. + Run the wrapper regression tests and the real image conformance suite before shipping a refresh: From 921d0211ab68bed26177c7c0319c1d61f6e9f4f9 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 3 Oct 2026 21:28:09 +0200 Subject: [PATCH 4/5] test(platform): handle reaped children in liveness checks --- .../core/video_links/ytdlp_toolchain.test.ts | 52 +++++++++++++++---- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/services/platform/backend/core/video_links/ytdlp_toolchain.test.ts b/services/platform/backend/core/video_links/ytdlp_toolchain.test.ts index aedcbf8102..8f03007be7 100644 --- a/services/platform/backend/core/video_links/ytdlp_toolchain.test.ts +++ b/services/platform/backend/core/video_links/ytdlp_toolchain.test.ts @@ -7,7 +7,7 @@ * the processes it started. */ import { spawn } from 'node:child_process'; -import { existsSync, readFileSync } from 'node:fs'; +import fs from 'node:fs'; import { chmod, mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; @@ -41,13 +41,11 @@ const FAST = { killGraceMs: 200, }; -/** Alive and not a zombie: an unreaped orphan must not count as stopped. */ +/** A zombie is already stopped, even before its parent reaps it. */ function isAlive(pid: number): boolean { - const stat = `/proc/${pid}/stat`; - if (existsSync('/proc/self/stat')) { - if (!existsSync(stat)) return false; - const state = readFileSync(stat, 'utf8').split(') ')[1]?.[0]; - return state !== undefined && state !== 'Z'; + if (fs.existsSync('/proc/self/stat')) { + const state = procStat(pid)?.state; + return state !== undefined && state !== '' && state !== 'Z'; } try { process.kill(pid, 0); @@ -86,7 +84,7 @@ function procStat( ): { comm: string; state: string; sid: number; startTime: string } | undefined { let stat: string; try { - stat = readFileSync(`/proc/${pid}/stat`, 'utf8'); + stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8'); } catch (err) { const code = (err as NodeJS.ErrnoException).code; if (code === 'ENOENT' || code === 'ESRCH') return undefined; @@ -350,6 +348,42 @@ async function stallingScript( }; } +describe('process liveness observations', () => { + it.each(['ENOENT', 'ESRCH'])( + 'counts a child that disappears during the stat read as gone (%s)', + (code) => { + // Force the procfs path on every host. Even a successful existence + // probe cannot guarantee the child remains alive until the read. + const exists = vi.spyOn(fs, 'existsSync').mockReturnValue(true); + const read = vi.spyOn(fs, 'readFileSync').mockImplementationOnce(() => { + throw Object.assign(new Error('process disappeared'), { code }); + }); + try { + expect(isAlive(12345)).toBe(false); + } finally { + read.mockRestore(); + exists.mockRestore(); + } + }, + ); + + it('does not report an unreadable live process as gone', () => { + const error = Object.assign(new Error('permission denied'), { + code: 'EACCES', + }); + const exists = vi.spyOn(fs, 'existsSync').mockReturnValue(true); + const read = vi.spyOn(fs, 'readFileSync').mockImplementationOnce(() => { + throw error; + }); + try { + expect(() => isAlive(12345)).toThrow(error); + } finally { + read.mockRestore(); + exists.mockRestore(); + } + }); +}); + describe('downloadTo bounds', () => { it('rejects a body that stops arriving, naming the body stage', async () => { const url = await stub('stall-body'); @@ -366,7 +400,7 @@ describe('downloadTo bounds', () => { /^\[video-toolchain\] yt-dlp download body: timed out after \d+ ms \(deadline 500 ms\)$/, ); expect(Date.now() - startedAt).toBeLessThan(5_000); - expect(existsSync(join(scratch, 'yt-dlp'))).toBe(false); + expect(fs.existsSync(join(scratch, 'yt-dlp'))).toBe(false); }); it('rejects a server that never answers, naming the response stage', async () => { From 0988bcf66175c03da5031e9ff524a641120ff72d Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 3 Oct 2026 21:29:19 +0200 Subject: [PATCH 5/5] ci(sandbox): install workspace dependencies for runtime validation --- .github/workflows/build.yml | 16 +++++++++------ tools/cli/scripts/deployment-ci.test.ts | 26 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 78dbaf0b09..32fa2d410c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -855,10 +855,12 @@ jobs: docker tag "ghcr.io/tale-project/tale/tale-sandbox-runtime:latest" \ "tale-sandbox-runtime:latest" - - name: Setup Bun - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + # Runtime conformance imports workspace schemas and the exec builder. + - name: Setup toolchain + uses: ./.github/actions/setup-turbo with: - bun-version: '1.3.12' + github-token: ${{ secrets.GITHUB_TOKEN }} + start-turbo-cache: 'false' - name: Run image validation run: bun services/platform/tests/integration/container-image-test.ts @@ -899,10 +901,12 @@ jobs: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL sudo docker image prune -af - - name: Setup Bun - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + # The fork lane runs the same workspace-dependent conformance helpers. + - name: Setup toolchain + uses: ./.github/actions/setup-turbo with: - bun-version: '1.3.12' + github-token: ${{ secrets.GITHUB_TOKEN }} + start-turbo-cache: 'false' - name: Run image validation (local build) run: bun services/platform/tests/integration/container-image-test.ts diff --git a/tools/cli/scripts/deployment-ci.test.ts b/tools/cli/scripts/deployment-ci.test.ts index 49df95afaf..860219ddd9 100644 --- a/tools/cli/scripts/deployment-ci.test.ts +++ b/tools/cli/scripts/deployment-ci.test.ts @@ -646,6 +646,32 @@ printf '%s\\n' "$TEST_COMPARE_STATUS" }, ); + test.each(['image-validate', 'image-validate-fork'])( + '%s installs workspace dependencies before running image checks', + async (id) => { + const job = (await workflow()).jobs[id]!; + const setupIndex = job.steps.findIndex( + (entry) => entry.uses === './.github/actions/setup-turbo', + ); + expect(setupIndex).toBeGreaterThanOrEqual(0); + const setup = job.steps[setupIndex]!; + expect(setup.if).toBeUndefined(); + expect(setup.with?.['start-turbo-cache']).toBe('false'); + // Inherit the shared Bun pin and its frozen install. The conformance + // helpers import workspace packages, which Bun alone cannot resolve. + expect(setup.with?.['bun-version']).toBeUndefined(); + for (const entrypoint of [ + 'container-image-test.ts', + 'container-sandbox-runtime-test.ts', + ]) { + const checkIndex = job.steps.findIndex((entry) => + entry.run?.includes(entrypoint), + ); + expect(checkIndex).toBeGreaterThan(setupIndex); + } + }, + ); + describe.each(['smoke-test', 'image-validate'])('%s', (id) => { const pull = async () => { const job = (await workflow()).jobs[id]!;