Skip to content

Shell backends (Phase 1): local + docker via per-session container - #233

Merged
FMXExpress merged 3 commits into
mainfrom
claude/shell-backend-local-and-docker
Jun 12, 2026
Merged

FMXExpress merged 3 commits into
mainfrom
claude/shell-backend-local-and-docker

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Phase 1 of the shell-backend abstraction. Adds an IShellBackend interface so shell_exec / execute_code can run somewhere other than the host process. Phase 1 ships two impls — local (historical default) and docker (per-session container with workspace bind-mounted at the same path); Phase 2 will add ssh behind the same interface.

What's new

Architecture

  • PasClaw.Shell.Backend — interface + process-global active backend + RunOneShot{,WithEnv}ViaBackend wrappers that Tool_Shell / Tool_ExecuteCode call into.
  • PasClaw.Shell.Backend.Local — thin wrapper around the existing PasClaw.Platform.RunOneShot. StartSession/CloseSession no-op (the host process IS the session).
  • PasClaw.Shell.Backend.Docker — spawns a long-running idle container at StartSession (tail -f /dev/null so the container doesn't exit), docker execs into it per call, stops it at CloseSession. Workspace + tmp/ + run/ bind-mounted at the same path inside the container so MakeTempScript paths and tool-RPC info files Just Work; config.json (provider keys), cache/, logs/ deliberately not mounted. Empty SessionId falls back to RunOneShot per documented contract so pasclaw -m one-shots don't pay container startup.
  • PasClaw.Shell.Backend.Factory — reads Cfg.ShellBackend + --backend override, builds + installs the matching impl. Raises clear exceptions on docker-daemon-unreachable; loud-not-silent so the operator sees the security intent failed.

Config / onboarding

  • TConfig.ShellBackend (sbLocal default) + TConfig.ShellBackendDocker {image, network, user, privileged}.
  • "shell_backend": "local" | "docker" round-trips in config.json; "shell_backend_docker" subobject only emitted when docker is on or defaults diverge.
  • PromptShellBackend in pasclaw onboard — y/N + image + network follow-ups when docker is picked.

CLI surface

  • --backend local|docker overrides config per-run on pasclaw agent, pasclaw tui, pasclaw heartbeat.
  • pasclaw status shows the active backend.
  • shell_exec's tool description names the backend so the model knows where its commands run (apt install won't persist past a per-session container).

Lifecycle wiring

  • Cmd_Agent_Run installs the backend after ConfigureSandbox, refuses startup on docker-not-available.
  • RunInteractive: StartShellSession(Session.Meta.Id) + SetCurrentSessionId before the loop, CloseShellSession in finally.
  • THeartbeat.TickOnce: per-tick session id (heartbeat-tick-N) so each tick gets its own container, torn down via finally.

Phase 1 scope (documented refuse-to-start otherwise)

  • pasclaw tui, pasclaw serve, pasclaw gateway refuse docker cleanly. TUI's in-process session switching (/new, /load) needs container handoff; serve/gateway's multi-tenant request flow needs cross-thread session-id propagation. Both are Phase 1.5.

Test plan

  • FPC make smoke clean (clean rebuild from scratch).
  • Full make test green (34 targets, +1 new: test-shell-backend).
  • pasclaw status shows the active backend.
  • Local backend round-trips identical to today's behaviour (output_cache, condense, promptware tests all pass — they go through Tool_Shell which now dispatches via the local backend).
  • Manual docker smoke: pick docker in onboarding, run pasclaw agent -i, model issues shell_exec("uname -a"), see it report the container's kernel instead of the host's. docker ps shows pasclaw-<sessionid> during the session.
  • Manual heartbeat-docker: enable heartbeat + docker, run pasclaw heartbeat --once, see pasclaw-heartbeat-tick-1 come and go.

Tests

shell_backend_tests (5 cases) pins:

  • no-backend fallback to PasClaw.Platform.RunOneShot
  • TLocalShellBackend round-trip
  • SetCurrentSessionId round-trip
  • dispatch goes through the active backend (via a recording mock backend — proves the docker case would also route correctly without needing docker on CI)
  • RunOneShotWithEnvViaBackend dispatch

End-to-end docker is exercised manually; spawning a container per unit test would need docker available in CI, which we don't currently require.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

Adds an IShellBackend abstraction so shell_exec / execute_code can
run somewhere other than the host process. Phase 1 ships two impls --
local (the historical default) and docker (per-session container);
Phase 2 will add ssh behind the same interface.

