Skip to content

feat(sandbox): code-execution sandbox + runnable artifacts - #1727

Merged
larryro merged 108 commits into
mainfrom
feat/sandbox-code-run
May 24, 2026
Merged

larryro merged 108 commits into
mainfrom
feat/sandbox-code-run

Conversation

@larryro

@larryro larryro commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds an isolated code-execution sandbox and folds it into the artifact system as a new class of runnable artifacts (python_runnable / node_runnable). The LLM can now author, edit, and execute Python or Node scripts inside the chat canvas, with generated files surfaced as downloadable chat-card parts.

What's new

New services

  • services/sandbox/ — Bun-based spawner that manages containerized executions (quota, slot reservation, watchdog, output streaming).
  • services/sandbox-runtime/ — hardened Docker image (Python + Node) used as the per-execution container.
  • services/sandbox-egress/ — tinyproxy-based egress proxy isolating sandbox network traffic.

Convex backend

  • convex/sandbox/ — execution schema (sandboxExecutions), internal mutations/queries, output ingestion, cron-driven cleanup, governance hooks.
  • node_only/sandbox/ — internal action layer + spawner client that talks to the sandbox service.

Agent tools

  • New runnable artifact types (python_runnable, node_runnable) integrated into artifact_create / artifact_edit.
  • New artifact_run tool — explicit, LLM-driven execution trigger. Separating authoring from execution prevents the LLM from spamming duplicate artifact_create calls on run failure.
  • chat-agent.json updated (en/de/fr) with the 4-step author → run → edit → re-run cycle.

Canvas UI

  • canvas-runnable-code-renderer.tsx — execution panel (status, stderr preview, generated files) stacked above the source pane.
  • Runnable types registered in the artifact bar / message-bubble pill icon maps.
  • New canvas.runDone i18n key (en/de/fr).

CLI

  • tale doctor — diagnostics for sandbox prerequisites (docker, network, images).
  • tale start / tale deploy integrate the sandbox + sandbox-egress services; dev compose publishes port 8003 for bun dev.

Pre-PR checklist

  • Ran bun run check (format, lint, typecheck, all tests). — not yet run; please run before merge
  • Updated services/platform/messages/{en,de,fr}.json (new canvas.runDone key).
  • Updated /docs/{en,de,fr}/ for every user-visible change. — pending: new agent tool, new artifact types, tale doctor, sandbox env vars (SANDBOX_URL, SANDBOX_TOKEN)
  • Every touched docs page has a real opening and closing. — N/A until docs are added
  • Ran bun run --filter @tale/docs lint and bun run --filter @tale/docs test. — N/A until docs are added
  • Updated README.md, README.de.md, README.fr.md. — likely needed (new services in the stack)

Test plan

  • bun run check is green.
  • tale doctor reports OK on a clean dev machine.
  • tale start brings up sandbox + sandbox-egress alongside the existing stack; ports/network as expected.
  • Smoke: chat-agent receives a "write & run a Python script that …" request → artifact_create(python_runnable) → artifact_run → canvas shows stdout/stderr + downloadable files; no duplicate v1 tabs in the artifact bar.
  • Failure path: forced runtime error → LLM follows artifact_edit → artifact_run cycle (not another artifact_create).
  • Node runnable equivalent path.
  • Quota + watchdog: spawn beyond the slot reservation budget; killed runs surface runErrorCode and a stderr preview.
  • sandboxExecutions audit rows are written and cleaned up by the cron.

Summary by CodeRabbit

  • New Features

    • Runnable artifacts (Python/Node) with sandboxed execution, run status, logs, and downloadable outputs
    • New runtime spawner and sandbox services (egress proxy, spawner, runtime) plus dev Compose/network support
    • Canvas and chat UI show runnable artifact status, run controls, and output downloads
    • CLI: new doctor command and sandbox network setup helpers; env tooling emits sandbox token
  • Bug Fixes

    • Prevented duplicate placeholder rows during streaming artifact creation
  • Tests

    • Added sandbox execution and quota unit tests

Comment thread services/sandbox-egress/Dockerfile Fixed
Comment thread services/sandbox/Dockerfile Fixed
@@ -0,0 +1,226 @@
'use node';
@@ -0,0 +1,523 @@
'use node';
@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds runnable artifact types (python/node), a new Convex execution workflow (sandboxExecutions, mutations, queries), an internal action that calls a sandbox spawner, and a Bun-based spawner service that runs per-call Docker sandboxes. Persists run config on artifacts, introduces artifact_run tool and updates artifact_create/edit, adds UI components to show run state/files, integrates sandbox services into compose/CLI/env/templates, provides a doctor command and tests, and implements network/volume/cleanup helpers and runtime images.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~150 minutes

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/sandbox-code-run

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 22

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tools/cli/src/lib/actions/deploy.ts (1)

47-48: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Include sandbox network in dry-run logging for parity.

ensureInfrastructure now creates two networks, but dry-run only reports one. Add a dry-run line for the sandbox network so operators see the full infra plan.

