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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions services/platform/lib/harnesses/exec-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
// injection safety, error paths). Byte-exact construction is
// golden-exec.test.ts.

import { readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import type { HarnessDefinition } from '@tale/shared/schemas/providers';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

Expand All @@ -13,6 +17,7 @@ import {
buildHarnessExec,
CACHE_AFFINITY_GATEWAY_HEADER,
isClaudeModelRef,
PLAYWRIGHT_MCP_ARG_SETS,
} from './exec-builder';
import { batteryFor, GOLDEN_BYO_ENV, GOLDEN_GATEWAY } from './test-helpers';
import type { HarnessExec, HarnessRunSpec } from './types';
Expand Down Expand Up @@ -904,3 +909,20 @@ describe('gemini requests the model it was given', () => {
}
});
});

describe('the Playwright MCP server the runtime image prepares for', () => {
it('has a record for every argument set a turn may start it with', () => {
// The image records the server's answers for these sets; a set missing
// there starts the server (~100 MB) with every turn again.
const recorded: unknown = JSON.parse(
readFileSync(
path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../../../sandbox-runtime/playwright-mcp-args.json',
),
'utf8',
),
);
expect(recorded).toEqual(PLAYWRIGHT_MCP_ARG_SETS);
});
});
10 changes: 10 additions & 0 deletions services/platform/lib/harnesses/exec-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,16 @@ const PLAYWRIGHT_MCP_ARGS = [
* the path, so the agent reads it as usual. */
const PLAYWRIGHT_VISION_ARGS = ['--image-responses', 'omit'] as const;

/** Every argument set a turn may start the Playwright MCP server with. The
* runtime image records the server's answers to the start of a turn for each
* of them (services/sandbox-runtime/playwright-mcp-args.json, held equal by
* this module's test), so a turn that never opens a browser never starts the
* server; a set it has no record for starts the server at once. */
export const PLAYWRIGHT_MCP_ARG_SETS: readonly (readonly string[])[] = [
PLAYWRIGHT_MCP_ARGS,
[...PLAYWRIGHT_MCP_ARGS, ...PLAYWRIGHT_VISION_ARGS],
];

/** The capability-dispatch bridge — lets the agent use the org's connected
* connectors. The credential stays server-side; the bridge only relays
* dispatch requests to the platform, authed by the session key. Because it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,97 @@ send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '
}
}

console.log('');
console.log('--- playwright MCP starts only when a turn uses the browser ---');
// The launcher answers the start of a turn from the manifests the image build
// recorded for the platform's argument sets (playwright-mcp-args.json): the
// real server, a Node process holding ~100 MB, must not run until the first
// tool call, its tool list must be the server's own, and a tool call must
// reach a server started then.
{
const nodeScript = `const { spawn, execFileSync } = require('child_process');
const args = JSON.parse(require('fs').readFileSync('/opt/tale/playwright-mcp/args.json', 'utf8'))[0];
const serverRunning = () => {
try { execFileSync('pgrep', ['-f', 'bin/mcp-server-playwright']); return true; } catch { return false; }
};
function session(command, argv) {
const srv = spawn(command, argv, { stdio: ['pipe', 'pipe', 'inherit'] });
const waiting = new Map();
let buf = '';
srv.stdout.on('data', (d) => {
buf += d.toString();
let idx;
while ((idx = buf.indexOf('\\n')) >= 0) {
const line = buf.slice(0, idx); buf = buf.slice(idx + 1);
let msg; try { msg = JSON.parse(line); } catch { continue; }
const done = waiting.get(msg.id);
if (done) { waiting.delete(msg.id); done(msg); }
}
});
const ask = (id, method, params) => new Promise((resolve) => {
waiting.set(id, resolve);
srv.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, ...(params ? { params } : {}) }) + '\\n');
});
const tell = (method) => srv.stdin.write(JSON.stringify({ jsonrpc: '2.0', method }) + '\\n');
return { srv, ask, tell };
}
const init = { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'conformance', version: '1.0' } };
(async () => {
const deadline = setTimeout(() => { console.error('LAZY_TIMEOUT'); process.exit(1); }, 90000);
const lazy = session('tale-playwright-mcp', args);
await lazy.ask(1, 'initialize', init);
lazy.tell('notifications/initialized');
const listed = await lazy.ask(2, 'tools/list');
if (serverRunning()) { console.error('LAZY_SERVER_STARTED_EARLY'); process.exit(1); }
const direct = session('mcp-server-playwright', args);
await direct.ask(1, 'initialize', init);
direct.tell('notifications/initialized');
const own = await direct.ask(2, 'tools/list');
direct.srv.kill();
if (JSON.stringify(listed.result) !== JSON.stringify(own.result)) { console.error('LAZY_TOOLS_DIFFER'); process.exit(1); }
const called = await lazy.ask(3, 'tools/call', { name: 'browser_navigate', arguments: { url: 'about:blank' } });
if (called.error || (called.result && called.result.isError)) { console.error('LAZY_NAVIGATE_FAILED ' + JSON.stringify(called)); process.exit(1); }
clearTimeout(deadline);
console.log('MCP_LAZY_OK ' + listed.result.tools.length);
lazy.srv.kill();
process.exit(0);
})().catch((error) => { console.error(error); process.exit(1); });
`;
const { combined } = await capture(
[
'docker',
'run',
'--rm',
'-i',
'--user',
'10001',
'--read-only',
'--tmpfs',
'/tmp:exec,nosuid,nodev,size=256m',
'--tmpfs',
'/workspace:uid=10001,gid=10001',
'--shm-size=512m',
'--env',
'HOME=/workspace/.home',
'--env',
'TMPDIR=/workspace/.tmp',
'--entrypoint',
'sh',
IMAGE,
'-c',
'mkdir -p "$HOME" "$TMPDIR" && exec node -',
],
{ stdin: nodeScript },
);
if (combined.includes('MCP_LAZY_OK')) {
pass(
'playwright MCP answers the start itself and starts the server on the first tool call',
);
} else {
fail(`playwright MCP lazy start failed (got: ${combined.slice(0, 400)})`);
}
}

console.log('');
console.log('--- runnerd boots under the daemon entrypoint ---');
// Start the daemon (PID 1 via the image entrypoint `daemon` arg) and probe
Expand Down
1 change: 1 addition & 0 deletions services/platform/tests/manual/reference/automation.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s
| [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: <exec id>`, 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) | ✅ automated | `tests/integration/container-sandbox-runtime-test.ts` (registry-driven: every `managed: true` harness's exec binary on the agent PATH), `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) / [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): 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` and `ping` from manifests the image build records for the platform's argument sets, starts the server on the first other request, replaying the client's start under an id of its own, and passes every message through both ways (a server request and the client's answer included); unknown arguments or protocol versions 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, the start answered without it, the start replayed on the first tool call, a roots request round trip, an unknown version and the eager switch, the exit status, the proxy flags), `tests/integration/container-sandbox-runtime-test.ts` (the image's own server: not running after `tools/list`, the same tool list as 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) |
| [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` |
Expand Down
1 change: 1 addition & 0 deletions services/platform/turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"$TURBO_ROOT$/services/sandbox-runtime/Dockerfile",
"$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",
"$TURBO_ROOT$/services/sandbox/src/config.ts"
]
},
Expand Down
12 changes: 9 additions & 3 deletions services/sandbox-runtime/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -488,10 +488,16 @@ COPY services/sandbox-runtime/tale-plan-gate /usr/local/bin/tale-plan-gate
# via the session entrypoint; baked here so it exists read-only.
COPY services/sandbox-runtime/tale-git-credential /usr/local/bin/tale-git-credential

# Playwright MCP launcher shim: appends --proxy-server/--proxy-bypass from the
# container's HTTPS_PROXY/NO_PROXY (Chromium ignores the env vars) and execs
# mcp-server-playwright. The agent adapters use this as the MCP command.
# Playwright MCP launcher: appends --proxy-server/--proxy-bypass from the
# container's HTTPS_PROXY/NO_PROXY (Chromium ignores the env vars), and answers
# the start of an agent turn (initialize, tools/list) from manifests of the
# real server's answers, recorded below for the argument sets the platform
# passes (playwright-mcp-args.json, held to exec-builder.ts by its test): the
# server, a Node process holding ~100 MB, starts only once the turn first uses
# the browser. The agent adapters use this as the MCP command.
COPY services/sandbox-runtime/tale-playwright-mcp /usr/local/bin/tale-playwright-mcp
COPY services/sandbox-runtime/playwright-mcp-args.json /opt/tale/playwright-mcp/args.json
RUN python3 -Es /usr/local/bin/tale-playwright-mcp --write-manifests /opt/tale/playwright-mcp/args.json

# Connector-dispatch MCP bridge: a dependency-free stdio MCP server the agent
# adapters wire in via --mcp-config. Relays connector({slug,operation,args})
Expand Down
11 changes: 10 additions & 1 deletion services/sandbox-runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,16 @@ Headless Chromium and Playwright are available on demand for automation,
rendering and screenshots. The runtime starts no display server, managed
browser or viewing tunnel. Configured transparent egress redirects external
network access through `@tale/sandbox-egress`; Playwright MCP also receives
the proxy settings through its launcher.
the proxy settings through its launcher (`tale-playwright-mcp`). Every managed
agent turn lists the Playwright MCP server, but most never open a browser, and
the server — a Node process that loads Playwright — holds about 100 MB while it
runs. So the launcher answers the start of a turn itself (`initialize`,
`tools/list`, `ping`) from manifests of the real server's answers, recorded at
image build for the argument sets the platform passes
([`playwright-mcp-args.json`](playwright-mcp-args.json)), and starts the server
only on the turn's first tool call, replaying the start to it. Unknown
arguments or protocol versions, and `TALE_PLAYWRIGHT_MCP_EAGER=1`, start the
server at once.

Python document libraries are baked into the shared Python 3.12 environment:
openpyxl and xlrd for spreadsheets, pypdf for PDFs, PyYAML for safe YAML
Expand Down
Loading