Architecture
  PasClaw.Shell.Backend.pas       interface IShellBackend +
                                  process-global active backend +
                                  RunOneShot{,WithEnv}ViaBackend
                                  wrappers Tool_Shell /
                                  Tool_ExecuteCode call into.
  PasClaw.Shell.Backend.Local.pas TLocalShellBackend -- thin wrapper
                                  around PasClaw.Platform.RunOneShot.
                                  StartSession / CloseSession no-op
                                  (host process IS the session).
  PasClaw.Shell.Backend.Docker.pas TDockerShellBackend -- spawns a
                                  long-running idle container at
                                  StartSession (`tail -f /dev/null`
                                  so it doesn't exit), `docker exec`s
                                  into it per call, stops at
                                  CloseSession.
                                    - workspace + tmp + run bind-
                                      mounted at the SAME path (so
                                      MakeTempScript paths and
                                      tool-RPC info files Just Work)
                                    - config.json (provider keys),
                                      cache/, logs/ deliberately not
                                      mounted
                                    - empty SessionId falls back to
                                      RunOneShot per documented
                                      contract (one-shot pasclaw -m
                                      doesn't pay container startup)
                                    - container name pasclaw-<id>
                                      sanitised + truncated for
                                      docker's regex
  PasClaw.Shell.Backend.Factory.pas InstallShellBackend -- reads
                                  Cfg.ShellBackend + --backend
                                  override, builds + installs the
                                  matching impl. Raises clear
                                  exceptions on docker-daemon
                                  unreachable; loud-not-silent so
                                  the operator sees the security
                                  intent failed.

Config / onboarding
  - TConfig.ShellBackend (sbLocal default) +
    TConfig.ShellBackendDocker {image, network, user, privileged}.
  - "shell_backend": "local" | "docker" round-trips in config.json;
    "shell_backend_docker" subobject emitted when docker is on or
    defaults diverge.
  - PromptShellBackend in `pasclaw onboard`: y/N + image + network
    follow-ups when docker is picked.

CLI surface
  - --backend local|docker overrides config per-run on `pasclaw
    agent`, `pasclaw tui`, `pasclaw heartbeat`.
  - `pasclaw status` shows the active backend.
  - shell_exec tool description names the backend so the model
    knows where its commands run (e.g. `apt install` won't persist
    past a per-session container).

Lifecycle wiring
  - Cmd_Agent_Run installs the backend after ConfigureSandbox,
    refuses startup on docker-not-available.
  - RunInteractive: StartShellSession(Session.Meta.Id) +
    SetCurrentSessionId before the loop, CloseShellSession in
    finally.
  - THeartbeat.TickOnce: per-tick session id (heartbeat-tick-N)
    so each tick gets its own container, torn down via finally.

Phase 1 scope (documented refuse-to-start otherwise)
  - `pasclaw tui`, `pasclaw serve`, `pasclaw gateway` refuse docker
    cleanly (per-session container handoff in their multi-tenant /
    in-process-session-switch flows is Phase 1.5).

Tests: shell_backend_tests (5 cases) pins
  - no-backend fallback to PasClaw.Platform.RunOneShot
  - TLocalShellBackend round-trip
  - SetCurrentSessionId round-trip
  - dispatch goes through active backend (recording mock)
  - RunOneShotWithEnvViaBackend dispatch
End-to-end docker is exercised manually; spawning a container per
test would need docker on CI which we don't currently require.

FPC make smoke + full make test (34 targets, +1 new) green. README
section added under Heartbeat. dproj updated.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 19f6c7474b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

daemon isn't available. The interesting case -- interactive
session, model issuing commands -- always has a SessionId.
Documented per-impl on IShellBackend.StartSession's contract. }
if (Trim(SessionId) = '') or (not IsRunning(SessionId)) then

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Do not fall back to host when docker has no session

When pasclaw agent -m ... --backend docker (or a docker config) reaches shell_exec/execute_code, RunSingleTurn never calls StartShellSession or SetCurrentSessionId, so GetCurrentSessionId is empty and this branch runs the command on the host via RunOneShot*. That bypasses the isolation the operator explicitly selected and the tool description advertises; allocate a temporary session for one-shot runs or fail instead of silently executing locally.

Useful? React with 👍 / 👎.

Comment thread src/cmd/PasClaw.Cmd.Serve.pas Outdated
Refuse docker here loudly so an operator who flipped on docker
globally doesn't silently end up on the host when they hit the
serve / gateway endpoints. }
if Cfg.ShellBackend = sbDocker then

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Parse --no-tools before rejecting docker serve

With shell_backend=docker in config, pasclaw serve --no-tools still exits here because the docker gate runs before ParseServe reads the flag, even though the message tells operators to use --no-tools and a tool-disabled server does not need shell isolation. The gateway path has the same ordering; parse args first and only reject docker when tools are enabled.

Useful? React with 👍 / 👎.

claude added 2 commits June 12, 2026 05:55
…:24.04 (~80 MB)

bookworm-slim is the Debian-canonical alias for debian:12-slim (same
digest, just the codename convention upstream Dockerfiles use). ~30 MB
smaller pull than ubuntu:24.04 and a faster cold-start; behaviourally
transparent to the model since both are GNU/glibc with the same bash,
coreutils, and apt-get. Operators who want maximum ubuntu compatibility
can still override during `pasclaw onboard` or in config.json.

Alpine considered and skipped as default: 16x smaller again but musl
libc + BusyBox utilities silently break subtly different command
behaviours (find -printf, xargs -d, grep -P, sed -i ''), which makes
"why did this shell command fail?" debugging worse. Operators who care
about the size win can pick alpine explicitly.

FPC make smoke + full make test still green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
…cker gate

Two from Codex on PR #233, both legit:

P1 -- Docker.Exec must never fall back to host. The previous
empty-SessionId path routed to PasClaw.Platform.RunOneShot, which
silently bypassed the isolation the operator selected and the
shell_exec tool description advertised.

  - RunSingleTurn (`pasclaw agent -m ...`) now allocates a synthetic
    one-shot session id around the loop (StartShellSession +
    SetCurrentSessionId, CloseShellSession in finally) so the
    docker backend has a real container for the model's tools.
  - TDockerShellBackend.StartSession with '' now RAISES (programmer
    bug -- forgotten lifecycle call); Exec with '' returns -1 with
    a clear diagnostic in Output instead of dispatching to the
    host. The Local backend still ignores SessionId, so the
    extra strictness only affects docker / ssh.
  - shell_backend_tests gains TestDockerRefusesEmptySessionId
    pinning the contract -- runs without docker on the box since
    the validation paths fail before any subprocess.

P2 -- Parse --no-tools before rejecting docker on serve/gateway.
The previous order rejected `pasclaw serve --no-tools` with
shell_backend=docker in config even though a tool-disabled server
never dispatches shell_exec, so the isolation story doesn't apply.
The help text even told operators to use --no-tools but the gate
ran before ParseServe / ParseGw read it. Moved both gates to after
ParseServe / ParseGw and added a `not Args.NoTools` clause.

FPC make smoke + full make test (35 targets) green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit ca4b931 into main Jun 12, 2026
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
Both changelog files were stuck at the 2026-06-10 TUI / background-
subagent / session_search / tool-RPC entries. ~7 weeks of merged
PRs (#214 through #244) had landed without a corresponding entry in
either file -- the git log was the only record of features like the
knowledgebase, inbound MCP server mode, checkpoints + /undo,
heartbeat daemon, shell backends (local | docker), send_message,
promptware defense, Windows shell-output encoding fixes, fs_grep
ripgrep optimisations, OpenTelemetry traces, and `pasclaw agent
--quiet`.

Added (newest first):

  2026-06-13
    #244  agent --quiet log-level clamp

  2026-06-12
    #243  dcc64 search path + agent --quiet / -q
    #242  OpenTelemetry traces (OTLP/HTTP+JSON)
    #241  fs_grep tier 5+6 (byte walker + Boyer-Moore-Horspool)
    #240  fs_grep tier 1-4 (deferred hash + skip-dirs + binary
          sniff + size cap)

  2026-06-11
    #239  Windows shell output: auto-detect UTF-8 vs OEM
    #238  Hashline fs_read header mojibake fix (¶ vs ¶)
    #237  Windows shell output: OEM codepage decode

  2026-06-10
    #233  Shell backends (local | docker via IShellBackend)
    #232  Heartbeat daemon + reversible condensation (CCR)
    #230  send_message tool + condenser families + promptware
          defense + task-aware MEMORY.md slicing

  2026-06-09
    #223  /goal Ralph loop + judge model + JSON-aware condenser
    #222  /undo wired into agent + sample dprojs
    #221  Checkpoints (auto-snapshot + TUI /undo)
    #220  mcp catalog: lenient hub projector
    #219  mcp: SSE / Streamable HTTP / stdio hub transports
    #218  Inbound MCP server mode
    #217  onboard: offer to index docs into the knowledgebase
    #214  Knowledgebase (RAG over operator-curated docs)

Skipped from this changelog (build-system / Delphi-fix / FPC-fix
PRs visible in the git log but not user-facing features):
#215, #216, #224, #225, #226, #227, #228, #229, #231, #234, #236.

Both files (README.md and docs/changelog.md) updated with the same
entries -- intentional mirror so a reader on either surface sees
the same history. Same prose in both; same footnote refs at the
bottom.

Validated: every [#N] reference in both files has a matching [#N]:
URL footnote (no broken links).
FMXExpress pushed a commit that referenced this pull request Jun 15, 2026
Previously serve/agent/gateway probed Docker (docker info) and spawned the
session container up front, so a down/slow/wedged Docker daemon blocked
startup even when no chat ever used a shell tool. Make it lazy:

- InstallShellBackend no longer probes Docker (no boot-time docker info).
- TDockerShellBackend.Exec spawns the container on the first
  shell_exec/execute_code -- health-probing (bounded docker info) then
  pull+run -- and surfaces any failure as that tool's result. Still no
  host fallback, so isolation is preserved (Codex P1 #233 intact).
- serve/agent/gateway set the current session id but no longer call
  StartShellSession; the finally cleanup is a no-op when nothing spawned.

Net: these commands start instantly regardless of Docker state; only chats
that actually run a shell tool pay the cost or see Docker errors. Combined
with the bounded info/stop timeouts, a stuck daemon can no longer hang the
app. (StartShellSession stays for TUI/heartbeat and remains valid as an
optional eager pre-spawn; Exec's IsRunning check makes it idempotent.)
FMXExpress pushed a commit that referenced this pull request Jun 21, 2026
Per review feedback: early changelog entries are typically 60-200
chars; entries I added in the catch-up commit ran 250-1111 chars.
Trimmed each of the 20 new entries to fit the historical band:

  Before  count: 20  min: 252  max: 1111  avg: 580
  After   count: 20  min: 208  max:  580  avg: 359

Cuts applied:

  - Drop implementation detail (file paths, internal field names,
    "the only X tool in Y that does Z" asides)
  - Drop test-count call-outs
  - Drop future-facing notes ("plus follow-up work that ...")
  - Collapse aspect-by-aspect breakdowns into single-clause WHAT +
    one constraint
  - Keep the PR's headline change + its most distinctive token
    (config flag, command name, endpoint path, file convention)

Both README.md and docs/changelog.md updated identically. Same 20
PRs, same dates, same order, same link-ref block -- just leaner
prose. Going forward I'll target ~200-400 char entries for new
feature PRs, with up to ~600 only for actual big-feature parents
(matches existing entries like #232 Heartbeat at 844 chars or
#233 shell backends at 783).
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
dcc64 F2613 'Unit PasClaw.Shell.Backend not found' at the
PasClaw.Config interface uses clause. PR FMXExpress#233 added the
src/pkg/shell/ directory and registered the four shell-backend
units as DCCReference entries, but missed adding the directory to
the DCC_UnitSearchPath. dcc64 needs both -- DCCReference is the
IDE's source-tree listing, the unit search path is what the
compiler walks to resolve `uses`.

Added ..\pkg\shell to:
  - src/pasclaw/PasClaw.dproj (the main binary build)
  - samples/component-console/SampleServer.dproj
  - samples/component-console/SampleConsole.dproj
  - samples/component-console/SampleSimple.dproj
  - samples/component-console/dcc32.cfg + dcc64.cfg
  - samples/component-console/Makefile

FPC build untouched (its repo-root Makefile already had src/pkg/shell
from PR FMXExpress#233); make smoke + full make test green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
Codex P2 on PR FMXExpress#234, legit. PR FMXExpress#234 fixed the IDE/msbuild path via
PasClaw.dproj's DCC_UnitSearchPath but missed the dcc64.exe fallback
in build-delphi.bat -- its hard-coded UNIT_PATH still lacked
src\pkg\shell, so the documented "msbuild.exe not on PATH" fallback
continued to F2613 on PasClaw.Shell.Backend through PasClaw.Config's
new uses-line.

Added src\pkg\shell to both:
  - build-delphi.bat (the actual review target)
  - build-fpc.bat (same class of bug, same root cause -- PR FMXExpress#233
    added the directory and only some build paths got updated)

Position matches the other batch's ordering (after pkg\markdown,
before pkg\vendor\dmvcframework).

FPC make smoke clean.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
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