Skip to content

refactor(sandbox): move run_code to a persistent per-thread session + fix the file/path model - #2301

Merged
larryro merged 29 commits into
mainfrom
fix/skill-description-yaml-colon
Jul 2, 2026
Merged

larryro merged 29 commits into
mainfrom
fix/skill-description-yaml-colon

Conversation

@larryro

@larryro larryro commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Started as a one-line skills fix and grew (on request, kept on one branch) into a reworking of how the chat run_code tool and the thread file model work — driven by real bugs seen in a panda-.pptx thread (duplicate files, tool confusion, packages/scratch not persisting). It ends with run_code running in a persistent per-thread sandbox session.

What changed, by theme

1. Skills — strict-YAML parse errors

create-pr / implement-feature / write-notes / visual-aspect-analyzer descriptions contained an unquoted : (YAML's key/value separator), so the dashboard's strict parser (parseDocument, core schema) rejected them. Quoted them + added a guard that runs parseSkillMd over every shipped SKILL.md.

2. run_code output path + visibility

  • Fixed the tool prompt: it advertised /workspace/… (which doesn't exist in the container) — the real, harvested dir is /user/output/. Model deliverables were silently lost.
  • run_code-produced files now render as chat download cards (same as the old native tools), not just in the Canvas.

3. Removed native pdf/excel/docx/text tools → skills

They overlapped with the docx/pdf/xlsx skills that drive run_code, so an agent produced the same file two ways. Removed them; document generation now has one path (skill + run_code). image (vision) and generate_image stay. toolNames is a lenient string array + the runtime skips unknown tools, so existing agent configs degrade gracefully — no migration. Historical tool-call rendering (labels/icons) preserved.

4. Canonical absolute workspace paths + de-dup + manifest

  • One path everywhere. threadFiles.path is now the canonical absolute /user/<root>/<name> the model uses in run_code scripts, file tools, and staging/harvest — no per-tool conversion. Reversible, non-destructive migration (v0_2_89/01) folds existing relative paths in.
  • Incremental harvest (the duplicate-pptx fix): unchanged re-harvested outputs are dropped by sha256, so no duplicate threadFiles / cards.
  • file_list returns fileId (storage id) as a handoff token to the image / document_write tools; path stays the identity.
  • run_code result carries a sandboxState manifest — uploads/code/outputs, each with fileId — so the model has ground truth (won't regenerate) on every run.

5. run_code → persistent per-thread session

run_code now runs inside a persistent session (thr-<threadId>), reusing the machinery external agents run on, so packages, files, and scratch persist across runs and the re-stage/re-harvest churn is gone. A clean cut-over (no flag, no fallback): ensureThreadSession → stage mutable inputs → install packages in-session → run steps → harvest only new/changed /user/output. The reaper's idle-stop + resume gives "warm within a turn, preserved across turns" for free (no turn-lifecycle surgery). destroyThreadSession on thread delete.

Design + rationale: services/sandbox/docs/run-code-persistent-sessions.md.

Migration

v0_2_89/01_thread_files_absolute_paths — reversible, non-destructive path rewrite (up prepends the source root, down strips it), with a round-trip test.

Verification

typecheck ✅ · oxlint 0 ✅ · knip 0 ✅ · migrations:check OK ✅ · format ✅ · touched tests + the migration round-trip pass.

⚠️ Needs live validation before this lands

The session execution path can't be exercised without a live session, and it's now the sole run_code path (no fallback). Test a multi-round thread — generate → pip-install → import next run → edit an upload — and confirm the v1 assumptions: in-session pip/npm env, and harvest (currently top-level /user/output only). Follow-ups: nested output dirs, a fileMetadata row per output, a durable session-op audit, a long-lived run_code container profile.

@larryro larryro changed the title fix(skills): quote colon-bearing descriptions so strict YAML parses refactor(sandbox): move run_code to a persistent per-thread session + fix the file/path model Jul 1, 2026
larryro added 19 commits July 2, 2026 08:14
Four SKILL.md descriptions contained an unquoted `: ` (colon-space),
which is the YAML key/value separator. Tale's loader parses frontmatter
with strict YAML 1.2 (`schema: 'core'`), so it read the rest of the
sentence as a nested mapping and rejected the skill with
`BLOCK_AS_IMPLICIT_KEY` ("Nested mappings are not allowed in compact
mappings") — surfaced in the dashboard Skills tab.

The write path (`serializeSkillMd`) auto-quotes such strings, but these
files were hand-authored and never round-tripped, and `skills:sync`
copies verbatim while `skills:check` never runs the real parser — so the
invalid YAML shipped undetected.

- Single-quote the descriptions for create-pr, implement-feature,
  write-notes, and visual-aspect-analyzer (text unchanged), and
  regenerate the .agents/.claude mirrors via skills:sync.
- Add a regression guard: parse every shipped SKILL.md (product catalog
  + generated mirrors) with the runtime parseSkillMd, closing the gap
  that let unquoted frontmatter ship.
The run_code tool told the model its sandbox dirs were `/workspace/code`,
`/workspace/output`, and `/workspace/uploads`, but the container bind-mounts
the host dir at `/user` (docker) / the shared `/user` emptyDir (k8s,
`WORKSPACE_MOUNT`), so the real paths are `/user/code` (cwd), `/user/uploads`,
and `/user/output` — and the spawner harvests ONLY `/user/output`. There is
no bare `/workspace`, so a model that followed the tool description (or its
"no output files were harvested" hint) wrote deliverables to a non-existent
path and lost them silently.

- Rewrite every model-facing `/workspace/*` string in run_code_tool.ts to the
  real `/user/*` dirs: description, arg hints, the empty-files hint (incl. its
  "correct" example), and the success message.
- Fix a stale `/workspace/output/` comment in file_metadata/schema.ts.
- Add tests/sandbox-output-paths.test.ts: assert the tool source never
  advertises `/workspace/{code,output,uploads}` and always references
  `/user/output`, locking the container-path contract (incl. the hint buried
  in `execute`).

Prompt/docs only — the sandbox already harvested `/user/output`; no runtime
or data-model change.
A file produced by `run_code` only appeared in the Canvas, while files
from the native document tools rendered as a prominent download card in
the chat — so code-generated deliverables were easy to miss. After a run
completes, append a file part per harvested output (mirroring the doc
tools' `appendFilePart`), so run_code deliverables render as the same
chat cards and still stay in the Canvas. No-ops on sub-agent threads.

Also teach the model the output-dir contract proactively, so it writes
the deliverable to the harvested path on the first try instead of
erroring then adjusting:
- file_write: note that a script's deliverable must go to `/user/output/`
  (cwd `/user/code` and `/tmp` are discarded), and to rewrite a skill's
  relative `output.xlsx` example accordingly.
- expand_skill: append the same reminder after the skill body, since many
  skills illustrate saving to a bare relative path.
… to skills

These first-class document-generation tools overlapped with the docx/pdf/
xlsx skills that drive `run_code` — an agent with a skill bound could
produce the same file two ways, and did (once via the buried code path,
once via the prominent tool card). Remove them so document generation has
one path: the skill + run_code.

- Delete excel/docx/pdf/text tool files; drop them from TOOL_NAMES and the
  registry. `image` (vision analysis) and `generate_image` stay — no skill
  replaces them.
- Runtime already skips unknown tool names (loadConvexToolsAsObject warns),
  and `toolNames` is a lenient string array, so existing agent configs that
  still list these names degrade gracefully — no migration needed.
- Keep the display-name + icon maps (string-typed, already hold non-tool
  names like `pptx`) so historical tool calls still render nicely.
- Built-in configs: drop the dangling tool names; the assistant already
  binds the doc skills, and bind `xlsx` to the analyst (it has run_code +
  file_write) so it keeps its Excel capability via the skill.

The tool-picker (TOOL_CATEGORIES, ToolName[]-typed) drops them too.
The thread workspace is one filesystem rooted at /user, mounted 1:1 by the
sandbox. Store `threadFiles.path` as the canonical absolute
`/user/<root>/<name>` so the model uses one path everywhere — file tools,
run_code scripts, staging/harvest — with no per-tool conversion.

- sandbox_paths.ts: parseWorkspacePath / workspacePathOf / relOf — the one
  root↔source mapping.
- file_read/write/edit/list/delete + run_code entryPath/steps take & emit
  absolute paths; the platform strips the /user root only when calling the
  spawner, so the spawner protocol is unchanged.
- harvest stores /user/output/<name>; the download card shows the basename.
- file_list also returns each file's fileId (storage id) as a handoff token
  to the image / document_write tools.
- Incremental harvest: skip re-uploading a byte-identical prior output
  (upsertThreadFile stores sha256; executeCode drops unchanged re-harvests),
  fixing the duplicate output files / duplicate chat cards.

Migration v0_2_89/01 folds existing relative paths into the absolute form
from their source — reversible, non-destructive, idempotent.
Records the target architecture: per-thread persistent sandbox session
(turn-scoped, stop-preserve), the canonical absolute workspace-path scheme,
incremental harvest, the sandbox-state manifest, and the fileId handoff.
Every run_code result now carries a `sandboxState` manifest — the current
workspace files grouped by area (uploads / code / outputs), each with its
absolute path and `fileId` (storage id) — plus a compact human-readable
summary appended to the result message. Reported on success and failure.

Gives the model ground truth so it doesn't regenerate an output it already
produced or re-read blindly, and surfaces the `fileId` to hand to the
`image` (analyze) / `document_write` tools. Files stay referenced by path;
`fileId` is the use-it-now handoff token.
ensureThreadSession / destroyThreadSession — the reusable lifecycle core for
running chat run_code inside a persistent per-thread sandbox session
(thr-<threadId>, ownerType 'thread'), reusing the exact machinery external
agents run on (reserveSessionSlotAndInsert / sessionCreate / resume).

Key simplification confirmed during API mapping: no turn-end stop hook is
needed — the spawner reaper already stop-preserves an idle session and
sessionCreate against the same id resumes it (workspace intact), so
"warm within a turn, preserved across turns" falls out of the existing
reaper + resume path. Only teardown is destroyThreadSession on thread delete.

Inert: nothing calls these yet — the run_code dispatch stage will, behind
SANDBOX_RUNCODE_SESSIONS (off by default), with ephemeral fallback.
Phase 2 dispatch: when the flag is on, run_code executes inside the thread's
persistent session (executeCodeInSession) — ensure/resume the session, stage
mutable inputs (prior outputs already persist in the workspace, so no
re-stage/re-harvest churn), install packages in-session (they persist),
run the step(s) as sequential execs, and harvest only new/changed
/user/output files (sha256). Off by default; any error falls back to the
ephemeral one-shot path, so the flag can never regress the tool.

Explicit handler return type breaks the `internal`-references-itself
inference cycle. v1 scope (validate against a live session): top-level
outputs only; fileMetadata rows + a durable session-op audit are follow-ups.
Clean cut-over — drop the SANDBOX_RUNCODE_SESSIONS flag and the ephemeral
fallback. run_code now calls executeCodeInSession unconditionally, and the
dead ephemeral staging in run_code_tool (spawner-language dispatch, download-
url payloads, sandboxArgs) is removed. On failure the tool surfaces the error
to the model. The shared ephemeral executeCode action stays for the workflow
sandbox node.
The three persistent-session workloads shared one per-org pool
(`maxSessionsPerOrg`), so per-thread run_code sessions competed with
external-agent user sessions and tripped QUOTA_EXCEEDED ("At most 2
sandbox sessions can be active") once two threads were warm.

Split the pool into three independently-capped budgets keyed by
ownerType: user agents (`maxSessionsPerOrg`, 2), per-thread run_code
(`maxThreadSessionsPerOrg`, 8), and per-workflow-run
(`maxWorkflowSessionsPerOrg`, 4). Admission counting, cap lookup, FIFO
rank, and the reserve-time hard cap all filter to the owner's budget so
the workloads never contend. The quota editor preserves the two new
caps (config/API tuned for now).
The spawner's global SANDBOX_MAX_SESSIONS defaulted to 2 — smaller than
a single org's summed per-org session budgets (user 2 + thread 8 +
workflow 4 = 14). Convex admitted sessions the spawner then refused with
a 429 (SpawnerBusyError) once two thread sessions were warm. Raise the
default host ceiling to 16 so it covers one active org's budgets with
headroom; sessions idle-stop, so this is a ceiling, not a reservation.
Converge the last one-shot caller onto the session model: a workflow
script step now runs in an ephemeral workflow-run session (reserve +
create, keyed per (execution, step), torn down at step end) — the exact
lifecycle workflow agent steps already use, and the same session-exec
machinery chat run_code runs on.

Extract a shared `runAndHarvestInSession` core (install packages, run
steps, harvest /user/output) so the thread and workflow paths never
diverge; executeCodeInSession keeps its thread staging and delegates to
it. Script staging (/user/code + /user/uploads), step env injection,
result.json, outputFileIds, and park-on-capacity are all preserved; the
admission poll now uses kind 'session' so script steps draw from the
per-org workflow session budget. The one-shot executeCode path now has
zero callers (removed next).
Move the last one-shot consumer — the crawler's headless-Chromium
document/page rendering — onto the session model. render.js now runs in
an ephemeral 'render' session (create → run → read /user/output → destroy,
via the shared runStepsInSession core) and its output is read straight
off the session, dropping the /v1/execute call plus the output-upload
HTTP callbacks entirely.

Renders get their own isolated per-org session budget
(maxRenderSessionsPerOrg, default 4) so heavy crawling can't starve
interactive agent / run_code sessions — the session-model replacement
for the old separate one-shot pool. After this the one-shot spawner path
has zero callers outside the (now-dead) executeCode action.
Every sandbox run is a session now (chat run_code, external agents,
workflow agent + script steps, and crawler renders), so the one-shot
audit/admission machinery is dead. Remove it wholesale:

- executeCode + its spawner→platform output-upload HTTP callbacks
  (/api/sandbox/output_upload_url, record_uploaded) and the backing
  mutations
- the sandboxExecutions audit table, its watchdog cron, lazy-GC
  rate-limit key, and RLS rules
- reserveSlotAndInsert / finalize / heartbeat / setRunning /
  cancelExecutionRecord and the daily-CPU-second budget
- spawner_client (spawnerExecute/Cancel) and the one-shot wire validators'
  callers; admission `kind` collapses to session-only and governance
  loses maxConcurrentPerOrg (+ its editor field and i18n)

The thread cancel cascade now has a single session path. Schema baseline
refreshed for the deliberate table drop (sandbox is unreleased — audit
rows only, no prod data).
Its only consumer was the one-shot /v1/execute concurrency gate, which no
client calls anymore (run_code, workflow steps, and crawler renders all
run as sessions). The operator now sees a single host cap —
SANDBOX_MAX_SESSIONS — matching the unified session model; per-org limits
are the governance `sandbox_quota` session budgets.

The dead /v1/execute route + its ExecutionBackend still linger because
that backend object also carries the spawner's boot/shutdown lifecycle
(host-lock, image warm, health, orphan sweep) and shares exec-common /
exec-response with the session path; fully excising it is a
decouple-lifecycle-from-execute refactor, tracked separately.
Reframe sessions.md around the single session model — every sandbox run
is a session, differing only by destroy timing (thread idle-stop / user /
run-end / render) — and the two-tier capacity model (per-org sandbox_quota
budgets under the SANDBOX_MAX_SESSIONS host cap). Drop the stale
SANDBOX_MAX_CONCURRENT reference in kubernetes.md.
No client calls the one-shot execute path anymore (run_code, workflow
steps, and crawler renders all run as sessions), so drop its HTTP surface:
handleExecute/handleCancel + the router dispatch, the in-flight registry
(spawn.ts), and the SIGTERM drain-loop + orphan-sweep isLive hooks in
cleanup.ts (sessions are label-disjoint — `tale.sandbox-session=1` vs the
one-shot `tale.sandbox=1` — so the sweep never touched them). The
ExecutionBackend's now-unreachable execute()/cancel() machinery is slimmed
out next.
… machinery

Complete the one-shot removal: the ExecutionBackend no longer executes
code — it keeps only the spawner host lifecycle (init/warmImage/health/
shutdown/orphan-sweep). DockerBackend and KubernetesBackend shrink to
those methods; execute()/cancel() and the whole execute machinery are
deleted:

- exec-common, exec-response, docker-args, validate-request,
  local-workspace-run, host-dir-workspace, k8s-stage/harvest/pod-spec/
  protocol/cache, sandbox-callback (+ their tests)
- the one-shot request/response wire types (src/types.ts) and the
  language/phase/step wire literals + their Convex-side parity mirror
- readPodLog, dockerKill, and the request-validation constants that only
  the deleted code used

exec-common/exec-response turned out to be one-shot-only (the session
path never used them); spawn-util is kept (shared). The k8s orphan sweep
+ shouldReap* helpers stay (reap stray legacy one-shot pods; sessions are
label-disjoint). All green: typecheck, lint, knip, 200 spawner + 79
platform sandbox tests.
@larryro
larryro force-pushed the fix/skill-description-yaml-colon branch from c37e4c2 to 42c79ba Compare July 2, 2026 00:22
larryro added 5 commits July 2, 2026 09:47
DinD (and its extras: inner-docker volume, shared buildkitd, browser
stack) is an agent-profile capability. A default-profile (run_code)
session under a DinD-enabled cfg got the DinD boot: --privileged on the
runc tier for untrusted user code, and the runtime entrypoint's DinD
branch setpriv-drops to 10001 unconditionally, which cannot write the
65534-owned workspace — the skeleton mkdir died, runnerd never came up,
and every chat run_code failed with an opaque 502 after the full 180s
health timeout. sessionDindEnabled() now gates every DinD side-effect in
the argv builder and the docker backend, so default-profile sessions take
the hardened TALE_DROP_UID path (unprivileged, uid 65534 honored).

The create wait also fails fast now: waitForRunnerdOrExit aborts as soon
as the container is definitively dead (isReapableContainerStatus) and
surfaces its last log lines, instead of blind-polling a corpse for
minutes and reporting only "did not become ready".
DELETE /v1/sessions/:id?if_idle=1 lets a janitor caller (the platform's
end-of-turn thread-session teardown) destroy a session only when nothing
is executing in it. Busy is decided spawner-side, mirroring the reaper's
two-tier check: this replica's in-flight exec map first, then runnerd's
own liveExecs counter as the cold-cache backstop. A failed probe is
"unknown", not "idle" — only a definitively gone backend object may
report not-busy, so a wedged-but-alive container is left to the reaper
rather than destroyed under a possibly-running exec. Busy responds
{destroyed:false, busy:true} and touches nothing.

Unconditional DELETE (thread-delete cascade, workflow step teardown,
management page) keeps its semantics. The query string is HMAC-covered
(authorize signs pathname + search).
Thread run_code sessions are TURN-scoped: one session amortizes all
run_code calls of a turn, but it must not linger as idle compute once
the turn ends. runGenerationCore's finally schedules
teardownThreadSessionAtTurnEnd with the turn's own threadId — delegate
sub-turns run through the same core with their sub-thread id, so every
turn cleans up exactly its own session; the next turn recreates it and
re-stages the workspace from threadFiles.

The teardown destroys via the spawner's conditional if_idle DELETE: when
a sibling turn on the same thread (e.g. the same delegate invoked twice
in parallel onto one sub-thread) still has a live exec, the spawner
no-ops with busy=true and everything is left alone — the surviving
turn's own finally tears down when it ends. Platform rows flip only
AFTER the spawner confirms the destroy (destroyThreadOwnedSessions:
mark destroyed + capacity wake + VK/op cleanup), so a busy skip can
never strand a destroyed row against a live container. Also corrects
the stale "falls back to the ephemeral one-shot path" comment (that
path is gone) and the cascade comment now that thread-owned sessions
are current again.
The session harvest stored output files via ctx.storage.store(new
Blob([ab])) — a type-less Blob. The self-hosted Convex backend rejects
the resulting empty content-type header with BadHeader ("Error
uploading file: … invalid HTTP header"), which failed every run_code
that produced a real output file (e.g. a generated .pptx) while
stdout-only runs passed. The spawner serves the generic
application/octet-stream, so fall back to the extension-derived type
(inferContentType — sessionReadFile's documented contract) and carry it
into the Blob, the threadFiles row, and the tool result, so file cards
get the true mime (pptx/pdf/…) instead of octet-stream.
The Code output dock was a single scroll row with scrollbar-hide — with
many output files (a pptx run yields 9+) everything past the fold was
invisible with zero affordance. When the chip row genuinely overflows
(measured via useResizeObserver + re-measure on file changes, same
pattern as tab-navigation), a chevron toggle appears; expanding wraps
the chips into bounded rows (max-h + scroll) so every file is reachable
without letting a huge run swallow the viewer.

Toggle is a real button with a localized accessible name (en/de/fr;
de-CH is a sparse override), aria-expanded + aria-controls on the chip
row, 24px hit target; axe audit covers the expanded state. Verified in
the real app in light and dark.
The tool entry already returns NO_USER_CONTEXT when userId is falsy, so
TypeScript narrows it to a non-empty string by the dispatch site — the
`?? ''` branch was dead code and implied an empty uploadedBy is a legal
state. Flagged by github-code-quality on the PR ("useless conditional").
larryro added 4 commits July 2, 2026 10:00
Generated-file message parts persist a raw storage download URL, so a
file the agent later deletes (file_delete cleaning up run_code
intermediates, e.g. QA slide renders) kept rendering forever as a broken
thumbnail or a live-looking card whose download 404s. FilePartDisplay
now gates on live existence via the existing useFileUrl/getFileUrl
pattern (null for a deleted storage object ⇒ render nothing, reactive so
cleanup takes effect immediately); parts without a parseable storage id
(external URLs) render unchanged, and history keeps rendering while the
existence query is in flight so live files never flash.
The session file read serves the generic application/octet-stream, so
the || fallback in renderDocumentInSandbox never fired and every
rendered PDF/image blob was persisted (and reported to callers) as
octet-stream. Treat the generic type as absent and fall back to the
request-derived type — the same convention the run_code harvest uses
(session_exec.ts, 3094d33).
The one-shot→session migration (5db122e) deleted spawner_client, but
this test still mocked it — the orphaned mock intercepted nothing, so
every case drove the real session client into fetch ECONNREFUSED :8003
and failed the Unit CI job. Mock the new seam (session_client +
session_exec) and let the real render_session run, preserving each
assertion's intent (staged http(s) script URL ≤4096 chars, output-file
naming, stderr surfacing, missing-output error) and adding coverage for
teardown-on-failure, the duplicate-session reap, and the real
content-type fallback.
The one-shot /v1/execute route this probe exercised was removed with
the session migration (81e419c), so the smoke test failed with three
404s. Walk the session lifecycle instead — signed create, inline
contentBase64 stage, exec over SSE, destroy — with the same 401/413
negative cases (session routes share the body-cap + HMAC layer).

The smoke-fileserver sidecar existed solely to host a files[].url for
the retired spawner-side input fetch; staged URLs are now fetched by
runnerd inside the session container, which cannot reach the compose
'internal' network, so the source ships inline and the sidecar goes.

Verified against a live spawner: 201 create, staged main.py, SSE
'event: result' with status completed + stdout 1, destroyed:true,
401 unsigned, 413 oversized.
@larryro
larryro merged commit 29c4b74 into main Jul 2, 2026
52 checks passed
@larryro
larryro deleted the fix/skill-description-yaml-colon branch July 2, 2026 02:46
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.

1 participant