Also applies to: 59-63

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/cli/src/lib/actions/deploy.ts` around lines 47 - 48, Dry-run logging in
deploy.ts’s ensureInfrastructure path only reports the internal network; add a
matching dry-run log for the sandbox network so the operator sees both networks.
Update the logger.info call(s) that currently print `${prefix}Would ensure
network: ${getProjectId()}_internal` to also emit `${prefix}Would ensure
network: ${getProjectId()}_sandbox` (do this in the earlier dry-run return block
and the later dry-run block around lines 59-63), referencing the same prefix,
getProjectId() and logger.info used in ensureInfrastructure.
services/platform/app/features/chat/components/canvas/canvas-pane.tsx (1)

153-161: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Localize runnable type labels instead of hardcoding English.

Python (sandbox) and Node (sandbox) should be translation keys so the canvas badge remains localized like the rest of the UI.

As per coding guidelines: “No hardcoded user-facing strings; always use the translation hook.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/platform/app/features/chat/components/canvas/canvas-pane.tsx` around
lines 153 - 161, Replace the hardcoded English labels for runnable types in
TYPE_LABELS so they use the translation hook instead of literal strings: update
the entries for the keys "python_runnable" and "node_runnable" in the
TYPE_LABELS Record<CanvasContentType, string> to call the i18n translate
function (use the existing t hook or import useTranslation/t as used in this
component) with distinct keys like "canvas.type.python_runnable" and
"canvas.type.node_runnable"; also add those keys (with appropriate localized
values) to the locale resource files so the badge text is translated at runtime.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@knip.config.ts`:
- Around line 56-57: The knip config's "entry" array currently only lists test
globs ('src/**/*.test.ts'), which can cause live runtime files like
src/server.ts to be treated as unused; update the knip.config.ts "entry" to
include the application's runtime entrypoint (e.g., add 'src/server.ts' to the
entry array) so knip analyzes the live service code when computing usage for the
project.

In
`@services/platform/app/features/chat/components/canvas/canvas-runnable-code-renderer.tsx`:
- Around line 156-157: The current cast using "as RunOutputFile[]" on
artifact?.runOutputFiles can hide runtime shape mismatches; replace it by
implementing a type guard (e.g., isRunOutputFile and isRunOutputFileArray) that
validates each object's required discriminators/fields and use that guard when
assigning outputFiles (instead of the cast) so you assign
artifact.runOutputFiles only when isRunOutputFileArray(artifact.runOutputFiles)
is true, otherwise default to an empty array; add the guard functions near the
component (or in a shared validators file) and reference them from
canvas-runnable-code-renderer.tsx when computing outputFiles.
- Around line 116-124: The component currently renders hardcoded user-facing
strings (e.g., the raw runStatus value and labels like "Run", "Files",
"stdout/stderr", "chars") inside CanvasRunnableCodeRenderer (see use of
runStatus and Badge) — replace those with i18n keys by importing and using the
project's translation hook (e.g., t or useTranslations) and wrap each
user-facing string (including the run status output) with t(...) calls using
appropriate keys; update all occurrences noted (around runStatus rendering and
the label locations at the other listed blocks) so the Badge children and all
labels call t('...') instead of literal text, and ensure keys are descriptive
and added to the locale files.

In `@services/platform/convex/agent_tools/artifacts/shared.ts`:
- Around line 24-33: The current isValidArtifactType function duplicates the
ArtifactType values with a manual OR-chain, risking drift; change it to derive
validity from the canonical artifactTypeEnum instead: import or reference
artifactTypeEnum and implement isValidArtifactType by checking whether value is
a member of artifactTypeEnum (e.g., using
Object.values(artifactTypeEnum).includes(value) or artifactTypeEnum.includes if
it’s an array), keeping the function signature isValidArtifactType(value:
string): value is ArtifactType and ensuring the check uses the enum’s runtime
values so future enum additions are automatically covered.

In `@services/platform/convex/node_only/sandbox/helpers/spawner_client.ts`:
- Around line 234-238: The catch block that wraps the fetch call to fetch(url, {
method: 'POST', headers, body }) currently swallows errors; update the catch to
log the error and context (e.g. URL and any identifying execution id) using
console.warn or console.error instead of leaving it empty, while keeping the
existing comment about best-effort cancellation; ensure the log includes the
error object so failures to POST cancellation requests are recorded for
debugging.

In `@services/platform/convex/sandbox/internal_mutations.test.ts`:
- Around line 57-85: The mock builder in makeBuilder only records status
predicates so tests won’t catch missing org/index predicates; update
builder.withIndex to also capture the index name argument and any org eq()
predicate (push { indexName: _name, field, value } into calls), and change
builder[Symbol.asyncIterator] to verify the captured indexName and org id (e.g.,
find a call with field === 'orgId' and expected value) before selecting
runningRows/queuedRows/completedRows so the fake query fails if
reserveSlotAndInsert drops or uses the wrong org/index filter.
- Around line 118-121: The test mock for internalMutation should be made generic
so the imported handlers keep their types and eliminate the repeated "as unknown
as" casts; update the mocked internalMutation signature to accept a generic type
parameter (e.g., internalMutation<TArgs, TReturn>(handler: MutHandler<TArgs,
TReturn>) or similar) and return a properly typed MutHandler<TArgs, TReturn>,
then adjust the mock implementation to forward types so usages like
reserveSlotAndInsert can be assigned directly (remove casts) — refer to the
mocked function name internalMutation and the test symbols reserveSlotAndInsert,
MutHandler, and baseArgs when making this change.

In `@services/sandbox-egress/Dockerfile`:
- Around line 27-28: Remove the inline HEALTHCHECK directive from the
Dockerfile: delete the HEALTHCHECK block ("HEALTHCHECK --interval=10s
--timeout=3s --retries=2 CMD nc -z 127.0.0.1 3128 || exit 1") so the image no
longer embeds orchestration-specific health policy; keep health checks
centralized in your Compose/service definitions instead (adjust
docker-compose.yml service for the sandbox-egress container to define equivalent
healthcheck there).

In `@services/sandbox-egress/tinyproxy.conf.template`:
- Around line 30-31: The configuration currently sets DisableViaHeader No which
contradicts the hardening intent; change the tinyproxy setting DisableViaHeader
from "No" to "Yes" in tinyproxy.conf.template so the Via header is suppressed on
outgoing requests (i.e., ensure the line reads DisableViaHeader Yes).

In `@services/sandbox-runtime/entrypoint.sh`:
- Around line 72-73: The uv command invocation "uv pip list --format=json
--python /workspace/.deps/python" uses an unsupported --python flag; change the
call to use a supported form such as "uv pip list --format=json" (or if you
intend to capture the current environment's installed packages, use "uv pip
freeze --format=json") so the command succeeds and produces
/workspace/install-report.json instead of failing silently.

In `@services/sandbox/Dockerfile`:
- Around line 32-33: The Dockerfile contains an image-level HEALTHCHECK (the
HEALTHCHECK instruction executing "curl -fsS http://127.0.0.1:8003/health ||
exit 1") which conflicts with the repo convention to centralize health checks in
compose; remove this HEALTHCHECK instruction from the Dockerfile and instead add
an equivalent healthcheck entry for this service in the compose/orchestration
configuration so health logic lives only at compose-level (keep the same
endpoint/interval/timeout/retries semantics when migrating).
- Line 12: Update the sandbox Dockerfile's FROM line to use the Bun 1.3 baseline
(e.g., change the FROM value to oven/bun:1.3-debian or newer) and update the
sandbox package.json `@types/bun` version to match the project's 1.3.11 (ensure
packageManager remains [email protected]); locate the Dockerfile's FROM directive and
the services/sandbox/package.json dependency entry for "`@types/bun`" to make
these changes so the container OS and type definitions align with the project
baseline.

In `@services/sandbox/src/config.ts`:
- Around line 17-22: Remove the "as 'runc' | 'runsc'" cast on the runtime
variable and add a type‑guard to narrow the value via control flow: read const
raw = process.env.SANDBOX_RUNTIME ?? 'runc', implement a function like
isSandboxRuntime(value: string): value is 'runc' | 'runsc' and use it in the
existing check (throw if not valid); after the guard the runtime value will be
narrowed to 'runc' | 'runsc' for use elsewhere (refer to the SANDBOX_RUNTIME
env, the runtime/raw variable and add isSandboxRuntime as the narrowing helper).

In `@services/sandbox/src/server.ts`:
- Around line 80-89: The code adds parsed.executionId into inFlightSet before
validating parsed, which may insert undefined; update the flow around JSON.parse
and inFlightSet so you validate that parsed.executionId is present and a valid
identifier (e.g., non-empty string) before calling inFlightSet.add; if
validation fails, return the 400 Response (same structure used on JSON parse
failure) and do not add to inFlightSet. Target the JSON.parse block and the use
of parsed, ExecuteRequest, parsed.executionId and inFlightSet in server.ts to
implement this guard.

In `@services/sandbox/src/spawn_util.ts`:
- Around line 82-116: The timeout is armed after awaiting collectStdout()/stderr
which means a hung docker prevents the timeout from ever starting; move the
timeout race to start before/while collecting output by creating a single
Promise.race that includes the exited promise, the timeout promise (the existing
timer logic that sets timedOut, calls proc.kill('SIGKILL') and spawns the docker
killer using DOCKER_BIN when opts.killOnTimeoutContainer is set), and the
stdout/stderr collection (collectStdout() and new
Response(proc.stderr).arrayBuffer()); in practice modify the code around
collectStdout(), proc.exited, and opts.timeoutMs so you start the timeout
Promise concurrently (using Promise.race) with collectStdout()/stderr collection
instead of awaiting output first, ensuring timer is set/cleared appropriately
and reusing proc, timer, proc.kill, killOnTimeoutContainer, and Bun.spawn as in
the current logic.

In `@services/sandbox/src/spawn.ts`:
- Around line 250-252: The current timeout cleanup timers call dockerKill (and
similarly dockerRm / rm in the other block) and silently swallow any errors;
update the handlers around setTimeout and the cleanup callers (referencing the
killTimer callback and the other cleanup block that calls dockerRm/rm) to catch
rejections and surface them: log the full error via the service logger (include
containerName/sessionDir context), increment a cleanup-failure metric or
counter, and optionally perform a best-effort retry or escalate (e.g., schedule
a single retry after a short delay) rather than ignoring the failure. Ensure
dockerKill, dockerRm and rm callers use .catch(err => { logger.error(..., err);
metrics.increment('cleanup.failure'); /* optional retry */ }) so orphaned
containers/directories are visible in logs/metrics.
- Around line 220-226: Detect and reject duplicate executionId values before
staging by checking inFlight.has(req.executionId) immediately (before computing
containerName/workspaceHostDir and before creating the AbortController); if the
id already exists, return/throw a clear error to abort the request. Use the
existing inFlight Map (symbol: inFlight) as the guard, and only create and set
the entry ({ containerName, abort }) after the check so you don't overwrite an
existing run; ensure any cleanup paths rely on the presence of that exact
inFlight entry to avoid canceling or deleting another run.
- Around line 130-165: The walker currently explores every entry under outputDir
even after byte limits are reached; modify the async function walk(rel: string)
so it short-circuits traversal as soon as caps are exceeded: at the top of walk
check if totalAccepted >= caps.totalMax (or another combined limit you choose)
and return immediately; before recursing into subdirectories check the same and
skip walking that child; before calling stat/readFile also check per-file and
remaining total bytes to avoid unnecessary I/O; keep using truncatedCount to
record skipped files and ensure files, totalAccepted, truncatedCount updates
remain consistent.

In `@services/sandbox/src/volume.ts`:
- Around line 43-57: The current check-then-create flow using runDocker allows a
race where volume create can fail with "already exists" and is treated as fatal;
update the logic around runDocker calls in this module (the inspect and create
calls in volume.ts) to treat a create failure that indicates the volume already
exists as non-fatal: after running the create command (the variable named
create), if create.exitCode !== 0 inspect create.stderr/create.stdout for the
“already exists” message (or Docker’s equivalent) and, if present, treat the
operation as successful (return) instead of throwing; only throw for genuine
failures that are not the already-exists case.

In `@tests/container-smoke-test.sh`:
- Around line 87-92: The docker network create step can fail if the network
already exists or is in use; make the setup idempotent by checking for the
network before creating or by swallowing non-fatal create errors: use `docker
network inspect tale-sandbox-net >/dev/null 2>&1 || docker network create
--internal --ipv6=false --driver=bridge tale-sandbox-net >/dev/null` or append
`|| true` to the `docker network create ... tale-sandbox-net` call so the script
does not hard-fail when the network already exists or creation returns a
non-zero status.

In `@tools/cli/src/commands/doctor.ts`:
- Around line 119-127: The SANDBOX_TOKEN check in function checkSandboxToken
currently returns status: 'fail' when missing/short which conflicts with the PR
making SANDBOX_TOKEN optional; change the returned status to 'warn' (or, if you
want to keep fail behavior for certain modes, gate the failure by checking the
runtime mode/flag and only set status: 'fail' when that explicit mode requires
the token). Update both occurrences of this logic (the checkSandboxToken
function and the similar check at lines ~175-178) so they return a warning
message and appropriate fix text instead of failing the entire doctor run unless
explicitly required by mode.

In `@tools/cli/src/lib/compose/services/create-sandbox-service.ts`:
- Around line 29-33: The ports mapping currently uses ports: ['8003:8003'] which
binds the spawner to all host interfaces; change this to bind to loopback only
by replacing that entry with an explicit loopback host binding (e.g.,
'127.0.0.1:8003:8003') in the create-sandbox-service definition so the container
port 8003 is published only on localhost and reduces the exposed attack surface.

---

Outside diff comments:
In `@services/platform/app/features/chat/components/canvas/canvas-pane.tsx`:
- Around line 153-161: Replace the hardcoded English labels for runnable types
in TYPE_LABELS so they use the translation hook instead of literal strings:
update the entries for the keys "python_runnable" and "node_runnable" in the
TYPE_LABELS Record<CanvasContentType, string> to call the i18n translate
function (use the existing t hook or import useTranslation/t as used in this
component) with distinct keys like "canvas.type.python_runnable" and
"canvas.type.node_runnable"; also add those keys (with appropriate localized
values) to the locale resource files so the badge text is translated at runtime.

In `@tools/cli/src/lib/actions/deploy.ts`:
- Around line 47-48: Dry-run logging in deploy.ts’s ensureInfrastructure path
only reports the internal network; add a matching dry-run log for the sandbox
network so the operator sees both networks. Update the logger.info call(s) that
currently print `${prefix}Would ensure network: ${getProjectId()}_internal` to
also emit `${prefix}Would ensure network: ${getProjectId()}_sandbox` (do this in
the earlier dry-run return block and the later dry-run block around lines
59-63), referencing the same prefix, getProjectId() and logger.info used in
ensureInfrastructure.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 563a2a93-503d-42b2-8301-27c5e0bc0db3

📥 Commits

Reviewing files that changed from the base of the PR and between ad6018a and 565f2f2.

⛔ Files ignored due to path filters (2)
  • services/platform/convex/_generated/api.d.ts is excluded by !**/_generated/**
  • services/sandbox/bun.lock is excluded by !**/*.lock
📒 Files selected for processing (68)
  • .commitlintrc.json
  • compose.yml
  • examples/agents/chat-agent.json
  • knip.config.ts
  • services/platform/app/features/chat/components/canvas/artifact-bar.tsx
  • services/platform/app/features/chat/components/canvas/canvas-context.tsx
  • services/platform/app/features/chat/components/canvas/canvas-pane.tsx
  • services/platform/app/features/chat/components/canvas/canvas-runnable-code-renderer.tsx
  • services/platform/app/features/chat/components/message-bubble.tsx
  • services/platform/convex/agent_tools/artifacts/artifact_create_tool.ts
  • services/platform/convex/agent_tools/artifacts/artifact_edit_tool.ts
  • services/platform/convex/agent_tools/artifacts/artifact_run_tool.ts
  • services/platform/convex/agent_tools/artifacts/shared.ts
  • services/platform/convex/agent_tools/tool_names.ts
  • services/platform/convex/agent_tools/tool_registry.ts
  • services/platform/convex/artifacts/internal_mutations.ts
  • services/platform/convex/artifacts/internal_queries.ts
  • services/platform/convex/artifacts/schema.ts
  • services/platform/convex/crons.ts
  • services/platform/convex/governance/soft_delete_helpers.ts
  • services/platform/convex/governance/soft_delete_validators.ts
  • services/platform/convex/lib/context_management/build_artifacts_context.ts
  • services/platform/convex/node_only/sandbox/helpers/spawner_client.ts
  • services/platform/convex/node_only/sandbox/internal_actions.ts
  • services/platform/convex/sandbox/internal_mutations.test.ts
  • services/platform/convex/sandbox/internal_mutations.ts
  • services/platform/convex/sandbox/internal_queries.ts
  • services/platform/convex/sandbox/output_mutations.ts
  • services/platform/convex/sandbox/schema.ts
  • services/platform/convex/schema.ts
  • services/platform/env.sh
  • services/platform/messages/de.json
  • services/platform/messages/en.json
  • services/platform/messages/fr.json
  • services/sandbox-egress/Dockerfile
  • services/sandbox-egress/entrypoint.sh
  • services/sandbox-egress/tinyproxy.conf.template
  • services/sandbox-runtime/Dockerfile
  • services/sandbox-runtime/entrypoint.sh
  • services/sandbox/Dockerfile
  • services/sandbox/Dockerfile.dockerignore
  • services/sandbox/package.json
  • services/sandbox/seccomp.json
  • services/sandbox/src/auth.ts
  • services/sandbox/src/cleanup.ts
  • services/sandbox/src/config.ts
  • services/sandbox/src/docker_args.test.ts
  • services/sandbox/src/docker_args.ts
  • services/sandbox/src/server.ts
  • services/sandbox/src/spawn.ts
  • services/sandbox/src/spawn_util.ts
  • services/sandbox/src/types.ts
  • services/sandbox/src/volume.ts
  • services/sandbox/tsconfig.json
  • tests/container-image-test.sh
  • tests/container-smoke-test.sh
  • tools/cli/src/commands/doctor.ts
  • tools/cli/src/index.ts
  • tools/cli/src/lib/actions/deploy.ts
  • tools/cli/src/lib/actions/start.ts
  • tools/cli/src/lib/compose/generators/generate-dev-compose.ts
  • tools/cli/src/lib/compose/generators/generate-stateful-compose.ts
  • tools/cli/src/lib/compose/services/create-convex-service.ts
  • tools/cli/src/lib/compose/services/create-sandbox-egress-service.ts
  • tools/cli/src/lib/compose/services/create-sandbox-service.ts
  • tools/cli/src/lib/compose/types.ts
  • tools/cli/src/lib/config/ensure-env.ts
  • tools/cli/src/lib/docker/ensure-network.ts

Comment thread knip.config.ts
Comment on lines +56 to +57
entry: ['src/**/*.test.ts'],
project: ['src/**/*.ts'],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add the runtime entrypoint to knip entries.

Line 56 only includes tests as entrypoints; src/server.ts should be listed too, otherwise knip can misclassify live service code as unused.

Suggested fix
     'services/sandbox': {
       // Standalone Bun HTTP service. Not in root workspaces (own bun.lock);
       // declare here so knip can resolve its entry points and ignore them
       // from the "unused" sweep.
-      entry: ['src/**/*.test.ts'],
+      entry: ['src/server.ts', 'src/**/*.test.ts'],
       project: ['src/**/*.ts'],
     },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
entry: ['src/**/*.test.ts'],
project: ['src/**/*.ts'],
entry: ['src/server.ts', 'src/**/*.test.ts'],
project: ['src/**/*.ts'],
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@knip.config.ts` around lines 56 - 57, The knip config's "entry" array
currently only lists test globs ('src/**/*.test.ts'), which can cause live
runtime files like src/server.ts to be treated as unused; update the
knip.config.ts "entry" to include the application's runtime entrypoint (e.g.,
add 'src/server.ts' to the entry array) so knip analyzes the live service code
when computing usage for the project.

Comment on lines +116 to +124
if (runStatus === 'failed' || runStatus === 'cancelled') {
return (
<Badge
variant="outline"
icon={AlertTriangle}
className="text-destructive border-destructive/40"
>
{runStatus}
</Badge>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Externalize run-panel labels and status text through i18n.

These strings are user-facing but hardcoded (Run, Files, stdout/stderr, chars, and raw runStatus). They should go through t(...) keys to avoid locale regressions.

As per coding guidelines: “No hardcoded user-facing strings; always use the translation hook.”

Also applies to: 183-185, 200-202, 211-213, 222-224

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@services/platform/app/features/chat/components/canvas/canvas-runnable-code-renderer.tsx`
around lines 116 - 124, The component currently renders hardcoded user-facing
strings (e.g., the raw runStatus value and labels like "Run", "Files",
"stdout/stderr", "chars") inside CanvasRunnableCodeRenderer (see use of
runStatus and Badge) — replace those with i18n keys by importing and using the
project's translation hook (e.g., t or useTranslations) and wrap each
user-facing string (including the run status output) with t(...) calls using
appropriate keys; update all occurrences noted (around runStatus rendering and
the label locations at the other listed blocks) so the Badge children and all
labels call t('...') instead of literal text, and ensure keys are descriptive
and added to the locale files.

Comment on lines +156 to +157
const outputFiles: RunOutputFile[] = (artifact?.runOutputFiles ??
[]) as RunOutputFile[];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Remove the as RunOutputFile[] cast and narrow with a typed validator/guard.

The cast can mask runtime shape mismatches from backend data; prefer a safe narrowing path before rendering.

As per coding guidelines: “Never use ‘as’, never ‘any’, never ‘unknown’; use type guards/generics/discriminated unions.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@services/platform/app/features/chat/components/canvas/canvas-runnable-code-renderer.tsx`
around lines 156 - 157, The current cast using "as RunOutputFile[]" on
artifact?.runOutputFiles can hide runtime shape mismatches; replace it by
implementing a type guard (e.g., isRunOutputFile and isRunOutputFileArray) that
validates each object's required discriminators/fields and use that guard when
assigning outputFiles (instead of the cast) so you assign
artifact.runOutputFiles only when isRunOutputFileArray(artifact.runOutputFiles)
is true, otherwise default to an empty array; add the guard functions near the
component (or in a shared validators file) and reference them from
canvas-runnable-code-renderer.tsx when computing outputFiles.

Comment on lines 24 to 33
export function isValidArtifactType(value: string): value is ArtifactType {
return (
value === 'html' ||
value === 'svg' ||
value === 'markdown' ||
value === 'mermaid' ||
value === 'code'
value === 'code' ||
value === 'python_runnable' ||
value === 'node_runnable'
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Derive isValidArtifactType from artifactTypeEnum to avoid drift.

The hand-maintained OR-chain duplicates enum values and can silently fall out of sync on future type additions.

Proposed change
 export function isValidArtifactType(value: string): value is ArtifactType {
-  return (
-    value === 'html' ||
-    value === 'svg' ||
-    value === 'markdown' ||
-    value === 'mermaid' ||
-    value === 'code' ||
-    value === 'python_runnable' ||
-    value === 'node_runnable'
-  );
+  return artifactTypeEnum.safeParse(value).success;
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/platform/convex/agent_tools/artifacts/shared.ts` around lines 24 -
33, The current isValidArtifactType function duplicates the ArtifactType values
with a manual OR-chain, risking drift; change it to derive validity from the
canonical artifactTypeEnum instead: import or reference artifactTypeEnum and
implement isValidArtifactType by checking whether value is a member of
artifactTypeEnum (e.g., using Object.values(artifactTypeEnum).includes(value) or
artifactTypeEnum.includes if it’s an array), keeping the function signature
isValidArtifactType(value: string): value is ArtifactType and ensuring the check
uses the enum’s runtime values so future enum additions are automatically
covered.

Comment on lines +234 to +238
try {
await fetch(url, { method: 'POST', headers, body });
} catch {
// Cancellation is best-effort; the watchdog cron will reap stuck rows.
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add logging to the catch block per coding guidelines.

The empty catch block silently swallows fetch failures. While the comment explains cancellation is best-effort, logging the error would help debugging stuck executions.

As per coding guidelines: "No empty catch blocks; log with console.warn/console.error or re-throw."

Proposed fix
   try {
     await fetch(url, { method: 'POST', headers, body });
-  } catch {
-    // Cancellation is best-effort; the watchdog cron will reap stuck rows.
+  } catch (err) {
+    // Cancellation is best-effort; the watchdog cron will reap stuck rows.
+    console.warn(`[spawner] cancel ${executionId} failed:`, err);
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
await fetch(url, { method: 'POST', headers, body });
} catch {
// Cancellation is best-effort; the watchdog cron will reap stuck rows.
}
try {
await fetch(url, { method: 'POST', headers, body });
} catch (err) {
// Cancellation is best-effort; the watchdog cron will reap stuck rows.
console.warn(`[spawner] cancel ${executionId} failed:`, err);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/platform/convex/node_only/sandbox/helpers/spawner_client.ts` around
lines 234 - 238, The catch block that wraps the fetch call to fetch(url, {
method: 'POST', headers, body }) currently swallows errors; update the catch to
log the error and context (e.g. URL and any identifying execution id) using
console.warn or console.error instead of leaving it empty, while keeping the
existing comment about best-effort cancellation; ensure the log includes the
error object so failures to POST cancellation requests are recorded for
debugging.

Comment on lines +250 to +252
const killTimer = setTimeout(() => {
void dockerKill(containerName).catch(() => {});
}, timeoutMs);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don’t silently swallow kill/cleanup failures.

If dockerKill, dockerRm, or rm fail, this leaves orphaned containers or session directories with no signal in logs or metrics. In a long-running spawner, that turns a recoverable cleanup problem into an invisible disk/slot leak.

Also applies to: 361-366

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/sandbox/src/spawn.ts` around lines 250 - 252, The current timeout
cleanup timers call dockerKill (and similarly dockerRm / rm in the other block)
and silently swallow any errors; update the handlers around setTimeout and the
cleanup callers (referencing the killTimer callback and the other cleanup block
that calls dockerRm/rm) to catch rejections and surface them: log the full error
via the service logger (include containerName/sessionDir context), increment a
cleanup-failure metric or counter, and optionally perform a best-effort retry or
escalate (e.g., schedule a single retry after a short delay) rather than
ignoring the failure. Ensure dockerKill, dockerRm and rm callers use .catch(err
=> { logger.error(..., err); metrics.increment('cleanup.failure'); /* optional
retry */ }) so orphaned containers/directories are visible in logs/metrics.

Comment on lines +43 to +57
const inspect = await runDocker(['volume', 'inspect', name]);
if (inspect.exitCode === 0) return; // already exists, already chowned

const create = await runDocker([
'volume',
'create',
'--label',
'tale.sandbox-cache=1',
name,
]);
if (create.exitCode !== 0) {
throw new Error(
`volume: failed to create cache volume ${name}: ${create.stderr.trim() || create.stdout.trim()}`,
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle concurrent first-create races for Docker volumes.

Line 43–57 has a check-then-create race. Two callers can both see “not exists”; one volume create will fail with “already exists”, which is currently treated as fatal.

Suggested fix
   const create = await runDocker([
     'volume',
     'create',
     '--label',
     'tale.sandbox-cache=1',
     name,
   ]);
   if (create.exitCode !== 0) {
+    const existsNow = await runDocker(['volume', 'inspect', name]);
+    if (existsNow.exitCode === 0) return;
     throw new Error(
       `volume: failed to create cache volume ${name}: ${create.stderr.trim() || create.stdout.trim()}`,
     );
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@services/sandbox/src/volume.ts` around lines 43 - 57, The current
check-then-create flow using runDocker allows a race where volume create can
fail with "already exists" and is treated as fatal; update the logic around
runDocker calls in this module (the inspect and create calls in volume.ts) to
treat a create failure that indicates the volume already exists as non-fatal:
after running the create command (the variable named create), if create.exitCode
!== 0 inspect create.stderr/create.stdout for the “already exists” message (or
Docker’s equivalent) and, if present, treat the operation as successful (return)
instead of throwing; only throw for genuine failures that are not the
already-exists case.

Comment on lines +87 to +92
docker network rm tale-sandbox-net >/dev/null 2>&1 || true
docker network create \
--internal \
--ipv6=false \
--driver=bridge \
tale-sandbox-net >/dev/null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid hard-failing when the sandbox network already exists.

Line 87–92 can fail under concurrent/local runs: if docker network rm is ignored (network still in use), docker network create ... tale-sandbox-net exits non-zero and the script aborts.

Suggested fix
-docker network rm tale-sandbox-net >/dev/null 2>&1 || true
-docker network create \
-    --internal \
-    --ipv6=false \
-    --driver=bridge \
-    tale-sandbox-net >/dev/null
+if ! docker network inspect tale-sandbox-net >/dev/null 2>&1; then
+  docker network create \
+      --internal \
+      --ipv6=false \
+      --driver=bridge \
+      tale-sandbox-net >/dev/null
+fi
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
docker network rm tale-sandbox-net >/dev/null 2>&1 || true
docker network create \
--internal \
--ipv6=false \
--driver=bridge \
tale-sandbox-net >/dev/null
if ! docker network inspect tale-sandbox-net >/dev/null 2>&1; then
docker network create \
--internal \
--ipv6=false \
--driver=bridge \
tale-sandbox-net >/dev/null
fi
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/container-smoke-test.sh` around lines 87 - 92, The docker network
create step can fail if the network already exists or is in use; make the setup
idempotent by checking for the network before creating or by swallowing
non-fatal create errors: use `docker network inspect tale-sandbox-net >/dev/null
2>&1 || docker network create --internal --ipv6=false --driver=bridge
tale-sandbox-net >/dev/null` or append `|| true` to the `docker network create
... tale-sandbox-net` call so the script does not hard-fail when the network
already exists or creation returns a non-zero status.

Comment on lines +119 to +127
function checkSandboxToken(env: NodeJS.ProcessEnv): Check {
if (!env.SANDBOX_TOKEN || env.SANDBOX_TOKEN.length < 32) {
return {
name: 'SANDBOX_TOKEN',
status: 'fail',
detail:
'missing or too short — required for HMAC auth between Convex and the sandbox spawner',
fix: 'Re-run `tale init` (or set a 64-char hex value manually)',
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

SANDBOX_TOKEN check severity conflicts with optional-token behavior.

This currently fails the whole doctor run when unset/short, but this PR explicitly makes SANDBOX_TOKEN optional. Downgrade to warn (or gate fail by mode) to avoid false hard failures.

Also applies to: 175-178

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/cli/src/commands/doctor.ts` around lines 119 - 127, The SANDBOX_TOKEN
check in function checkSandboxToken currently returns status: 'fail' when
missing/short which conflicts with the PR making SANDBOX_TOKEN optional; change
the returned status to 'warn' (or, if you want to keep fail behavior for certain
modes, gate the failure by checking the runtime mode/flag and only set status:
'fail' when that explicit mode requires the token). Update both occurrences of
this logic (the checkSandboxToken function and the similar check at lines
~175-178) so they return a warning message and appropriate fix text instead of
failing the entire doctor run unless explicitly required by mode.

Comment on lines +29 to +33
// Dev convention: publish 8003 to host loopback so `bun dev`'s local
// convex-local-backend (running on the host) can reach the spawner.
// Matches rag (8001) and crawler (8002). The `tale deploy` generator
// can omit this for hardened prod deployments — same as those services.
ports: ['8003:8003'],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Bind sandbox port to loopback explicitly.

ports: ['8003:8003'] exposes the spawner on all host interfaces, but the comment says loopback-only. With docker.sock mounted, this widens attack surface unnecessarily.

Suggested fix
-    ports: ['8003:8003'],
+    ports: ['127.0.0.1:8003:8003'],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Dev convention: publish 8003 to host loopback so `bun dev`'s local
// convex-local-backend (running on the host) can reach the spawner.
// Matches rag (8001) and crawler (8002). The `tale deploy` generator
// can omit this for hardened prod deployments — same as those services.
ports: ['8003:8003'],
// Dev convention: publish 8003 to host loopback so `bun dev`'s local
// convex-local-backend (running on the host) can reach the spawner.
// Matches rag (8001) and crawler (8002). The `tale deploy` generator
// can omit this for hardened prod deployments — same as those services.
ports: ['127.0.0.1:8003:8003'],
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/cli/src/lib/compose/services/create-sandbox-service.ts` around lines 29
- 33, The ports mapping currently uses ports: ['8003:8003'] which binds the
spawner to all host interfaces; change this to bind to loopback only by
replacing that entry with an explicit loopback host binding (e.g.,
'127.0.0.1:8003:8003') in the create-sandbox-service definition so the container
port 8003 is published only on localhost and reduces the exposed attack surface.

@larryro
larryro force-pushed the feat/sandbox-code-run branch from d906dd0 to cc5514a Compare May 20, 2026 02:47
larryro added 25 commits May 24, 2026 09:35
… proxy, spawner)

Container-side foundation for the `code_run` agent tool: an ephemeral
Python/Node sandbox the LLM can invoke to run code with arbitrary packages
and surface generated files (e.g. .pptx via python-pptx) as chat attachments.

Components:

- services/sandbox-runtime: lean Python 3.12 + Node 24 + uv image. Entrypoint
  installs requested packages on demand (`--only-binary=:all:` for pip and
  `--ignore-scripts` for npm by default — closes setup.py / postinstall ACE
  vectors per R2.7), emits PHASE markers for the chat UI, then execs user
  code at /workspace/code/main.{py,js}.

- services/sandbox-egress: tinyproxy sidecar on tale-sandbox-net (an
  internal-only Docker bridge). Filters CONNECT host requests against an
  allow-list (pypi.org, files.pythonhosted.org, registry.npmjs.org, github
  package endpoints). Replaces the originally-planned iptables IP allow-list
  which R1.3/R2.1 showed was unsafe due to shared Fastly/Cloudflare CDN IPs.

- services/sandbox: ~250 LOC Bun HTTP service. POST /v1/execute with
  HMAC-signed body spawns one ephemeral container; POST /v1/cancel/:id
  propagates AbortSignal as docker kill. Workspace is a per-call tmpfs
  Docker volume (size=256m, hard ENOSPC cap per R2.2); pip/npm caches are
  per-org named volumes (closes the R2.3 cross-tenant wheel-cache poison
  vector). docker_args.ts is a pure builder with strict regex validation;
  the #1 regression gate per R1.22 has 9 passing unit tests asserting the
  argv shape and that user code never reaches argv.

- compose.yml: registers both services and the internal `sandbox` network
  pinned to `tale-sandbox-net`. IPv6 disabled on the bridge to prevent
  v4-allowlist bypass via v6 routes (R1.3).

- .commitlintrc.json: add `sandbox` scope.

Convex schema, executeCode action, code_run tool, CLI compose generator
work, and tests follow in M2 and M3.

Plan: /home/larry/.claude/plans/presentation-generation-from-prompts-delightful-aho.md
…ine (M2)

Convex-side of the sandbox feature: a new code_run agent tool, the
sandboxExecutions audit table, and the executeCode internal action that
owns the spawner HTTP round-trip + transactional storage uploads.

Schema (services/platform/convex/sandbox/schema.ts):
- sandboxExecutions table — uploadedBy, agentSlug, lifecycleStatus,
  statusChangedAt, heartbeatAt, estimatedSeconds/actualSeconds, full
  output-files validator, structured errorCode taxonomy (R1.12 + R2.8).
- Indexes: by_organizationId_and_status (quota counting), by_org_user
  (GDPR cascade), by_status (watchdog), by_threadId, by_organizationId.

Mutations (services/platform/convex/sandbox/internal_mutations.ts):
- reserveSlotAndInsert — atomic concurrency-cap + daily-CPU-budget +
  audit-row insert in one mutation, closes the TOCTOU race R1.8/R1.10
  flagged. Uses the same withIndex pattern as video_links/mutations.ts.
- setRunning / heartbeat / finalize.
- recoverStuckSandboxes — watchdog cron flips rows older than
  2×max-timeout to failed/SPAWNER_UNAVAILABLE (Convex 30-min hard-kill
  skips action try/finally; mirrors recoverStuckTranscriptions pattern).

Node action (services/platform/convex/node_only/sandbox/internal_actions.ts):
- executeCode — reserves slot → resolves+validates inputFiles via internal
  query (IDOR check) → setRunning + 60s heartbeat loop → POSTs to spawner
  with HMAC-signed body → all-or-nothing storage upload (rolls back blobs
  on partial failure) → batched fileMetadata insert → finalize. Per
  feedback_no_empty_catch: infra failures throw, user-code failures return
  a structured {success:false, errorCode, ...}.

Tool (services/platform/convex/agent_tools/code/code_run_tool.ts):
- code_run — Python 3.12 + Node 24, packages on demand, inputFiles
  ref-by-fileMetadataId, allowSdist/allowInstallScripts opt-in overrides,
  full errorCode-recovery table in description, tool-selection precedence
  vs excel/pdf/docx/image (per R1.15).

Wiring:
- schema.ts registers sandboxExecutions.
- crons.ts adds 'recover stuck sandbox executions (every 5 min)'.
- soft_delete_validators registers 'sandboxExecution'; soft_delete_helpers
  maps it to the table + uploadedBy author field.
- tool_registry / tool_names register codeRunTool.

Tests + CLI integration (M3) follow.

NOTE: services/platform/convex/_generated/api.d.ts will regenerate on the
next `bunx convex deploy` / `tale start`; the typescript errors against
internal.sandbox.* in this commit are the documented stale-codegen state
from feedback_api_dts_autogenerated, not bugs.
…(M3)

CLI work to deploy the sandbox stack via `tale start` / `tale deploy`:

- ComposeService type extended with cap_add, mem_limit, pids_limit,
  ulimits, security_opt, runtime — previously absent from the generator
  which silently dropped these on the convex service.
- BONUS FIX surfaced by sandbox review (R1.17): create-convex-service.ts
  was shipping the production convex container WITHOUT NET_ADMIN, so
  services/convex/docker-entrypoint.sh:79 was silently logging "iptables
  present but no NET_ADMIN capability — SSRF firewall NOT installed" on
  every deploy. Apply the missing cap_add + mem_limit + pids_limit +
  ulimits flags so production deployments finally get the SSRF egress
  firewall the entrypoint was always trying to install.
- New service factories: create-sandbox-service (HTTP spawner, mounts
  docker.sock, two-network membership) and create-sandbox-egress-service
  (tinyproxy sidecar on the internal sandbox bridge).
- STATEFUL_SERVICES includes 'sandbox' + 'sandbox-egress' so the
  deploy.ts auto-include-missing-stateful logic picks them up on the
  next `tale deploy` after upgrade — no migration registry entry needed.
- ensureSandboxNetwork() creates `tale-sandbox-net` (fixed Docker name,
  --internal, --ipv6=false). Called from both start.ts (dev) and
  deploy.ts (prod) infrastructure setup.
- ensure-env: SANDBOX_TOKEN added to requiredVars + secretDefaults
  (auto-generated 32-byte hex). generateEnvContent emits SANDBOX_TOKEN +
  SANDBOX_RUNTIME / SANDBOX_EGRESS_ALLOWLIST comment block for operators
  to override.
- New command: `tale doctor` — preflight checks for sandbox host
  requirements (docker, /var/run/docker.sock, runsc registration with
  dockerd, userns-remap, AppArmor docker-default, SANDBOX_TOKEN
  presence). R1.17 surfaced that there was no `doctor` command at all;
  scope here is intentionally narrow (sandbox-relevant only) to avoid
  scope creep — future Docker version / disk headroom checks belong
  here too but separately.

CLI typecheck passes (`bunx tsc --noEmit`).

Next: tests (M3 test pass) + bun run check until green.
…ient

oxlint flagged 4 issues in M1/M2 code:

- spawner_client.ts:97 — `throw new Error(...)` inside `catch (err)` without
  forwarding the original. Added `{ cause: err }` so debugging keeps the
  network-error chain.
- internal_actions.ts:445 — same pattern; same fix.
- spawner_client.ts:113 — `await res.json() as SpawnerExecuteResponse`. Annotated
  with `oxlint-disable typescript/no-unsafe-type-assertion` because the wire
  contract is validated on the spawner side; trusting it here is by design.
- internal_actions.ts:177 — `err.data as { message?: string }`. Same disable,
  scoped to the line that runs only after a `'message' in err.data` narrowing.

The remaining lint error (lib/seo/integration.test.ts) predates this branch
and is unrelated to the sandbox work.
)

Mocks _generated/server.internalMutation so the real handler is callable
with a fabricated ctx (matches the file_metadata/internal_mutations.test.ts
pattern). Covers:

- Empty in-flight → row inserted with status='queued', lifecycleStatus='active'.
- Cap reached (4 running) → throws ConvexError (atomic concurrency cap,
  closes the TOCTOU race R1.8/R1.10 flagged).
- Daily CPU budget pre-debit overflow (4 × 500s prior + 30s requested >
  1800s cap) → throws — pre-debit semantics verified, closes R1.10's
  post-debit overshoot.
- recoverStuckSandboxes — only the row whose heartbeatAt is older than
  2×max-timeout gets flipped to failed/SPAWNER_UNAVAILABLE.

All 4 tests pass via vitest. Combined with the 9-test argv builder gate
shipped in M1, that's two of R1.22's five critical regression gates.
The remaining three (in-container privilege assertion, fileMetadata IDOR
via inputFiles, cancellation propagation) require either a running
docker daemon (privilege) or a Convex test harness (IDOR / cancellation);
both are integration-test scope and best added when wiring up CI for the
sandbox stack.
Five real bugs surfaced by trying to actually hit /v1/execute end-to-end:

1. **Docker CLI API skew (L3 /health 503)** — Debian's `docker.io` 20.10.5
   speaks API 1.41; modern daemons require ≥1.44. Switched to the official
   static CLI via `COPY --from=docker:27-cli` and changed /health from
   `docker info --format` (which panics in old CLI) to `docker version
   --format`.

2. **tmpfs Docker volumes aren't shared between docker run calls** — my
   original multi-helper staging (busybox containers writing to a shared
   workspace volume) silently failed because each `docker run` of a
   tmpfs-driver-local volume creates a fresh mount. Tried piping tar to
   stdin into the runtime container, but then…

3. **`docker cp` can't read from --tmpfs mounts** — verified directly: file
   present inside container (`docker exec ls`) but `docker cp` returns
   "Could not find the file ... in container". Switched workspace to a
   1:1 host bind mount under /var/lib/tale-sandbox/sessions/<uuid>/.
   Spawner now stages files via Bun fs (no busybox/tar dance) and harvests
   outputs the same way. The compose + CLI factory mount
   /var/lib/tale-sandbox into the spawner container at the same path so
   the docker daemon (resolving against host fs) and the spawner agree on
   it. Trade-off: lose the perfect tmpfs ENOSPC cap; keep --ulimit
   fsize=100m per file + post-run rm -rf.

4. **uv/pip fail under --read-only** — uv writes to $HOME/.cache/uv,
   nobody's $HOME is /nonexistent which is RO. Set HOME=/tmp (we have
   --tmpfs /tmp) + UV_CACHE_DIR=/cache/pip.

5. **Cache volume permission denied** — new Docker volumes are root-owned
   by default; the runtime user is 65534. ensureCacheVolume now detects
   first-creation and runs a transient busybox to chown the mount point
   65534:65534.

6. **Internal-only sandbox network blocks tinyproxy's own outbound** —
   sandbox-egress couldn't resolve pypi.org because `internal: true` cut
   all DNS too. Put sandbox-egress on BOTH `sandbox` (where runtime
   containers reach it) and `internal` (where it has internet for the
   upstream tunnel). Runtime containers stay solely on sandbox.

7. **Timeout didn't kill the container** — killing the docker CLI process
   doesn't stop the sibling container; it just disconnects the wrapper.
   Two-tier timeout now: inner timer issues `docker kill <name>` at
   timeoutMs; outer (CLI process kill) at timeoutMs+30s as belt-and-
   suspenders.

8. **Error classifier patterns stale** — uv's "no matching distribution"
   has become "unsatisfiable"; runtime-time egress denial exits with 1
   not 64. Broadened PACKAGE_NOT_FOUND regex; classify EGRESS_DENIED on
   any exit when stderr matches.

9. **tinyproxy log file root-owned** — entrypoint chowns the log to
   nobody so tinyproxy (which drops privs) can write to it.

L4 verified end-to-end:
- python hello world: 620ms
- python-pptx (warm cache): 1.18s, real .pptx file with 3 slides
- TIMEOUT: exit 137 at 3.27s for a sleep(30) with timeoutMs=3000
- EGRESS_DENIED, PACKAGE_NOT_FOUND, RUNTIME_ERROR: all classified
- HMAC mismatch: 401

api.d.ts regen picked up sandbox/* + agent_tools/code/* on the platform
restart that happened during testing — included.
The L4 spawner regex was UUID-only (hex + hyphens), but executeCode passes
the Convex audit row's _id (lowercase alphanumeric, base36-ish) as the
spawner executionId. Broaden both regexes to [a-zA-Z0-9_-]{1,64} — still
safe for Docker container names and argv positions, now accepts both
UUIDs and Convex ids.

L5 verified end-to-end: executeCode action via convex run produced a
real .pptx in 2.6s with audit row + fileMetadata row both populated.
…nt demo

- compose.yml + create-sandbox-service: publish 8003:8003 (same shape as
  rag/crawler dev convention). `bun dev` runs convex-local-backend on
  the host; without this the executeCode action can't resolve `sandbox`
  (Docker DNS). The tale-deploy generator can omit the port for hardened
  prod deployments — same option as rag/crawler.

- examples/agents/chat-agent.json: add `code_run` to toolNames; flip
  Rule 7's "do NOT produce .pptx — there is no PPTX export" line in
  EN / DE / FR system prompts to "for downloadable .pptx call code_run
  with python-pptx==1.0.2". HTML in-chat slide guidance via
  artifact_create is preserved as the in-chat default.

Verified end-to-end via host loopback: HMAC-signed POST to
127.0.0.1:8003/v1/execute produces a real .pptx in 2.3s.

Recipe for bun dev:
  1. .env has SANDBOX_TOKEN=<hex> and SANDBOX_URL=http://sandbox:8003
     (for the dockerized convex container).
  2. services/platform/.env.local has the same SANDBOX_TOKEN and
     SANDBOX_URL=http://127.0.0.1:8003 (sync-convex-env-from-dotenv
     applies higher priority for .env.local; bun dev's local convex
     backend picks up the loopback URL).
  3. `bun dev` from services/platform/.
When code_run finished it left the file as a fileMetadata row but never
attached it to the assistant message — so the LLM said "your pptx is
ready" and nothing appeared in the chat bubble. Mirror what excel/pdf/
docx tools do:

- insertOutputFiles + executeCode now thread storageId through to the
  tool layer (was only returning fileMetadataId).
- code_run tool calls appendFilePart(ctx, {fileName, mimeType,
  downloadUrl}) per output file, with downloadUrl built via
  buildDownloadUrl(storageId, name) — same helper excel_tool uses.

Verified: re-ran executeCode directly via convex run; the response now
carries storageId for each file. The chat-bubble attachment fires when
the tool is invoked through the agent loop (next chat send should show
the .pptx card alongside the LLM's text response).
bun dev surfaced this on first invocation:

  Uncaught Error: SANDBOX_TOKEN env var is required for sandbox/code_run;
  set it in .env
    at handler (.../convex/node_only/sandbox/internal_actions.ts:438:8)

bun dev's convex-local-backend runs on the host with whatever env it
gets from .env / .env.local. The hard throw in getSpawnerToken() turned
"forgot to set the secret" into "tool is dead." rag (8001) and crawler
(8002) both sit on the same internal Docker network with no auth and
just work; sandbox should match.

Auth is now opt-in. Both sides agree:

  unset on both          -> unsigned requests accepted; one-time boot
                            warning on the spawner
  set on spawner only    -> 401 (catches client/server config drift)
  set on client only     -> harmless (client signs, server ignores)
  set on both            -> HMAC required, mismatch = 401

tale init still auto-generates SANDBOX_TOKEN so prod stays HMAC-on by
default; this only removes the hard-error path when the secret happens
to be missing at runtime.

Files (4):
- services/sandbox/src/types.ts        sandboxToken: string | null
- services/sandbox/src/config.ts       drop requireEnv; treat "" as unset
- services/sandbox/src/server.ts       gate verify() on token !== null;
                                       warn once on boot in unauth mode
- spawner_client.ts                    drop throw; omit signature header
                                       when token is null

Verified:
- spawner with SANDBOX_TOKEN unset boots, logs the warning, accepts an
  unsigned POST and runs python in 482ms.
- spawner with SANDBOX_TOKEN set still returns 401 on bad/missing sig.
- 9 argv unit tests still pass.
…r bun dev)

User's `bun dev` action threw `fetch failed: sandbox:8003` because the
client defaulted to the Docker DNS name. From the host, that doesn't
resolve.

The convention rag and crawler follow is the inverse:
  - Code default = http://localhost:<port>  (works for bun dev with
    published ports)
  - services/platform/env.sh sets the docker DNS as the default for
    in-container processes, e.g. RAG_URL="${RAG_URL:-http://rag:8001}".
    The platform docker-entrypoint sources env.sh and then convex env
    sets the value into the convex backend, so dockerized actions see
    the docker name.

Two changes:

- spawner_client.getSpawnerUrl() defaults to http://localhost:8003.
- services/platform/env.sh adds SANDBOX_URL="${SANDBOX_URL:-http://sandbox:8003}"
  next to RAG_URL / CRAWLER_URL / SEARCH_SERVICE_URL.

Net effect:
  bun dev (host node)          → code default localhost:8003 → works
                                  zero-config via the published port
  dockerized convex (in compose) → env.sh default sandbox:8003 → works
  operator override (either)   → SANDBOX_URL in .env / .env.local /
                                  docker compose environment block
                                  takes precedence

Sandbox argv unit tests (9) still pass.
Foundation for folding code_run into the artifact system (plan
Refinement 2). The sandbox execution layer is unchanged behaviorally;
the wire protocol grows phase events so the canvas can show live
progress, and the artifacts schema grows run-state fields so a runnable
artifact's row holds its current execution state.

Schema (artifacts/schema.ts):
- type union gains `python_runnable` + `node_runnable`
- run-state fields (all optional — non-breaking per
  feedback_deprecate_dont_delete_schema_fields):
  runPackages, runOptions, runStatus (queued|installing|running|
  completed|failed|cancelled), runProgress, runStartedAt, runCompletedAt,
  runExitCode, runErrorCode, runErrorMessage, runStdoutPreview/StorageId,
  runStderrPreview/StorageId, runOutputFiles, runExecutionId

Mutations (artifacts/internal_mutations.ts):
- initArtifactRun: set runStatus='queued' + clear prior-run remnants
- patchArtifactRunProgress: mid-flight status/progress updates fired
  on PHASE events from the spawner
- finalizeArtifactRun: write final exit code + output files + clear
  the live progress string

Spawner (services/sandbox/src/):
- spawn_util.runDocker now accepts onStdoutChunk callback that fires
  per chunk during the docker run (vs after exit).
- spawn.executeRequest accepts ExecuteRequestOptions.onPhase and runs
  a line-buffered parser over the stdout chunks; PHASE: installing /
  PHASE: running lines fire the callback with {phase} events.
- server /v1/execute switches from buffered JSON response to SSE:
  emits 'event: phase data: {...}' per phase + final
  'event: result data: {...full response...}'.

Verification:
- 9 argv unit tests still pass.
- bun run typecheck clean.
- curl smoke against rebuilt container: SSE stream emits two phase
  events ('installing', 'running') then the final result event with
  a real .pptx in outputFiles.

M5b will switch the convex spawner_client to a streaming consumer and
wire artifact_create / artifact_edit to call executeCode for runnable
types.
…r runnable types (M5b)

Builds on M5a's schema + SSE foundation. The agent-facing tool surface
is now the artifact pair (create/edit); the sandbox spawner stays
unchanged and is invoked transparently when an artifact's type is
runnable.

- spawner_client.spawnerExecute now consumes the SSE stream from the
  spawner. Phase events fire an optional onPhase callback; the final
  `event: result` payload is returned as the same SpawnerExecuteResponse
  shape callers had before (drop-in replacement; signature gained an
  optional `callbacks` arg).
- spawner_client also exposes an SSE event parser that tolerates partial
  reads and chunk boundaries.

- executeCode internal_action gains optional `artifactId`. When set:
  - onPhase fires patchArtifactRunProgress with a human-readable
    progress string ("Installing python-pptx" / "Running code") so the
    canvas runnable-code-renderer can subscribe and show live state.
  - On success, finalizeArtifactRun writes runStatus=completed plus
    exit code, stdout/stderr previews, and runOutputFiles. The audit
    sandboxExecutions row still gets its own forensics; the artifact
    row holds the latest result for fast canvas reads.

- artifact_create_tool:
  - shared.ts adds runnable types to the enum + isRunnableArtifactType /
    runnableLanguage helpers.
  - input schema gains optional `packages`, `allowSdist`,
    `allowInstallScripts`, `timeoutMs` (gated semantically on runnable
    types).
  - execute(): after the canonical content settle, runnable types
    call initArtifactRun then executeCode with the new artifactId so
    the spawner streams progress straight to the artifact row.

- artifact_edit_tool:
  - both patch and rewrite success branches call a new local
    maybeRerun() helper. For runnable types this reloads the row to
    pick up runPackages/runOptions captured at create time, fires
    initArtifactRun to clear prior-run remnants, then re-invokes
    executeCode with the new content.
  - LLM can iterate via small patches without re-emitting the full
    script; canvas subscribes to the same artifact row and updates.

The `code_run` standalone tool still exists; M5c will remove it and
update the demo agent / system prompt to point at the unified path.
…/ node_runnable (M5c)

remove the standalone code_run tool in favor of two new artifact types
(python_runnable, node_runnable) so sandbox code execution shares the
artifact tool surface: live source streaming in the canvas pane, patch /
rewrite edit semantics for multi-turn refinement, and LLM context-aware
iteration via build_artifacts_context.

- canvas: new canvas-runnable-code-renderer with source on the left and
  status chip + file chips + collapsible stdout/stderr on the right;
  canvas-pane routes python_runnable / node_runnable to it
- context: build_artifacts_context surfaces runStatus / runErrorCode /
  runOutputFiles attributes for runnable types so follow-up turns pick
  the right next action (patch on failure, leave alone on completion)
- agent: chat-agent.json EN/DE/FR rule 7 points at artifact_create with
  type "python_runnable" instead of code_run
- registry: drop code_run from tool_names / tool_registry and remove the
  tool source file
artifact_create for python_runnable / node_runnable types was crashing
the chat with "Element type is invalid: ... got: undefined" because
ArtifactBar's TYPE_ICONS and message-bubble's ARTIFACT_PILL_ICONS only
had entries for the original five canvas types. tsc didn't catch this
because the artifact row reaches them as `any` through useQuery.

also store storageId alongside fileMetadataId on artifact runOutputFiles
so the canvas right-pane file chip can build a download url without a
second roundtrip (api.file_metadata.queries.getById doesn't exist).
…tool results

before this fix, artifact_create and artifact_edit awaited executeCode for
runnable types but discarded the entire run outcome — they only returned
{success: true, artifactId, revision, message} to the llm. so a python
script that exited with RUNTIME_ERROR still showed up as a successful
tool call and the llm happily told the user "文件已生成" while no file
existed.

now both tools forward the run outcome to the llm for runnable types:
runStatus, runExitCode, runErrorCode, runErrorMessage, runStdoutPreview,
runStderrPreview, durationMs, files[], executionId. tool-level success
is redefined for runnable types as (runStatus === 'completed' && files
.length > 0) so the llm can branch correctly. the tool description gains
an errorCode recovery table and an explicit "never say file generated
unless success === true && files.length > 0" guardrail. chat-agent rule
7 EN/DE/FR gain the same checkpoint.

canvas right pane and build_artifacts_context were already showing the
failure state correctly — this aligns the llm's reply with what the user
sees in canvas.
…nderer

users reported that after a python_runnable artifact finishes, the
download chip and run status were nowhere to be seen on the canvas.
root cause: the canvas-pane keeps `showStreamingSource=true` for 10s
after stream start (MIN_SOURCE_VIEW_MS dwell window), and during that
window the source-only branch runs first — it knew nothing about
runnable types and just rendered raw source via CanvasCodeRenderer,
bypassing the runnable renderer with its file chips / status panel.

route runnable artifacts to CanvasRunnableCodeRenderer regardless of
the streaming-source dwell. the renderer now also handles its own
`isStreaming` so the source view still renders with the streaming caret
during the source phase, while the run panel updates reactively from
the artifact row.

additionally, the runnable renderer stacks at narrow canvas widths.
moved the execution panel ON TOP of the source for narrow canvases
(default 480px, below md breakpoint) so the file chip is visible
immediately. on wide canvases (≥768px) the side-by-side layout is kept.
…p md: layout switch

the responsive md:flex-row split was based on viewport width, not canvas
pane width, so a typical 1536px viewport with a 480px canvas triggered
md: mode and tried to side-by-side the panel — but the panel's md:w-80
(320px) plus a flex-1 source ate the whole canvas and squeezed the run
panel out of layout (height=0, width=0 confirmed via getBoundingClientRect).

simpler: always stack execution panel on top, source below. canvas pane
max width is 900px anyway, so side-by-side was cramped even when it did
fit. tailwind container queries would be the responsive answer but a
simple stack is fine here.

also add the canvas.runDone i18n key in en/de/fr that the renderer was
referencing (was leaking the raw key into the ui).
… the race to execute

artifact_create's onInputDelta inserts a placeholder row (toolCallId
recorded, liveStreamMode='create', empty content) and only sets
state.artifactId AFTER the mutation roundtrip returns. when the model
finishes streaming the input fast enough, the AI SDK fires `execute`
before that mutation roundtrip lands — state.artifactId is still
undefined, so execute falls through to the createArtifact else branch
and inserts a SECOND row with full content. result: two artifacts for
one tool call, one empty + one settled, showing up in the artifact bar
as two duplicate-titled v1 tabs.

defensive fallback: in execute's else branch, before inserting a new row,
look up any in-flight create-placeholder for this toolCallId scoped to
org+thread. if found, finalize THAT row instead of inserting fresh. the
new internal query findStreamingPlaceholderByToolCallId is scoped tight
enough that it can never claim a settled or cross-conversation artifact.

no schema change. lookup runs only on the rare fallback path so the
extra (indexless) toolCallId filter inside the org-and-thread index walk
is fine — the thread's recent artifact set is small.
…n tool

artifact_create and artifact_edit for python_runnable / node_runnable
now behave like static types — they only write / patch the source row.
they no longer await executeCode, no longer surface a run outcome, no
longer auto-run. the new artifact_run tool is the explicit, llm-driven
trigger to execute the script: it reads the row's persisted runPackages
/ runOptions, calls executeCode, and returns the full run outcome
(runStatus, runErrorCode, runStderrPreview, files[], executionId, ...).

why split it out: real chat smoke showed the llm keeping calling
artifact_create on a fresh thread when a run failed — three duplicate
v1 tabs of "大熊猫介绍 PPTX" accumulating, never invoking artifact_edit.
the unified semantics conflated "author source" with "execute it" and
the natural llm recovery from a failed run was to create a new artifact.
making execution its own tool decouples the two decisions so the llm's
next-action decision tree narrows correctly:
- need to make a deck → artifact_create (no auto-run)
- need to run it → artifact_run(artifactId)
- run failed → artifact_edit(artifactId, patch) → artifact_run again

chat-agent.json rule 7 (EN/DE/FR) is rewritten to walk this 4-step
cycle and to explicitly forbid calling artifact_create twice for the
same request.

no schema change, no spawner change, no executeCode action change,
no canvas change. the toolCallId race-recovery from a18b5eb stays.
runPackages / runOptions are still persisted on the row via the
existing initArtifactRun mutation, called once at create time so
artifact_run picks them up automatically.
before this patch:
- during artifact_create streaming, the canvas right panel showed a bare
  "RUN" header with nothing beneath it (no status, no files, no errors)
  because the artifact row has no run state yet — looked broken.
- after artifact_create settled, the panel filled with a stale "queued"
  status that never resolved, because artifact_create called
  initArtifactRun which forces runStatus='queued' as a side-effect of
  persisting the run config — but with the split flow no run actually
  gets queued until artifact_run is invoked.

split initArtifactRun into two:
- new setArtifactRunConfig — only persists runPackages / runOptions
  (called by artifact_create after the source settles).
- existing initArtifactRun — persists config AND resets runStatus to
  'queued' (called by artifact_run immediately before executeCode, same
  as today).

canvas renderer now hides the execution panel entirely while runStatus
is undefined and no prior-run artefact (files / stderr / errorCode) is
present. once artifact_run kicks off, the panel re-appears with live
status. completed-state artifacts still show the panel + file chips as
before.
…t duplicate rows

artifact_create's onInputDelta was running this guard:

  if (!state.rowInitialized && ...) {
    const inserted = await ctx.runMutation(createArtifact, {...});
    state.artifactId = inserted.artifactId;
    state.rowInitialized = true;  // ← set AFTER the await
    ...
  }

the AI SDK dispatches input-deltas back-to-back without waiting for the
prior handler's promise to settle. when two deltas arrive while the
first createArtifact mutation roundtrip is still in flight, BOTH delta
handlers observe `state.rowInitialized === false`, both pass the guard,
and both insert placeholder rows. user ends up with two `v1` tabs of
the same title in the artifact bar — one empty, one finalized — for a
single observed artifact_create tool call.

flip `state.rowInitialized = true` synchronously immediately after the
guard passes, before awaiting the mutation. the second delta now sees
the guard closed and skips the insert. supersedes the toolCallId
race-recovery from a18b5eb for this particular case (that fix was
designed for a different race — state.artifactId being undefined when
execute fires; this is the simpler in-handler check-then-act). the
race-recovery in execute stays for the residual case of execute firing
before the placeholder mutation lands.
- Break a self-referential Convex type in `executeCode` that resolved to
  `any` and cascaded 130+ implicit-any errors across the platform: type
  the handler return explicitly and use `Id<'sandboxExecutions'>` instead
  of `Awaited<ReturnType<typeof ctx.runMutation<...>>>`.
- Replace narrowing `as` casts in new sandbox code with type guards
  (artifact-type set, SSE phase, JSON parse) so oxlint stops flagging
  them.
- Register `services/sandbox` as a knip workspace; drop `export` from
  helpers only used in their own file; delete the unused
  `removeVolume` / `harvestOutput` / `CancelResponse` exports.
- Pre-create `tale-sandbox-net` in the smoke-test script (it's external
  in compose.yml; the CLI owns its lifecycle, the smoke script didn't).
  Tear it down in cleanup.
- Anchor the service-image grep in the smoke + validate-images scripts
  to `/tale-${service}:` so `db` no longer matches `tale-sandbox-egress`
  via the `db` substring in `sandbox`.
- Suppress AVD-DS-0002 on the two new Dockerfiles that legitimately run
  as root (sandbox spawner needs the docker socket; sandbox-egress
  entrypoint chowns the log before tinyproxy drops privs).
The previous attempt used inline `# trivy:ignore:AVD-DS-0002` comments
before `FROM` in services/sandbox{,-egress}/Dockerfile, but the misconfig
scanner reports these whole-file rules at line 1 and does not honor
adjacent-line ignores for them — the alerts kept firing on the PR.

Switch to `.trivyignore.yaml` with per-path scoping so each suppression is
narrowly targeted and documented (statement field), and wire the file into
the security.yml Trivy step via `trivyignores:`. Per-path beats `.trivyignore`
plaintext, which would mask the same finding across every Dockerfile.

Also suppress AVD-DS-0026 (no HEALTHCHECK) on sandbox-runtime: it is an
ephemeral one-shot image — the spawner runs it per code_run call, the
entrypoint executes user code, and the container exits.

Image-level scans in build.yml run `vuln,secret` by default (no misconfig),
so no change is needed there.
Closes ~all P0/P1 findings from the two-round /tmp/sandbox-review pass.

Security / control plane
- create-sandbox-service.ts binds the spawner to 127.0.0.1 (was 0.0.0.0)
  — docker.sock + unsigned-token would have been remote-root.
- server.ts now exits at boot when SANDBOX_TOKEN is unset, unless the
  operator sets SANDBOX_ALLOW_UNAUTH=true. ensure-env auto-mints the
  token; tale doctor's required-token check matches the runtime contract.
- server.ts caps /v1/execute body at 256 KB, validates executionId
  before registering it, and the cancel route regex now matches the
  Convex doc-id alphabet (was UUID-only). req.signal aborts now drive
  cancelExecution so a closed SSE stream tears the container down.
- seccomp.json was a 3-line stub that nothing wired up; deleted.

Egress
- tinyproxy.conf.template gains Allow ACLs + DisableViaHeader Yes +
  AnonymousHeader stripping XFF/Forwarded/Via/From.
- entrypoint.sh installs iptables REJECT rules for 169.254.169.254 and
  RFC1918 ranges (mirrors services/convex/docker-entrypoint.sh).
- Dockerfile + healthcheck switched to a CONNECT probe that fails when
  the allowlist is broken; cap_add: [NET_ADMIN] added.
- Egress runs on sandbox + internal — internal provides the NAT path
  (tale-sandbox-net is --internal) without weakening the hostname-only
  exposure (peers can already reach pypi directly via their own NAT).

Spawner runtime correctness
- cancelExecution wraps dockerKill in a 5s timeout with SIGKILL
  fallback so a wedged daemon never hangs the HTTP cancel response.
- SIGTERM handler stops accepting requests, aborts in-flight executions,
  and drains for up to 20s before exit (was process.exit(0)
  unconditionally — was leaking /var/lib/tale-sandbox/sessions/<id>/).
- Dead volume sweep removed (it filtered tale.sandbox=1 on volumes that
  never exist; per-execution storage is a host bind mount, cache
  volumes are tale.sandbox-cache=1 and must NOT be reaped). Replaced
  with a host-dir mtime sweep over the session root.
- stdout phase parser drains lineBuf on EOF; the final unterminated
  PHASE: line no longer leaks into user-visible stdout.
- Six empty catch() blocks across spawn.ts / spawn-util.ts /
  spawner_client.ts / internal_actions.ts replaced with console.warn
  + cause (AGENTS.md no-empty-catch rule).
- numEnv rejects whitespace-only and negative values; SANDBOX_PORT
  range-checked.
- Filenames in services/sandbox/src/ migrated to dash-case
  (docker-args.ts, spawn-util.ts) per AGENTS.md.

Convex state machine
- sandbox/internal_mutations.ts: finalize early-returns when the row
  is already terminal (closes the watchdog-vs-action race that was
  clobbering SPAWNER_UNAVAILABLE audit data); setRunning is monotonic
  across queued → installing → running; watchdog sweeps queued AND
  installing AND running rows past the cutoff (a throw between
  reserveSlotAndInsert and setRunning no longer leaks a quota slot
  forever).
- node_only/sandbox/internal_actions.ts: one failExecution helper
  consolidates the six prior failure exits. It finalizes the audit row
  AND finalizeArtifactRun (so the canvas spinner can no longer hang
  forever) AND cascade-deletes any _storage blobs uploaded for the
  doomed run. INPUT_REJECTED replaces the misleading
  SPAWNER_UNAVAILABLE code for IDOR-rejected input paths. The
  AbortController is now actually .abort()ed in finally.
- artifacts/internal_mutations.ts: patchArtifactRunProgress and
  finalizeArtifactRun gain terminal-status guards mirroring the audit
  side. initArtifactRun no longer hard-patches runPackages /
  runOptions — the artifact_run tool's per-call overrides stay
  per-call (was contradicting its own documentation).

Wire-shape consolidation
- New convex/sandbox/wire.ts is the single source of truth for
  error-code / run-status / phase / output-file validators + literal
  arrays (pattern matches convex/tts/error_codes.ts). sandbox + artifact
  schemas + internal mutations + action + spawner_client all import
  from it. The 9-member errorCode union previously copied 6 times
  is now defined once; INPUT_REJECTED added.
- services/sandbox/src/wire.ts is the spawner-side mirror (the spawner
  cannot import from Convex). Centralized ID alphabet regex shared by
  server.ts / spawn.ts / docker-args.ts / volume.ts.
- runProgress changes from a server-authored English string to a
  structured { kind, package?, version? } shape so the UI can render
  localized text via ICU. en/de/fr message files gain the full
  chat.canvas.runStatus.* / runErrorCode.* / runProgress.* /
  typeLabel.* key set; keys-dynamic.txt registers the four enum-driven
  prefixes.

Agent tool surface
- artifact_create_tool deletes the ghost timeoutMs field (artifacts
  schema has no runTimeoutMs column; was silently dropped) and the
  unused ArtifactCreateRunOutcome interface.
- artifact_run_tool removes the inlined Chinese description example
  per feedback_no_locale_terms_in_tool_descriptions; the try/catch
  now wraps runQuery (where v.id() throws) instead of toId (which is
  a pure cast).
- Stale code_run literals across services/sandbox/package.json,
  sandbox-runtime/Dockerfile, doctor.ts, ensure-env.ts replaced with
  artifact_run.

Soft-delete unregistration
- sandboxExecution is audit-only; the half-wired soft-delete plumbing
  (no by_org_lifecycleStatus index, not in TRASH_VISIBLE_RESOURCE_TYPES,
  no fetchTrashSubpage case, no retention cleanup, no storage cascade)
  is removed cleanly along with the lifecycleStatus field and the
  unused by_org_user / by_threadId indices.

UI / i18n
- canvas-runnable-code-renderer routes every user-visible string
  through useT('chat'). The renderer reads runProgress.kind/package/
  version and lets ICU format the localized text.
- New canvas/icon-map.ts consolidates the per-artifact-type Icon
  Record that lived in three places (artifact-bar.tsx, canvas-pane.tsx,
  message-bubble.tsx) with a drift between them; TYPE_LABEL_KEYS,
  TYPE_EXTENSIONS, TYPE_MIME_TYPES also moved.

CI / images / smoke
- build.yml + cleanup-pr-images.yml matrices add sandbox, sandbox-egress,
  and sandbox-runtime — none of which were built before this commit
  (first tale deploy would have failed at the first artifact_run call
  with image-not-found).
- spawner calls ensureImage(cfg.runtimeImage) at boot, with retry.
- tests/container-image-test.sh and container-smoke-test.sh include
  the three new images; the smoke now exercises a signed
  POST /v1/execute end-to-end probe.
- sandbox-runtime/entrypoint.sh stops writing the write-only
  install-report.json + install-stdout.log files.

Build / test loop
- services/sandbox added to root workspaces (was outside bun run check
  reach). Renamed to @tale/sandbox; lint/format scripts added.
- Dockerfile multi-stage with literal bun.lock + --frozen-lockfile
  --production; non-root user where docker.sock permits.
- New services/sandbox/src/server.test.ts (21 tests) covers
  cancel-route regex, loadConfig fail-closed defaults, HMAC verify.
- knip.config.ts entry for services/sandbox now anchors on src/server.ts.

Verification
- bun run check: 44/44 tasks, 70 661 platform tests pass, knip clean.
- services/sandbox: 21 tests pass.

Plan: /home/larry/.claude/plans/plan-issues-glistening-peach.md
Review reports: /tmp/sandbox-review/round{1,2}/
larryro added 17 commits May 24, 2026 09:35
The platform forwards prior-run output files (base64-encoded, up to
10 MB raw / ~13.5 MB after base64 inflation) inline in the request
body so the spawner can pre-stage them for the next run. The previous
256 KB cap was sized for "agent-authored code + small input file set"
and never accounted for binary artifact outputs (PPTX/PDF/images)
getting fed back in, so re-running any artifact that had already
produced a non-trivial output file failed with HTTP 413
"sandbox spawner refused payload — request body exceeds spawner cap".

20 MB aligns with the upstream priorOutputFiles cap
(MAX_PRIOR_OUTPUT_BYTES = 10 MB) after base64 overhead plus room
for source files + JSON wrapper. Still sits well below the spawner
container's 512 MB mem_limit so a single oversized POST cannot OOM
the process — the original DoS-guard intent is preserved.
…oads work

`listRunsPerFile` was projecting `sandboxExecutions.outputFiles` straight to
the canvas, but that field is the audit row and intentionally omits
`storageId`. <FileChip>'s `useFileUrl(storageId)` therefore returned null,
leaving `<a href="#">` and a non-functional download button.

Look up `storageId` per file via `fileMetadata` after the pure projection
runs. Keeps `selectRunsPerFile` synchronous (unit tests unchanged) and
fixes existing rows without a backfill.
…in one project)

A single artifact can now carry .py and .js files together. The agent
runs each step with its native interpreter, and the sandbox installs
both pip and npm dependencies in one container.

Wire / sandbox changes:
- `polyglot` language literal added to wire schema (both sides) with
  parity assertions
- `packagesByLang: {python?, node?}` accepted alongside the legacy flat
  `packages` field; spawner stages packages-python.json /
  packages-node.json when polyglot
- entrypoint.sh gets a `polyglot` branch that runs both `uv pip
  install` and `npm install` (skipping empty buckets) then execs a
  Python dispatcher wrapper that subprocesses python3 / node per step
  by extension
- spawner validator rejects polyglot steps with unsupported extensions
  upfront (only .py / .js / .cjs / .mjs)
- runtime image (Dockerfile) unchanged — both interpreters were
  already present

Platform / agent-tool changes:
- New `script_runnable` artifact type in schema + Zod enum; legacy
  `python_runnable` / `node_runnable` literals retained for
  read-validator compatibility per the deprecate-don't-delete rule
- `inferStepLanguage(path)` + `runtimesForFiles(paths)` helpers
- `artifact_run_tool` collects per-step runtimes and picks
  python / node / polyglot for the wire; refuses mixed runs in
  single-script mode with a clear diagnostic
- `artifact_create_tool` exposes only `script_runnable` to the LLM
  (legacy types still readable but not creatable)
- `artifact_packages_add` + create accept grouped `{python, node}`
  packages; mirror the locked-runtime bucket to legacy `runPackages`
- Defensive parser `classifyPackages(specs, defaultLang)` strips
  `python:` / `pip:` / `node:` / `npm:` prefix tags from flat-array
  inputs so an agent that sends `["python:markitdown[pptx]",
  "pptxgenjs"]` no longer ships `python:markitdown[pptx]` to npm and
  trips EUNSUPPORTEDPROTOCOL
- Canvas frontend learns the new type (icon, label, file-extension-
  driven highlighter); en / de / fr message catalogs add the label

Tests:
- 8 new `classifyPackages` cases + 12 `inferStepLanguage` /
  `runtimesForFiles` / `defaultEntryFileFor` cases (vitest)
- 4 new spawner validator cases (polyglot accept, bad-extension reject,
  steps-required, combined packagesByLang cap)
- New spawn-staging case for polyglot wrapper + packages-*.json layout

Verification: `bun test` (sandbox: 92 pass), `npx vitest run` (platform
artifacts: 26 pass), `npx tsc --noEmit` clean. One pre-existing
no-map-spread lint warning in convex/artifacts/queries.ts predates this
branch and is unrelated.
…thon, node} only

The previous design accepted both `packages: string[]` (flat) and
`packages: {python, node}` (grouped). LLMs reliably picked the shorter
flat form and then mis-routed Python specs to npm (e.g.
`markitdown[pptx]` → EINVALIDTAGNAME) or vice versa. Defensive
heuristics could paper over each new failure mode but the underlying
design — letting the agent choose between two shapes for the same
thing — kept generating new ways to fail.

Forcing the grouped form removes the choice. The agent declares
which bucket each spec belongs to at the input layer; the tool no
longer has to guess.

Tool surface changes (all three artifact_* runnable tools):
- `artifact_create.packages`: `z.object({python?, node?})` only
- `artifact_run.packages`: same shape, optional one-shot override
- `artifact_packages_add.packages`: same shape, refined to require
  at least one bucket non-empty
- Tool descriptions updated with concrete `{python, node}` examples
  for python-only / node-only / mixed cases; no more "flat OR object"
  prose

The `classifyPackages` helper survives as a legacy-data safety net:
old `runPackages` flat rows (including any with `python:`/`node:`
prefix tags) are still classified correctly on read by artifact_run.
New writes always go through the grouped persistence path.

`shared.ts` heuristics (added in this branch):
- `[` in spec → python (pip extras; npm package names disallow `[`)
- `^@scope/...` → node (npm scoped package)
These only fire on the legacy flat fallback path; new inputs are
already disambiguated.

Verification: `npx tsc --noEmit` clean, 26 artifact agent_tool vitest
cases pass, 92 sandbox bun tests pass, lint clean for this diff
(pre-existing no-map-spread in convex/artifacts/queries.ts predates
the branch).
…fact files

`getLatestRunOutputs` returned the chronologically-most-recent
`completed` artifactRuns row and used its `artifactRunFiles` verbatim,
even when that list was empty. A qa-only run that exits 0 without
writing to /workspace/output/ therefore shadowed an earlier generator
run that wrote (e.g.) WISeKey-Introduction.pptx — the next
`artifact_run` on the same artifact got nothing pre-staged and the
script hit FileNotFoundError on a file the canvas was still showing.

Walk the `completed`-run chain newest-first and return the first run
that actually produced files. Bounded scan (50 runs) to keep the
worst case predictable. Matches user intuition: "the artifact's PPTX
should stay accessible across iterations regardless of whether the
last run happened to be a no-output QA pass."

Also surface a stderr note when pre-stage finds candidate filenames
in `artifactRunFiles` but the `_storage` blob is missing — that path
was silent before, so a regression there left users guessing.

Verification: `npx tsc --noEmit` clean. The walk-back path is exercised
implicitly by any artifact with a generator + multiple QA iterations;
no new unit test was added because `internalQuery` callers go through
the action layer and the existing pre-stage integration tests would
need a dedicated harness setup to mock storage.
…legacy outputs on empty harvest

Two-bug compound regression in the pre-stage path for follow-up
`artifact_run` calls:

1. `getLatestRunOutputs` walked back through `completed`-status runs
   only. A multi-step run that partially succeeded (main.js wrote a
   pptx, then qa.py crashed) lands as `status: 'failed'` overall but
   the pptx is real and IS in `artifactRunFiles` — the walk-back
   skipped it.

2. `applyFinalizeArtifactRun` rewrote the legacy
   `artifacts.runOutputFiles` field whenever the run status was
   `completed`, regardless of whether the harvest produced files. A
   `qa.py`-only run that exits 0 with no /workspace/output/ writes
   thus blanked the legacy field, defeating the fallback path too.

Together: a generator-then-validator workflow that ever produces a
partial-success run leaves no path back to its output for the next
`artifact_run`'s pre-stage. The user sees `FileNotFoundError` on a
file the canvas is still happily showing.

Fixes:
- Walk-back is now status-agnostic. `artifactRunFiles` is append-only
  and only carries files that survived harvest + storage upload, so
  the presence of a row IS the "this file was really produced" signal.
  Whether the surrounding run ultimately exited completed / failed /
  cancelled doesn't change that signal.
- Legacy `artifacts.runOutputFiles` is only written when
  `runOutputFiles.length > 0`. Empty harvests preserve whatever the
  prior run left there — the same rule that already protected
  failed / cancelled runs now applies to completed runs too.

Other run-row fields (`runStatus`, error code, progress, ...) keep
their existing "latest run wins" semantics — only the cumulative
output reference is now sticky.

Tests: 5 new `getLatestRunOutputs` cases via vitest mock
(failed-with-files vs latest-completed-empty, cascade across
failed+cancelled+completed-empty, legacy fallback, none case, IDOR
scope). `npx tsc --noEmit` clean; lint clean for this diff
(pre-existing `no-map-spread` in convex/artifacts/queries.ts predates
the branch).
…end-to-end

Spawner's POST /v1/execute validator returns the canonical request shape
via an explicit allowlist:

  return {
    request: {
      executionId, organizationId, language, files,
      ...(packages !== undefined && { packages }),
      ...(steps !== undefined && { steps }),
      ...
    },
  };

`priorOutputFiles` was never in that allowlist. The Convex action's
upstream pre-stage payload was therefore SILENTLY DROPPED before
spawn.ts read it — `req.priorOutputFiles` was always `undefined`, and
`stageWorkspace` never wrote anything to /workspace/output/. Every
"the script can't find the pptx I just generated" report this debugging
session traced back to this. The platform-side walk-back fixes from
prior commits were computing the right candidates but no candidate
ever reached the host bind-mount.

Fixes:
- Add `priorOutputFiles` validation in validate-request.ts (array of
  `{name: string, contentBase64: string}`) and include it in the
  returned request shape.
- Add INFO logs that make pre-stage observable end-to-end:
  - `[sandbox.preStage] source=... candidates=N totalBytes=B fromRun=...`
    on the Convex action side, plus `STAGED files=[...]` /
    `SKIP-CAP` / `SKIP-MISSING` warnings.
  - `[sandbox.execute] id=... lang=... entry=... files=N prior=N` per
    POST on the spawner side.
  - `[sandbox.stage] pre-staged N file(s) into <dir>: [...]` when
    stagePriorOutputFiles actually writes anything.
  Spawner used to log only on warn/error so "did the request reach
  the spawner / did pre-staging happen" required code inspection.

Tests: 3 new validate-request cases (passthrough, non-array reject,
bad-element reject). 95 sandbox bun tests pass.

Deploy note: the running `tale-sandbox` container needs to be rebuilt
from this code (`docker build -t ghcr.io/tale-project/tale/tale-sandbox:latest -f services/sandbox/Dockerfile .` + restart) for the fix to take effect.
The platform-side action runs under bun dev hot-reload so the diagnostic
logs there are already live.
The grouped `packages: {python?, node?}` shape forced after dropping
the flat-array union still let LLMs put right-syntax specs in the
wrong bucket: `[email protected]` (npm version pin) declared under
`packages.python` made it to `uv pip install`, which then parsed
`3.12.0` as a local path and failed obscurely; `markitdown[pptx]`
declared under `packages.node` made `npm install` choke on the `[`
with EINVALIDTAGNAME. Each round-trip burns a sandbox slot and
leaves the agent guessing.

Strict syntax validation at the Zod input layer catches both at the
tool entry. Error message says which bucket the spec belongs in, so
the agent can fix the call without a sandbox spawn.

Two pure detectors in `shared.ts`:
- `detectPythonSpecError(spec)` returns a message when `spec` is
  unambiguously npm (`pkg@digit` pin without whitespace, `@scope/...`,
  `^x.y.z` / `~x.y.z` range at start).
- `detectNodeSpecError(spec)` returns a message when `spec` is
  unambiguously pip (`pkg[extras]`, PEP 440 ops `==`/`~=`/`!=`/`===`,
  `pkg @ url` whitespace-direct-URL).

`refinePackagesObject` runs both across `{python, node}` and emits
one issue per bad entry with `path: [bucket, index]` so the agent's
error log points at the exact spec.

Wired via `.superRefine` on the `packages` schema in artifact_create,
artifact_run, and artifact_packages_add. Spawner / runtime images
unchanged — no docker rebuild needed.

Tests: 10 new cases (5 python-reject + 5 node-reject + 2 mixed
refinePackagesObject + canonical-passes for each bucket). Existing
20 cases still pass. `npx tsc --noEmit` clean.
… upload

Per sandbox-wobbly-origami plan §1 & §5 — adds:
- toSandboxStorageUrl() helper for internal proxy-routed storage URLs
- 4 new errorCode literals (HARVEST_READ_FAILED, UPLOAD_FAILED,
  UPLOAD_QUOTA_EXCEEDED, UPLOAD_REPORT_FAILED) on both sides + Convex
  validator; bidirectional Equal<> parity guard still passes
- SpawnerExecuteBody now carries priorOutputDownloads (replaces inline
  base64) + outputUploadSlots + outputUrlEndpoint + reportUploadedEndpoint
- SpawnerExecuteResponse.outputFiles[].storageId replaces contentBase64;
  adds optional uploadStats + timing diagnostic fields
- validateExecuteResponse() rewired to enforce the new shape
…peline

Per sandbox-wobbly-origami plan §2-§5:

- Schema: 5 new optional fields on sandboxExecutions (outputUploadSlots,
  outputUrlQuotaRemaining, uploadedStorageIds, uploadStats, timing); new
  constants SANDBOX_MAX_OUTPUT_FILES_PER_RUN=16 and
  SANDBOX_OUTPUT_UPLOAD_SLOTS_PREALLOC=2
- internal_mutations: applyInitOutputSlots / applyConsumeUrlQuota /
  applyRecordUploaded; recoverStuckSandboxes now also reclaims orphans
  reported via EP2; finalize takes uploadStats + timing
- sandbox_http.ts (new): HMAC-verified httpActions for EP1
  (output_upload_url) and EP2 (record_uploaded); both reuse SANDBOX_TOKEN
- http.ts: route /api/sandbox/output_upload_url + /api/sandbox/record_uploaded
- internal_actions: prior outputs now ship as download URLs (no base64);
  pre-alloc 2 upload slots + persist quota; spawner result.outputFiles
  carry storageId directly so no post-flight ctx.storage.store loop;
  forward uploadStats + timing to finalize
- artifact_run_tool: recovery table adds 4 new errorCode rows
Per sandbox-wobbly-origami plan §1, §3, §5:

- types.ts: ExecuteRequest swaps priorOutputFiles → priorOutputDownloads
  (URL list); adds outputUploadSlots / outputUrlEndpoint /
  reportUploadedEndpoint. ExecuteResponse.outputFiles[].contentBase64 →
  storageId; adds optional uploadStats + timing
- validate-request.ts: matches the new wire schema; rejects requests
  missing the required slot/endpoint fields
- sandbox_callback.ts (new): HMAC-signed POST helpers for EP1 + EP2 and
  presigned-slot upload POST; reuses SANDBOX_TOKEN
- spawn.ts: stagePriorOutputFiles → stagePriorOutputDownloads (fetches
  URLs instead of decoding base64); harvestOutputDir uploads via slots,
  lazily requests more via EP1, reports each via EP2, returns
  uploadStats + per-phase timing; classifies harvest failures into
  HARVEST_READ_FAILED / UPLOAD_FAILED / UPLOAD_QUOTA_EXCEEDED /
  UPLOAD_REPORT_FAILED
- config.ts: default body cap dropped from 20 MB to 2 MB (no more
  inline base64 outputs); operator overridable via env
- server.ts: log preAlloc slots count for diagnostic
- tests: rewritten to match the new wire shape end-to-end
…ault)

Per sandbox-wobbly-origami plan §4-§5:

- Caddyfile: new /api/sandbox/* handle (HMAC-authenticated callbacks)
  routed to convex:3211, ahead of the generic /api/* block; existing
  /api/storage/* gets log_skip so the upload token in query strings
  no longer lands in stdout
- compose.yml: convex service env adds SANDBOX_STORAGE_INTERNAL_BASE_URL
  =http://proxy so internal storage + callback URLs stay on the Docker
  network (proxy is the internal Caddy alias)
- compose.dev.yml: sandbox service adds extra_hosts so bun-dev mode
  (Convex on host, sandbox in compose) can reach host.docker.internal
- CLI deploy: new LOCKSTEP_SERVICES (sandbox + sandbox-egress) — always
  included on default `tale deploy`, matching the build matrix's
  single-version lockstep policy and preventing platform-vs-sandbox
  image drift after a rollout
Bring sandbox-wobbly-origami Phase A–D commits to a verified working
state in both docker-compose and bun-dev modes, fix a pre-existing
download-filename bug, and add the cumulative output manifest that
prevents stale-run output chips from disappearing between runs.

Pipeline / Phase 8 verification fixes
-------------------------------------
- sandbox_http.ts: migrate HMAC verify from node:crypto to Web Crypto API
  so the route stays in Convex's V8 isolate (no 'use node' overhead).
- internal_actions.ts: split storageBase (convex:3210) vs httpApiBase
  (convex:3211). Storage upload URLs live on :3210; the EP1/EP2 sandbox
  callbacks live on :3211. Both overridable via env.
- compose.yml: SANDBOX_STORAGE_INTERNAL_BASE_URL=http://convex:3210 on the
  convex service so the spawner reaches storage directly on the internal
  docker network instead of bouncing through Caddy's self-signed HTTPS.
- compose.dev.yml: mount ./services/platform/convex onto /app/convex
  inside platform (bunx convex deploy reads from there, not from the
  baked-in image snapshot); set NODE_ENV=development on convex so the
  dev-only guards in V8 isolates trip correctly.
- dev.ts: default SANDBOX_STORAGE_INTERNAL_BASE_URL / SANDBOX_HTTP_API_BASE_URL
  to http://host.docker.internal:3210/3211. Operators on machines where a
  VPN/proxy hijacks RFC1918 (singbox-tun, tailscale, ...) and breaks the
  docker-bridge→host path should override via .env.local with their LAN IP.
- Rename sandbox_callback.ts -> sandbox-callback.ts (filename-case lint).
- test_sandbox_e2e.ts: new internal action driving the 6 end-to-end cases
  from plan §8.3 (5MB / 50MB output, multi-step prior_output round-trip,
  18-file quota cap, body-size cap, Caddy token-leak stub). Used by
  Phase 8.3 / 8.4 verification.

Cumulative output manifest (artifact carry-forward)
---------------------------------------------------
- artifactOutputsTable: per-artifact (artifactId, name) manifest with
  replacement semantics. Each successful harvest upserts; empty harvests
  leave existing entries untouched. Replaces the previous "latest run
  outputFiles" walk-back so multi-run histories that produce different
  filenames stop dropping earlier files from the canvas.
- listRunsPerFile carries forward outputs from a prior row when the
  latest row produced none of its own (in-flight or settled empty).
- New errorCodes in wire.ts:
  * PRE_STAGE_FAILED — pre-stage attestation tripped; abort before user
    code runs against a corrupt workspace.
  * UPLOAD_INCOMPLETE — any harvest-side upload or EP2 record-uploaded
    callback dropped; refuse to surface a partial workspace to the LLM.

Canvas FileChip download filename fix
-------------------------------------
- FileChip now points href at /http_api/storage?id=...&filename=... (the
  platform httpAction that sets Content-Disposition: attachment;
  filename="..."). The raw /api/storage/{id} Convex backend route returns
  no Content-Disposition, so browsers were falling back to the storageId
  UUID as the saved filename. Pre-existing bug surfaced by Phase 8.4
  real-UI download testing via Playwright.
Fixes the recurring "FileNotFoundError" the user hit running QA on a prior
artifact run's output: with the old latest-run walk-back, a follow-up run
that produced a different filename structurally shadowed earlier outputs
(Run 1 wrote `output.pptx`; Run 2 wrote only `qa_report.txt`; Run 3's
pre-stage saw Run 2 and lost `output.pptx`). The earlier `priorOutputDownloads`
infrastructure was correct; the read side was the defect.

Three reinforcing changes:

1. Cumulative state via `artifactOutputs` manifest. Every harvest upserts
   each file into a `(artifactId, name)`-keyed manifest in
   `applyFinalizeArtifactRun`. Same-name files patch in place (newest
   wins); new names accumulate; empty harvests don't wipe earlier output.
   Pre-stage reads the manifest first; falls back to a newest-name-wins
   reduction across `artifactRunFiles` for pre-manifest artifacts (with
   the action invoking `deriveOutputManifestFromHistory` to populate
   the manifest lazily so the next read is O(1)). Legacy
   `artifacts.runOutputFiles` is the final fallback.

2. Fatal pre-stage attestation. `stagePriorOutputDownloads` now returns
   `{staged, skipped}` with sha256 per staged file and structured skip
   reasons (`unsafe_path | fetch_failed | http_error | url_expired |
   write_failed`); the spawner surfaces this on `ExecuteResponse.priorStage`.
   The action diffs `staged` against the manifest it sent; any expected
   file the spawner couldn't inject aborts the run with
   `PRE_STAGE_FAILED` BEFORE user code executes — no more silent stderr
   notes that the LLM never reads.

3. Upload-completeness gate. `uploadStats.failures` non-empty (transport
   POST or EP2 record-uploaded callback dropped) → fatal
   `UPLOAD_INCOMPLETE` instead of a `success: true` with a partial
   workspace.

Also fixes a latent terminal-guard bug in `applyFinalizeArtifactRun`: the
old "no-op if artifact row is terminal" was too coarse and silently
dropped any finalize from a caller that didn't go through
`initArtifactRun` first (direct executeCode callers, test harnesses,
future custom paths). Gate the no-op on `runExecutionId` parity instead —
same execution = duplicate delta, no-op; different execution = genuinely
new run, proceed.

Sha256 flows end-to-end: spawner computes during harvest, plumbs through
`OutputFile`, `SandboxOutputFile` validator, `finalizeArtifactRun` args,
into the manifest row. Existing manifest entries (lazy-derived from
legacy data) leave sha256 undefined and the attestation treats them as
presence-only until a fresh run refreshes them.

Tests:
- 6 new unit cases in `internal_queries.test.ts` covering the no-shadow
  invariant, manifest precedence, lazy-derive signaling, `from_run` pin
  bypass, and sha256 propagation.
- 4 new unit cases in `internal_mutations.test.ts` covering the
  executionId-parity finalize guard (same-id no-op, different-id
  proceeds, fresh-row proceeds, missing-id proceeds).
- 7 new spawn-prior-outputs cases covering return shape, sha256
  correctness on text + binary, every skip-reason classification, and a
  mixed staged+skipped scenario.
- New `cumulative_manifest_no_shadow` e2e case exercising the exact
  three-run user-reported failure mode against the live spawner.

Verified end-to-end: rebuilt + restarted `tale-sandbox` container,
deployed the platform changes, ran the full 7-case e2e suite (all pass)
plus 73,000+ unit tests. The user's repro now succeeds: Run 1 writes
foo.txt; Run 2 writes only bar.txt; Run 3 sees BOTH foo.txt AND bar.txt
in `/workspace/output/` with no intermediate initArtifactRun.
LLM-generated code hit "LibreOffice not found" then guessed
`pip install libreoffice-python` (a non-existent PyPI package). The
artifact_run tool description didn't state which system binaries are
present, didn't explain why runtime apt-get is impossible (read-only
root, UID 65534, no CAP_SYS_ADMIN), and didn't flag visual rendering
QA as out-of-scope for the sandbox.

Add three SANDBOX ENVIRONMENT bullets covering baked-in binaries
(positive + NOT-available list), runtime-install impossibility with
anti-hallucination call-outs for libreoffice-python / pandoc-python,
and out-of-scope task shapes (visual QA, headless browser, OCR,
video transcoding). Tighten the INSTALL_FAILED recovery row to
distinguish a misspelled Python/Node spec (retry) from a missing
system binary (stop and surface the limitation).

Prompt-surface change only; no Dockerfile or behavior change.
Bundle of 16 fixes from the two-round review of the sandbox feature:

- Spawner: SANDBOX_TOKEN is now opt-in on both sides (drop the asymmetric
  fail-closed gate + SANDBOX_ALLOW_UNAUTH flag). Bound SSE live-tail
  stdout/stderr deltas and lineBuf so a runaway runtime can't flood the
  consumer. Pass timeoutMs through dockerKill so a wedged daemon can't
  leak the docker CLI subprocess. Bound pre-stage fetch with
  AbortSignal.timeout + per-file streamed size cap (new fetch_timeout /
  download_too_large skip reasons). Refresh spawner lock mtime + clamp
  negative wall-clock skew.

- Convex: mirror the spawner's replay-nonce cache + align skew to 30s.
  Terminal-state guard on insertOutputFiles + hoisted rollback helper so
  a user-cancel landing between harvest and finalize doesn't leak
  fileMetadata rows or _storage blobs. Duplicate-finalize gate now
  short-circuits when runExecutionId is omitted AND the row is already
  terminal (closes the tool-fallback-finalize duplicate path).

- Agent tools: artifact_file_{create,update} now surface ConvexError +
  InvalidArtifactPathError codes (too_large, too_many_files,
  duplicate_path, empty_project, invalid_path) instead of flattening
  every error into a bare message; descriptions updated to match.
  Pre-validate streaming path before beginEditStream and set a sticky
  hard-fail flag so a malformed path doesn't spam WARN per delta.

- RLS / role gates: add explicit role check to artifacts.userEdit (the
  public mutation bypassed the READ_ONLY matrix entry for `member`).
  Add RLS rules for the four new artifactFiles / artifactRuns /
  artifactRunFiles / artifactOutputs tables (parent-artifactId org
  resolution, internal-only writes).

- i18n: add the 6 missing canvas.runErrorCode keys in en/de/fr
  (HARVEST_READ_FAILED, UPLOAD_FAILED, UPLOAD_QUOTA_EXCEEDED,
  UPLOAD_REPORT_FAILED, PRE_STAGE_FAILED, UPLOAD_INCOMPLETE) and fix
  the French gender on "Préparation de la sandbox".

- Misc: tale doctor now loads the project .env before checking
  SANDBOX_TOKEN (and reports it as opt-in informational, not a hard
  fail). Delete test_sandbox_e2e.ts — manual harness mis-shelved as
  an automated test; e2e coverage lives in container-smoke-test.sh.

Deferred (tracked separately): split the sandbox spawner onto its own
Docker network so a compromise of crawler/rag can't sign requests to
docker.sock — defense-in-depth, not a correctness bug.
@larryro
larryro force-pushed the feat/sandbox-code-run branch from e81ec30 to c36a9dd Compare May 24, 2026 01:38
larryro added 5 commits May 24, 2026 10:39
Convex Node actions read `process.env` from the Convex deployment env
(populated by `convex env set`), not the host container's OS env.
`SANDBOX_STORAGE_INTERNAL_BASE_URL` was previously set on the convex
service in compose.yml, where it was invisible to the rewrite in
`toSandboxStorageUrl` — uploads silently fell back to SITE_URL
(`https://localhost`) and the spawner POSTed to its own loopback,
returning UPLOAD_FAILED for every harvested file.

Bake the var into the platform image so the entrypoint's env-sync
pushes it into the Convex deployment on every boot. The value
`http://convex:3210` is stable across single-color compose and
blue/green CLI deploys (the convex service always carries that DNS
alias).
Two-round subagent review of feat/sandbox-code-run surfaced 5 P0 + 10 P1
issues spanning wire-schema convergence, Phase-B migration safety,
headless-deploy upgrade, agent-tool surface, and run-result UX.

[A] Wire sha256 convergence (P0-1, P0-2, P1-6)
- fileMetadata + artifactRunFiles tables gain optional sha256 field.
- outputFileValidator (sandbox/output_mutations.ts) takes required
  sha256; insertOutputFiles persists it onto fileMetadata and surfaces
  it on the inserted-files return shape.
- wire.ts adds HarvestOutputFile interface + Equal<HarvestOutputFile,
  SpawnerOutputFile> parity guard so future spawner-side OutputFile
  drift fails CI typecheck instead of silently breaking the audit row.
- spawner_client.ts response type + SSE parser require sha256 on each
  outputFile so a wire-drift surfaces as a hard failure.
- Manual sha256 re-join in internal_actions.ts:1154 removed —
  insertedFiles[i].sha256 flows naturally from the mutation now.
- getLatestRunOutputs pinned-run + walk-back paths return sha256
  symmetric with the cumulative manifest (P1-6).

[B] Phase-B backfill safety (P0-3, P0-4)
- backfill_artifact_files_table registered in migrations.runAll after
  Phase A so `tale deploy` populates the new tables automatically
  (previously manual-invocation-only — silent skip on upgrade).
- Sentinel _phaseB_complete on artifacts row, patched as the LAST
  write per artifact; on retry, completed artifacts skip at O(1).
  Per-artifact write block no longer wraps in catch-and-continue —
  Convex transaction rolls a partial failure back atomically.
  Pre-sentinel partial-orphan rows are recovered by reusing the
  existing artifactRuns row instead of skipping the whole artifact.

[C] Deploy + tool surface + UX (P0-5, P1-7..14, P1-16)
- ensureEnv splits requiredVars into user-supplied (HOST, TLS_MODE)
  vs auto-gen secrets; non-TTY upgrades silently mint missing secrets
  (SANDBOX_TOKEN etc.) so headless `tale deploy` keeps working when
  the schema gains a new required secret. Deploy.ts forwards
  --force-recreate when secrets were just rotated so containers pick
  up the new value instead of keeping the stale null token.
- spawnerExecute combines caller's signal with
  AbortSignal.timeout(timeoutMs + 60s); spawnerCancel adds a 5s
  fetch timeout so user-stop returns even when the spawner is
  unreachable.
- artifact_list switches to a new listByThreadMetadata query
  (server-side projection) so the action no longer allocates MB of
  string content just to count bytes.
- artifact_create collision response carries existingTitle +
  existingFiles, eliminating an extra artifact_file_list round-trip.
- artifact_run validates inputs.from_run against the artifact pre-
  dispatch via new validateRunIdForArtifact query; structured
  pin_target_not_found error replaces silent fallback to "latest".
- FileChip renders disabled <button> instead of broken <a href="#">
  on missing storageId (a11y + semantics).
- chat-agent.json (en/de/fr) system prompt slimmed: tool-call
  signatures move to tool descriptions, routing + guardrails stay.
- artifacts.mutations.userEdit fails explicitly on undefined
  membership rather than relying on implicit role coercion.
- finalizeArtifactRun replaces broad trustTerminal branch with
  fallbackOverPriorExecution — fallback finalize only no-ops when
  the row already carries executionId, so history from an unrelated
  second execution is preserved.

New tests:
- sandbox/internal_mutations.test.ts: insertOutputFiles sha256
  round-trip + terminal-state skip (2 cases).
- migrations/backfill_artifact_files_table.test.ts: sentinel-based
  skip, partial-orphan recovery, in-flight pass-through (4 cases).

Validation: 73,123 vitest tests pass; format/lint/typecheck clean
across all 34 workspace tasks.
The sha256 plumbing landed in 20baa61 but missed the action's own
returns validator on `files[]`. Harvest emits sha256 (set by the
spawner during upload), `insertOutputFiles` propagates it through the
inserted-row return value, and the action lifts the field into its
result — but Convex's runtime validator on `files[i]` listed only
{name, fileMetadataId, storageId, size, contentType}, so every
successful run with files came back as ReturnsValidationError.

The file's bytes were already in `_storage` and the fileMetadata row
inserted, which is why the UI showed the pptx fine while the LLM saw
"Run FAILED before completion".
PRIOR_FETCH_DEFAULT_TIMEOUT_MS and PRIOR_FETCH_DEFAULT_MAX_BYTES are
only used internally — no external consumers or tests reference them.
Two failures on PR 1727 CI:
1. Positive path returned HTTP 400 'request must set exactly one of
   entryPath or steps' — smoke test still posted the legacy 'code'
   field. Switch to files[]/entryPath and supply the now-required
   outputUploadSlots + endpoint URLs (placeholders, never hit since
   print(1) writes no outputs).
2. Oversized-body test got 401 instead of 413 because the body cap
   default rose from 256 KB to 2 MiB (e165ab4 / c36a9dd); 256 KB
   no longer exceeds the cap so HMAC check fires first. Bump the
   probe to 2 MiB + 1 byte.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants