oficina / equipo Public

Merge main into copy-specialist

Paul Campbell pushed by paul@keymail.dev b24a13f626c9a750ac0e6754ef7ad09f353cd892 parent 31f8258parent dc62df5
24 files changed, +736 −77
  • .rastrillo/budgets.txt +2 −2
  • docs/superpowers/specs/2026-11-13-pi-isolated-shell.md +69 −0
  • internal/fakepi/tensorx.go +19 −3
  • internal/runner/containment/engineering_shell_test.go +1 −1
  • internal/runner/containment/mounts.go +5 −0
  • internal/runner/containment/pi_linux_test.go +2 −2
  • internal/runner/provider/check_policy.go +29 −13
  • internal/runner/provider/go_policy.go +3 −0
  • internal/runner/provider/pi/batch_linux_test.go +84 −0
  • internal/runner/provider/pi/go_probe_test.go +90 −0
  • internal/runner/provider/pi/harness_test.go +9 −8
  • internal/runner/provider/pi/home.go +9 −2
  • internal/runner/provider/pi/real_test.go +18 −29
  • internal/runner/provider/pi/shell_test.go +150 −0
  • internal/runner/provider/pi_extension.ts +37 −9
  • internal/runner/provider/pi_go.go +54 −0
  • internal/runner/provider/pi_guards_test.go +70 −0
  • internal/runner/provider/pi_policy_test.go +5 −5
  • internal/runner/provider/pi_shell.go +13 −0
  • internal/runner/provider/pi_shell.sh +26 −0
  • internal/runner/provider/types.go +1 −0
  • internal/runner/thin/opencodestep.go +1 −1
  • internal/runner/thin/pi_go_test.go +37 −0
  • scripts/runner-reference-allowlist.json +2 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 03107ef6..d7cf95d0 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -26,7 +26,7 @@ time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI se
time internal/runner/provider/codex 35s Plan 3 CI repair measured 24.464s for the full package (controller CI 27.908s).
time internal/runner/provider/pi 60s The real pinned Pi in bubblewrap against a fake TensorX: probes P1 to P5 (a hundred RPC turns), the hostile repository, and the pinned tree checked whole (about 160 MB); measured 22s locally.
time internal/runner/provider/opencode 90s The real pinned OpenCode in bubblewrap against a fake Go: probes, the hostile repository per source, termination, resume; the 260 MB binary hashed per launch. Measured 40s.
-size internal/runner/provider 5362 - Engineering retains Go tree descriptors and reuses one root digest per lease. Checks keep path pins. Tree traversal lives in gotoolchain. Measured 5362 source lines.
+size internal/runner/provider 5448 - Pi adds a pinned isolated shell, immutable configuration files and offline Go with retained tree descriptors. Shared tree traversal remains in gotoolchain. Measured 5448 source lines.
time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops.
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 25086 17166 Copy validation lives in copydesk; contained execution and publication use the runner’s private state and launch helpers.
+size internal/runner/thin 25086 17203 Copy validation lives in copydesk; contained execution and publication use the runner’s private state and launch helpers.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
diff --git a/docs/superpowers/specs/2026-11-13-pi-isolated-shell.md b/docs/superpowers/specs/2026-11-13-pi-isolated-shell.md
new file mode 100644
index 00000000..e5748d08
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-13-pi-isolated-shell.md
@@ -0,0 +1,69 @@
+# Pi shell isolation and offline Go
+
+Paul approved this containment change on 2026-11-13 ("fix it all up"). This
+controller design supersedes the Pi Bash exception in the connectors spec,
+section 2.1, and the Pi deferral in the Engineering toolchain spec.
+
+Pi 1.5.2's `dist/core/tools/bash.js` calls `createLocalBashOperations`, then
+spawns the configured shell. `dist/utils/shell.js:getShellEnv` copies the CLI
+environment. Equipo supplies the provider key through the secret argument pipe
+(`containment/mounts.go:addSecretEnv`); the credential home itself is never
+mounted. The old shell could read that variable and the CLI's `/proc` files.
+It also shared the relay at `127.0.0.1:18080` and `/egress/proxy.sock`
+(`containment/egress.go`). Equipo's extension approved calls without adding a
+sandbox. The previous `TestPiP4AStepCanReadTheKey` explicitly asserted this.
+
+Use Pi's existing `shellPath` setting, fixed to `/config/pi/bash`. No Pi patch
+or package pin change is needed. In the pinned tree,
+`dist/core/agent-session.js` uses `getShellPath()` both to construct the Bash
+tool and in `executeBash`; `dist/utils/shell.js:getShellConfig` passes `-c`
+and the command separately to the configured executable. Missing wrappers fail
+closed. The wrapper passes the command as one argument to Bash after bubblewrap
+has created the sandbox. It never evaluates the command in the CLI namespace.
+
+The wrapper uses absolute executable paths, including setup before isolation.
+It starts bubblewrap through `env -i`, then clears the child environment again;
+otherwise bubblewrap itself can retain the key in its process environment.
+The wrapper is embedded in Equipo, checked against its compiled digest and
+mounted read-only, with the pinned bubblewrap executable. It creates fresh
+user, PID, network, IPC and UTS namespaces, drops capabilities, disables nested
+user namespaces, clears the environment and mounts a fresh `/proc` and `/dev`.
+The filesystem contains read-only `/usr` and `/etc`, a writable workspace and
+shell-only temporary directory, and an empty home. The CLI's home, config,
+package tree, key file, tool socket and relay socket are absent. Shell exit
+also ends its background processes. Pi's native file tools are confined to the
+workspace by a path check when each call is gated; its settings, model and MCP
+files are individually mounted read-only. The containing directory stays
+writable for Pi's settings lock.
+
+Pi gates every call in one assistant message before running them together, so
+the gate-time path check alone could race a shell command that swaps a checked
+path for a link. Equipo's extension therefore never lets a file tool and a
+shell command run at the same time: whichever is gated second while the other
+is still running is refused ("Run file tools and shell commands in separate
+messages"). Calls of one kind still run in parallel, and separate messages run
+in turn. TestPiBatchSeparatesShellAndFileTools covers both orders with a
+positive control. The shell inherits only stdio (TestPiShellInheritedDescriptors).
+
+Engineering gets the same configured Go root and optional module cache as
+Claude and Codex. A Pi attempt retains directory descriptors using the shared
+Go pinning code; cleanup closes them. Only the Go root is hashed. Both outer
+and inner mounts are read-only. The inner environment sets local toolchain,
+offline module resolution and private scratch, disables Go environment files,
+workspace discovery, telemetry and CGO, and ignores global Git configuration.
+Review and answer roles keep their existing tool sets and get no Go mounts.
+A missing module cache is omitted; an invalid existing cache is refused.
+
+The real pinned Pi runs against the existing local fake provider in tests.
+Shell and Go-built probes test credential files, inherited and process
+variables, TCP relay and Unix sockets. The same Go binary runs outside the
+sandbox as a positive control, reporting only whether access succeeded. An
+import from a prepared module cache proves offline `go test`; writes to both
+trees must fail. Mutation checks remove each boundary and must fail its guard.
+These offline probes do not replace provider release certification.
+
+The Pi policy format advances to `pi-v2`, so old policies cannot silently
+retain the old shell behavior. No wire protocol or database migration changes
+are needed. `origin/copy-specialist` already reserves protocol 21 and migration
+0081; this change consumes neither. Rollback uses the previous versioned
+release and its matching certificates, restoring the old Pi shell limitation.
diff --git a/internal/fakepi/tensorx.go b/internal/fakepi/tensorx.go
index 9d5aa9e5..5dc5b490 100644
--- a/internal/fakepi/tensorx.go
+++ b/internal/fakepi/tensorx.go
@@ -174,9 +174,25 @@ func (f *TensorX) serve(w http.ResponseWriter, r *http.Request) {
if role == "user" {
text = steps(text)
}
- if role == "user" && strings.HasPrefix(text, "CALL ") {
- parts := strings.SplitN(text, " ", 3)
- chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "tool_calls": []any{map[string]any{"index": 0, "id": "call_1", "type": "function", "function": map[string]any{"name": parts[1], "arguments": parts[2]}}}}}}))
+ if role == "user" && (strings.HasPrefix(text, "CALL ") || strings.HasPrefix(text, "BATCH ")) {
+ var calls []struct {
+ Name string `json:"name"`
+ Arguments json.RawMessage `json:"arguments"`
+ }
+ if strings.HasPrefix(text, "BATCH ") {
+ _ = json.Unmarshal([]byte(strings.TrimPrefix(text, "BATCH ")), &calls)
+ } else {
+ parts := strings.SplitN(text, " ", 3)
+ calls = append(calls, struct {
+ Name string `json:"name"`
+ Arguments json.RawMessage `json:"arguments"`
+ }{parts[1], json.RawMessage(parts[2])})
+ }
+ var batch []any
+ for i, c := range calls {
+ batch = append(batch, map[string]any{"index": i, "id": fmt.Sprintf("call_%d", i+1), "type": "function", "function": map[string]any{"name": c.Name, "arguments": string(c.Arguments)}})
+ }
+ chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "tool_calls": batch}}}))
chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "tool_calls"}}))
} else {
reply := "ok done"
diff --git a/internal/runner/containment/engineering_shell_test.go b/internal/runner/containment/engineering_shell_test.go
index 0c2b07de..35e24934 100644
--- a/internal/runner/containment/engineering_shell_test.go
+++ b/internal/runner/containment/engineering_shell_test.go
@@ -20,7 +20,7 @@ import (
// Fake CLIs run Bash through the pinned builders' namespace and mask layout.
// No model endpoint, real credential, or permissive sandbox fallback is used.
func TestEngineeringShellNesting(t *testing.T) {
- for _, name := range []string{"claude", "codex", "pi"} {
+ for _, name := range []string{"claude", "codex"} {
t.Run(name, func(t *testing.T) {
m, l := fixture(t)
b := provider.Binding{Provider: name, Home: "/fake-runtime", CredentialHome: "/fake-source", RuntimeRoot: "/fake-homes"}
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go
index 3ce1c15d..6185ff15 100644
--- a/internal/runner/containment/mounts.go
+++ b/internal/runner/containment/mounts.go
@@ -364,6 +364,11 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error
}
allowed[k] = true
}
+ for _, name := range []string{"settings.json", "models.json", "mcp.json"} {
+ if err = p.bind(filepath.Join(runtimeHome, "agent", name), "/home/runner/agent/"+name, true, false); err != nil {
+ return nil, err
+ }
+ }
allowed["EQUIPO_PI_TOOLS"] = true
allowed["EQUIPO_PI_CONFINE"] = l.Policy.Env["EQUIPO_PI_CONFINE"] == "/workspace"
allowed["NODE_EXTRA_CA_CERTS"] = provider.TestCAAllowed()
diff --git a/internal/runner/containment/pi_linux_test.go b/internal/runner/containment/pi_linux_test.go
index 0299f6a9..0fb239d4 100644
--- a/internal/runner/containment/pi_linux_test.go
+++ b/internal/runner/containment/pi_linux_test.go
@@ -67,9 +67,9 @@ func piLaunch(t *testing.T, m *Manager) (provider.Launch, []string, string) {
os.Chmod(filepath.Join(sockDir, "equipo.sock"), 0600)
nodeSum := sha256Hex(trueBin)
in := provider.PiPolicyInputs{Node: node, NodeSHA256: nodeSum, Tree: tree, TreeSHA256: sum, Bwrap: "/usr/bin/bwrap", ToolProxy: put("proxy", "proxy", 0755), Extension: put("equipo.ts", string(provider.PiExtensionSource()), 0600),
- Home: home, Workspace: work, Action: "inspect", Provider: "tensorx", Model: "z-ai/glm-5.3", KeyEnv: "TENSORX_API_KEY", Tools: []string{"read", "grep", "find", "ls", "mcp__equipo__submit_review"}, EgressHosts: []string{"api.tensorx.ai"},
+ Shell: put("bash", string(provider.PiShellSource()), 0700), Home: home, Workspace: work, Action: "inspect", Provider: "tensorx", Model: "z-ai/glm-5.3", KeyEnv: "TENSORX_API_KEY", Tools: []string{"read", "grep", "find", "ls", "mcp__equipo__submit_review"}, EgressHosts: []string{"api.tensorx.ai"},
Models: json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"$TENSORX_API_KEY","baseUrl":"https://api.tensorx.ai/v1","models":[{"id":"z-ai/glm-5.3"}]}}}`),
- Settings: json.RawMessage(`{"defaultProjectTrust":"never"}`),
+ Settings: provider.PiSettings,
MCP: json.RawMessage(`{"autoEnableCodemode":false,"mcpServers":{"equipo":{"args":["--socket","/tool/equipo.sock"],"command":"/opt/equipo-tool-proxy","exposure":"direct"}}}`)}
if err := provider.WritePiConfig(in); err != nil {
t.Fatal(err)
diff --git a/internal/runner/provider/check_policy.go b/internal/runner/provider/check_policy.go
index 0af25533..2ea5325b 100644
--- a/internal/runner/provider/check_policy.go
+++ b/internal/runner/provider/check_policy.go
@@ -135,7 +135,7 @@ func attestCheck(l Launch, argv []string) (string, error) {
// sessions in that home, and the tools the role pins. The key is not in
// it: it reaches the namespace as KeyEnv through the secret pipe.
-const piPolicyVersion = "pi-v1"
+const piPolicyVersion = "pi-v2"
// Paths inside a Pi namespace.
const (
@@ -171,7 +171,7 @@ func PiExtensionSHA256() string { return digest(piExtension) }
// PiSettings is settings.json: project trust never granted, whatever a
// flag or a project says.
-var PiSettings = json.RawMessage(`{"defaultProjectTrust":"never"}`)
+var PiSettings = json.RawMessage(`{"defaultProjectTrust":"never","shellPath":"/config/pi/bash"}`)
// PiMCP is mcp.json: Equipo's own tools only, through the tool proxy on
// the attempt's socket, declared to the model directly (no codemode, no
@@ -198,6 +198,8 @@ var piWriteTools = []string{"bash", "edit", "write"}
type PiPolicyInputs struct {
Node, NodeSHA256, Tree, TreeSHA256 string
Bwrap, ToolProxy, Extension string
+ Shell, GoRoot, ModuleCache string
+ GoLease *GoLease
Home, Workspace, Action string
Provider, Model, KeyEnv string
Tools, EgressHosts []string
@@ -230,11 +232,9 @@ func PiArgv(in PiPolicyInputs) []string {
// piEnv is Pi's environment: its config directory, every startup fetch
// off (version check, catalogue, telemetry), and the extension's gate.
-func piEnv(in PiPolicyInputs, readOnly bool) map[string]string {
+func piEnv(in PiPolicyInputs) map[string]string {
env := map[string]string{"LANG": "C.UTF-8", "PI_CODING_AGENT_DIR": PiAgentDir, "PI_OFFLINE": "1", "PI_SKIP_VERSION_CHECK": "1", "PI_TELEMETRY": "0", "EQUIPO_PI_TOOLS": strings.Join(in.Tools, ",")}
- if readOnly {
- env["EQUIPO_PI_CONFINE"] = "/workspace"
- }
+ env["EQUIPO_PI_CONFINE"] = "/workspace"
if in.ExtraCA != "" {
env["NODE_EXTRA_CA_CERTS"] = piTestCA
}
@@ -379,11 +379,11 @@ func BuildPiPolicy(in PiPolicyInputs) (Policy, error) {
return Policy{}, ErrPolicy
}
}
- readOnly := profile.ReadOnly
- m := effectiveManifest{Version: piPolicyVersion, Action: in.Action, Provider: in.Provider, Harness: "pi", KeyEnv: in.KeyEnv, Argv: PiArgv(in), Env: piEnv(in, readOnly), NamespaceArgs: NamespaceArguments(), Workspace: in.Workspace, RuntimeHome: in.Home, Tools: slices.Clone(in.Tools), Settings: settings, MCP: mcp, Catalog: models}
+ m := effectiveManifest{Version: piPolicyVersion, Action: in.Action, Provider: in.Provider, Harness: "pi", KeyEnv: in.KeyEnv, Argv: PiArgv(in), Env: piEnv(in), NamespaceArgs: NamespaceArguments(), Workspace: in.Workspace, RuntimeHome: in.Home, Tools: slices.Clone(in.Tools), Settings: settings, MCP: mcp, Catalog: models}
m.EgressHosts = slices.Clone(in.EgressHosts)
sort.Strings(m.EgressHosts)
m.OuterMounts = []Mount{{Source: in.Node, Target: PiNode, ReadOnly: true}, {Source: in.Tree, Target: PiTree, ReadOnly: true}, {Source: in.ToolProxy, Target: "/opt/equipo-tool-proxy", ReadOnly: true}, {Source: in.Extension, Target: PiExtension, ReadOnly: true}}
+ m.OuterMounts = append(m.OuterMounts, Mount{Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true}, Mount{Source: in.Shell, Target: PiShell, ReadOnly: true})
if in.ExtraCA != "" {
m.OuterMounts = append(m.OuterMounts, Mount{Source: in.ExtraCA, Target: piTestCA, ReadOnly: true})
}
@@ -398,15 +398,20 @@ func BuildPiPolicy(in PiPolicyInputs) (Policy, error) {
m.Files = append(m.Files, f)
}
for _, f := range m.Files {
+ if f.Mount.Target == PiShell && f.SHA256 != digest(PiShellSource()) {
+ return Policy{}, ErrPolicy
+ }
if f.Mount.Target == PiExtension && f.SHA256 != PiExtensionSHA256() {
return Policy{}, ErrPolicy
}
}
- bwrap, err := piFile(Mount{Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true})
- if err != nil {
- return Policy{}, err
+ for _, name := range []string{"settings.json", "models.json", "mcp.json"} {
+ f, err := piFile(Mount{Source: filepath.Join(in.Home, "agent", name), Target: PiAgentDir + "/" + name, ReadOnly: true})
+ if err != nil {
+ return Policy{}, err
+ }
+ m.Files = append(m.Files, f)
}
- m.Files = append(m.Files, bwrap)
if m.Files[0].SHA256 != in.NodeSHA256 {
return Policy{}, ErrTree
}
@@ -418,11 +423,14 @@ func BuildPiPolicy(in PiPolicyInputs) (Policy, error) {
return Policy{}, ErrTree
}
m.Trees = []treePin{{Mount: m.OuterMounts[1], SHA256: tree}}
+ if err := piGoPolicy(in, &m); err != nil {
+ return Policy{}, err
+ }
raw, hash, err := hashJSON(m)
if err != nil {
return Policy{}, err
}
- return Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: m.Env, Settings: settings, MCP: mcp}, nil
+ return Policy{goLease: in.GoLease, Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: m.Env, Settings: settings, MCP: mcp}, nil
}
// piSessionID is an id Pi accepts for --session-id, never a path.
@@ -478,6 +486,14 @@ func attestPi(l Launch, argv []string) (string, error) {
return "", ErrPolicy
}
for _, f := range m.Files {
+ if gotoolchain.Target(f.Mount.Target) {
+ held, err := p.OpenGoTree(l.Binding, f.Mount)
+ if err != nil {
+ return "", err
+ }
+ held.Close()
+ continue
+ }
current, err := piFile(f.Mount)
if err != nil || current.SHA256 != f.SHA256 {
return "", ErrPolicy
diff --git a/internal/runner/provider/go_policy.go b/internal/runner/provider/go_policy.go
index 280f4b4c..ab70ac70 100644
--- a/internal/runner/provider/go_policy.go
+++ b/internal/runner/provider/go_policy.go
@@ -86,6 +86,9 @@ func (p Policy) OpenGoTree(b Binding, mount Mount) (*os.File, error) {
return openGoDirectory(mount)
}
l := b.provenance
+ if p.IsPi() && p.goLease != nil {
+ l = &p.goLease.lease
+ }
if l == nil {
return nil, ErrPolicy
}
diff --git a/internal/runner/provider/pi/batch_linux_test.go b/internal/runner/provider/pi/batch_linux_test.go
new file mode 100644
index 00000000..07e2399e
--- /dev/null
+++ b/internal/runner/provider/pi/batch_linux_test.go
@@ -0,0 +1,84 @@
+package pi
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// Pi gates every call in a message before running them together. A file
+// tool and a shell command in one message must never both run: the shell
+// could swap a checked path for a link before the file tool opens it.
+func TestPiBatchSeparatesShellAndFileTools(t *testing.T) {
+ h := newHarness(t, realInstall(t))
+ work := t.TempDir()
+ for _, name := range []string{"a.txt", "b.txt"} {
+ if err := os.WriteFile(filepath.Join(work, name), []byte("plain\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ r := h.open(work, "implement", []string{"submit_candidate"}, "")
+ batch := func(calls ...map[string]any) []ToolResult {
+ t.Helper()
+ raw, _ := json.Marshal(calls)
+ got := results(r.prompt(t, "BATCH "+string(raw), "allow"))
+ if len(got) != len(calls) {
+ t.Fatalf("batch returned %d results, want %d", len(got), len(calls))
+ }
+ return got
+ }
+ bash := map[string]any{"name": "bash", "arguments": map[string]string{"command": "echo shell-ran"}}
+ read := func(name string) map[string]any {
+ return map[string]any{"name": "read", "arguments": map[string]string{"path": "/workspace/" + name}}
+ }
+ // Results arrive in completion order; a refused call is an error result
+ // (the files exist, so a read that runs does not error).
+ refused := func(res ToolResult) bool { return res.IsError }
+ byTool := func(rs []ToolResult, tool string) ToolResult {
+ t.Helper()
+ for _, r := range rs {
+ if r.Tool == tool {
+ return r
+ }
+ }
+ t.Fatalf("no %s result in %+v", tool, rs)
+ return ToolResult{}
+ }
+ // Positive control: file tools alone, and a shell command alone, run.
+ for _, res := range batch(read("a.txt"), read("b.txt")) {
+ if refused(res) {
+ t.Fatal("two file reads in one message were refused")
+ }
+ }
+ if res := batch(bash); refused(res[0]) {
+ t.Fatal("a lone shell command was refused")
+ }
+ // Shell first: the read must not run beside it.
+ if res := batch(bash, read("a.txt")); refused(byTool(res, "bash")) || !refused(byTool(res, "read")) {
+ t.Fatalf("shell then read: %+v", res)
+ }
+ // File tool first: the shell command must not run beside it.
+ if res := batch(read("a.txt"), bash); refused(byTool(res, "read")) || !refused(byTool(res, "bash")) {
+ t.Fatalf("read then shell: %+v", res)
+ }
+ // Separate messages still work in turn.
+ if res := batch(read("a.txt")); refused(res[0]) {
+ t.Fatal("a read after a mixed batch was refused")
+ }
+}
+
+func TestPiShellInheritedDescriptors(t *testing.T) {
+ h := newHarness(t, realInstall(t))
+ r := h.open(t.TempDir(), "implement", []string{"submit_candidate"}, "")
+ shellOK(t, h, r, `python3 - <<'PY'
+import os
+fds=[]
+for name in os.listdir('/proc/self/fd'):
+ try: os.fstat(int(name))
+ except OSError: continue
+ fds.append(int(name))
+assert sorted(fds)==[0,1,2],sorted(fds)
+print('stdio-only')
+PY`, "stdio-only")
+}
diff --git a/internal/runner/provider/pi/go_probe_test.go b/internal/runner/provider/pi/go_probe_test.go
new file mode 100644
index 00000000..cc5364c3
--- /dev/null
+++ b/internal/runner/provider/pi/go_probe_test.go
@@ -0,0 +1,90 @@
+package pi
+
+import (
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+const piGoProbe = `package main
+import("bytes";"fmt";"net";"os";"path/filepath";"time")
+func main(){
+ mode:=os.Args[1]; exposed:=false
+ switch mode {
+ case "env": _,exposed=os.LookupEnv("TENSORX_API_KEY")
+ case "proc":
+ files,_:=filepath.Glob("/proc/[0-9]*/environ")
+ tasks,_:=filepath.Glob("/proc/[0-9]*/task/*/environ")
+ for _,p:=range append(files,tasks...){ b,_:=os.ReadFile(p);if bytes.Contains(b,[]byte("TENSORX_API_KEY=")){exposed=true} }
+ case "processes":
+ files,_:=filepath.Glob("/proc/[0-9]*/cmdline")
+ for _,p:=range files { b,_:=os.ReadFile(p);if (bytes.HasPrefix(b,[]byte("pi-rpc\x00"))||bytes.HasPrefix(b,[]byte("pi\x00"))){exposed=true} }
+ case "file": b,e:=os.ReadFile(os.Args[2]);exposed=e==nil&&len(b)>0
+ case "tcp", "unix": c,e:=net.DialTimeout(mode,os.Args[2],time.Second);if e==nil{exposed=true;c.Close()}
+ }
+ if exposed{fmt.Println("exposed")}else{fmt.Println("isolated")}
+}
+`
+
+func goHarness(t *testing.T) *harness {
+ t.Helper()
+ h := newHarness(t, realInstall(t))
+ raw, err := exec.Command("go", "env", "GOROOT").Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.goRoot, err = filepath.EvalSymlinks(strings.TrimSpace(string(raw)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.moduleCache = t.TempDir()
+ return h
+}
+
+func TestPiGoBinaryIsolation(t *testing.T) {
+ h := goHarness(t)
+ work := t.TempDir()
+ if err := os.WriteFile(filepath.Join(work, "probe.go"), []byte(piGoProbe), 0600); err != nil {
+ t.Fatal(err)
+ }
+ r := h.open(work, "implement", []string{"submit_candidate"}, "")
+ // A synthetic key file in the CLI home tests the inner boundary as well
+ // as the real credential home's absence from the outer namespace.
+ if err := os.WriteFile(filepath.Join(r.home, ".oauth-token"), []byte(testKey), 0600); err != nil {
+ t.Fatal(err)
+ }
+ shellOK(t, h, r, "go build -o /workspace/probe /workspace/probe.go && echo built", "built")
+ tcp, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tcp.Close()
+ socket := filepath.Join(t.TempDir(), "probe.sock")
+ unix, err := net.Listen("unix", socket)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer unix.Close()
+ for _, tc := range []struct{ mode, control, isolated string }{
+ {"env", "unused", "unused"}, {"proc", "unused", "unused"}, {"processes", "unused", "unused"},
+ {"file", filepath.Join(h.keyHome, ".oauth-token"), filepath.Join(h.keyHome, ".oauth-token")},
+ {"file", filepath.Join(h.keyHome, ".oauth-token"), "/home/runner/.oauth-token"},
+ {"tcp", tcp.Addr().String(), "127.0.0.1:18080"},
+ {"unix", socket, "/egress/proxy.sock"},
+ } {
+ t.Run(tc.mode, func(t *testing.T) {
+ // Execute the exact binary built by Pi outside the shell as a positive
+ // control. It reports presence only, never any credential bytes.
+ cmd := exec.Command(filepath.Join(work, "probe"), tc.mode, tc.control)
+ cmd.Env = append(os.Environ(), "TENSORX_API_KEY="+testKey)
+ out, err := cmd.Output()
+ if err != nil || string(out) != "exposed\n" {
+ t.Fatal("positive control failed")
+ }
+ shellOK(t, h, r, "/workspace/probe "+tc.mode+" "+tc.isolated, "isolated")
+ })
+ }
+}
diff --git a/internal/runner/provider/pi/harness_test.go b/internal/runner/provider/pi/harness_test.go
index 19e228cd..faac8fd7 100644
--- a/internal/runner/provider/pi/harness_test.go
+++ b/internal/runner/provider/pi/harness_test.go
@@ -115,13 +115,14 @@ func (s *toolServer) serve(c net.Conn, tools []string) {
// containment: bubblewrap, the egress relay to api.tensorx.ai only, the
// key through the secret pipe.
type harness struct {
- t *testing.T
- manager *containment.Manager
- scratch string
- install Install
- proxy string
- keyHome string
- tensorx *fakepi.TensorX
+ t *testing.T
+ manager *containment.Manager
+ scratch string
+ install Install
+ proxy string
+ keyHome string
+ tensorx *fakepi.TensorX
+ goRoot, moduleCache string
}
func copyTestBinary(t *testing.T, dir, name string) string {
@@ -301,7 +302,7 @@ func (h *harness) openWith(work, action string, equipo []string, session, kept s
if session == "" {
session = NewSessionID()
}
- in, cleanup, err := Prepare(h.scratch, Run{Install: h.install, Bwrap: "/usr/bin/bwrap", ToolProxy: h.proxy, Scratch: scratch, Workspace: work, Action: action, Provider: "tensorx", Model: "z-ai/glm-5.3", Equipo: equipo, Resume: session, EgressHosts: egressHosts(t), ExtraCA: h.tensorx.CA})
+ in, cleanup, err := Prepare(h.scratch, Run{GoRoot: h.goRoot, ModuleCache: h.moduleCache, Install: h.install, Bwrap: "/usr/bin/bwrap", ToolProxy: h.proxy, Scratch: scratch, Workspace: work, Action: action, Provider: "tensorx", Model: "z-ai/glm-5.3", Equipo: equipo, Resume: session, EgressHosts: egressHosts(t), ExtraCA: h.tensorx.CA})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/runner/provider/pi/home.go b/internal/runner/provider/pi/home.go
index 42beed57..acc19230 100644
--- a/internal/runner/provider/pi/home.go
+++ b/internal/runner/provider/pi/home.go
@@ -46,6 +46,7 @@ func Paths(root string) (node, tree string) {
type Run struct {
Install
Bwrap, ToolProxy, Scratch string
+ GoRoot, ModuleCache string
Workspace, Action string
Provider, Model string
Equipo []string
@@ -69,7 +70,8 @@ func Prepare(scratchRoot string, r Run) (provider.PiPolicyInputs, func(), error)
if err := os.Mkdir(home, 0700); err != nil {
return provider.PiPolicyInputs{}, nil, err
}
- cleanup := func() { os.RemoveAll(home) }
+ goLease := &provider.GoLease{}
+ cleanup := func() { goLease.Close(); os.RemoveAll(home) }
for _, d := range []string{"agent", "sessions"} {
if err := os.Mkdir(filepath.Join(home, d), 0700); err != nil {
cleanup()
@@ -81,9 +83,14 @@ func Prepare(scratchRoot string, r Run) (provider.PiPolicyInputs, func(), error)
cleanup()
return provider.PiPolicyInputs{}, nil, err
}
+ shell := filepath.Join(r.Scratch, "bash")
+ if err := os.WriteFile(shell, provider.PiShellSource(), 0700); err != nil {
+ cleanup()
+ return provider.PiPolicyInputs{}, nil, err
+ }
keyEnv := provider.PiKeyEnvs[r.Provider]
in := provider.PiPolicyInputs{Node: r.Node, NodeSHA256: r.NodeSHA256, Tree: r.Tree, TreeSHA256: r.TreeSHA256, Bwrap: r.Bwrap, ToolProxy: r.ToolProxy, Extension: ext,
- Home: home, Workspace: r.Workspace, Action: r.Action, Provider: r.Provider, Model: r.Model, KeyEnv: keyEnv, Tools: Tools(r.Action, r.Equipo), Resume: r.Resume,
+ Shell: shell, GoRoot: r.GoRoot, ModuleCache: r.ModuleCache, GoLease: goLease, Home: home, Workspace: r.Workspace, Action: r.Action, Provider: r.Provider, Model: r.Model, KeyEnv: keyEnv, Tools: Tools(r.Action, r.Equipo), Resume: r.Resume,
EgressHosts: r.EgressHosts, Models: Models(r.Provider, r.Model), Settings: Settings, MCP: MCP, ExtraCA: r.ExtraCA}
if err := provider.WritePiConfig(in); err != nil {
cleanup()
diff --git a/internal/runner/provider/pi/real_test.go b/internal/runner/provider/pi/real_test.go
index eec26c76..78f43934 100644
--- a/internal/runner/provider/pi/real_test.go
+++ b/internal/runner/provider/pi/real_test.go
@@ -144,31 +144,26 @@ func TestPiP3MCPPinning(t *testing.T) {
}
}
-// P4, as connectors spec §2.1 states it for metered keys: a step CAN
-// read the key (it is in the namespace's environment, and nothing keeps
-// a shell from it), so this asserts that plainly. It is in no argv.
-func TestPiP4AStepCanReadTheKey(t *testing.T) {
+// P4: the CLI retains its key; shell commands cannot read its environment.
+func TestPiP4ShellCannotReadTheKey(t *testing.T) {
h := newHarness(t, realInstall(t))
r := h.open(t.TempDir(), "implement", []string{"submit_candidate"}, "")
- key := `K=$(printf 'tx-equipo-%s' test-key); `
- r.prompt(t, call("bash", map[string]string{"command": key + `for p in /proc/[0-9]*; do tr '\0' '\n' < $p/environ 2>/dev/null; done | grep -c "$K"`}), "deny")
- if n := strings.TrimSpace(lastTool(h)); n == "0" || n == "" {
- t.Fatalf("the key was not readable: %q (the spec says a step can read it)", lastTool(h))
- }
- r.prompt(t, call("bash", map[string]string{"command": key + `cat /proc/[0-9]*/cmdline > /tmp/argv 2>/dev/null; grep -c "$K" /tmp/argv || true`}), "deny")
- if n := strings.TrimSpace(lastTool(h)); n != "0" {
- t.Fatalf("the key is in an argv: %q", lastTool(h))
- }
+ shellOK(t, h, r, `python3 - <<'PY'
+import glob
+for p in glob.glob('/proc/[0-9]*/environ'):
+ try: raw=open(p,'rb').read()
+ except OSError: continue
+ assert b'TENSORX_API_KEY=' not in raw
+print('key-isolated')
+PY`, "key-isolated")
}
-// P5: killing the namespace ends every descendant, a shell's background
-// loop included; an abort alone does not (rev 3 §5: termination comes
-// from the namespace).
+// P5: the inner PID namespace ends background children when its shell exits.
func TestPiP5DescendantTermination(t *testing.T) {
h := newHarness(t, realInstall(t))
work := t.TempDir()
r := h.open(work, "implement", []string{"submit_candidate"}, "")
- r.prompt(t, call("bash", map[string]string{"command": `nohup sh -c 'while :; do date +%s%N > /workspace/alive; sleep 0.05; done' >/dev/null 2>&1 & echo started`}), "deny")
+ r.prompt(t, call("bash", map[string]string{"command": `nohup sh -c 'while :; do date +%s%N > /workspace/alive; sleep 0.05; done' >/dev/null 2>&1 & sleep 0.2; echo started`}), "deny")
alive := filepath.Join(work, "alive")
moving := func() bool {
a, _ := os.ReadFile(alive)
@@ -176,16 +171,11 @@ func TestPiP5DescendantTermination(t *testing.T) {
b, _ := os.ReadFile(alive)
return len(a) > 0 && string(a) != string(b)
}
- if !moving() {
- t.Fatal("the background loop never ran")
+ if _, err := os.Stat(alive); err != nil {
+ t.Fatal("background loop never ran")
}
- ctx, cancel := contextTimeout(10 * time.Second)
- defer cancel()
- if err := r.launcher.Interrupt(ctx, r.session); err != nil {
- t.Fatalf("abort: %v", err)
- }
- if !moving() {
- t.Fatal("an abort ended the loop; the namespace kill should be what does")
+ if moving() {
+ t.Fatal("a descendant outlived the shell")
}
if err := r.stop(t); err != nil {
t.Fatalf("exit not proven: %v", err)
@@ -218,10 +208,9 @@ func TestPiAcceptanceHostileRepository(t *testing.T) {
t.Fatalf("declared %v", req.Tools)
}
}
- // Only the provider's host: another host is refused at the relay, and
- // there is no other network at all.
+ // The CLI can reach its provider; Bash cannot reach even the relay.
r.prompt(t, call("bash", map[string]string{"command": `exec 3<>/dev/tcp/127.0.0.1/18080; printf 'CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n' >&3; head -c 12 <&3; echo; (exec 4<>/dev/tcp/1.1.1.1/443) 2>&1 | head -c 80`}), "deny")
- if out := lastTool(h); !strings.Contains(out, "403") || !strings.Contains(out, "unreachable") && !strings.Contains(out, "refused") && !strings.Contains(out, "No such") {
+ if out := lastTool(h); strings.Contains(out, "403") || !strings.Contains(out, "unreachable") && !strings.Contains(out, "refused") && !strings.Contains(out, "No such") {
t.Fatalf("network: %q", out)
}
if err := r.stop(t); err != nil {
diff --git a/internal/runner/provider/pi/shell_test.go b/internal/runner/provider/pi/shell_test.go
new file mode 100644
index 00000000..d1ae12db
--- /dev/null
+++ b/internal/runner/provider/pi/shell_test.go
@@ -0,0 +1,150 @@
+package pi
+
+import (
+ "fmt"
+ "golang.org/x/mod/sumdb/dirhash"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func shellOK(t *testing.T, h *harness, r *run, command, marker string) {
+ t.Helper()
+ evs := r.prompt(t, call("bash", map[string]string{"command": command}), "deny")
+ res := results(evs)
+ if len(res) != 1 || res[0].IsError || !strings.Contains(lastTool(h), marker) {
+ // Never include tool output: a regressed probe may have read a key.
+ t.Fatalf("shell probe failed: %s", marker)
+ }
+}
+
+func TestPiShellIsolation(t *testing.T) {
+ h := newHarness(t, realInstall(t))
+ r := h.open(t.TempDir(), "implement", []string{"submit_candidate"}, "")
+ if err := os.WriteFile(filepath.Join(r.home, ".oauth-token"), []byte(testKey), 0600); err != nil {
+ t.Fatal(err)
+ }
+ script := fmt.Sprintf(`python3 - <<'PY'
+import os,glob,socket
+assert 'TENSORX_API_KEY' not in os.environ, 'inherited key'
+for p in glob.glob('/proc/[0-9]*/environ')+glob.glob('/proc/[0-9]*/task/*/environ'):
+ try: raw=open(p,'rb').read()
+ except OSError: continue
+ assert b'TENSORX_API_KEY=' not in raw, 'CLI environment reachable'
+for p in [%q, '/home/runner/.oauth-token', '/home/runner/agent/models.json', '/config/pi/equipo.ts', '/egress/proxy.sock', '/tool/equipo.sock']:
+ assert not os.path.exists(p), 'protected path reachable'
+for family,addr in [(socket.AF_INET,('127.0.0.1',18080)),(socket.AF_UNIX,'/egress/proxy.sock'),(socket.AF_UNIX,'/tool/equipo.sock')]:
+ s=socket.socket(family);s.settimeout(1)
+ try: s.connect(addr)
+ except OSError: pass
+ else: raise AssertionError('relay reachable')
+ s.close()
+print('shell-isolated')
+PY`, filepath.Join(h.keyHome, ".oauth-token"))
+ shellOK(t, h, r, script, "shell-isolated")
+}
+
+func TestPiEngineeringOfflineGo(t *testing.T) {
+ h := goHarness(t)
+ work := t.TempDir()
+ for name, body := range map[string]string{
+ "go.mod": "module fixture.invalid/app\n\ngo 1.26\nrequire fixture.invalid/cached v1.0.0\n",
+ "app_test.go": "package app\nimport (\"testing\"; dep \"fixture.invalid/cached\")\nfunc TestOffline(t *testing.T) { if dep.Value != 42 {t.Fatal(dep.Value)} }\n",
+ } {
+ if err := os.WriteFile(filepath.Join(work, name), []byte(body), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for name, body := range map[string]string{
+ "fixture.invalid/cached@v1.0.0/go.mod": "module fixture.invalid/cached\n\ngo 1.26\n",
+ "fixture.invalid/cached@v1.0.0/dep.go": "package cached\nconst Value=42\n",
+ "cache/download/fixture.invalid/cached/@v/v1.0.0.mod": "module fixture.invalid/cached\n\ngo 1.26\n",
+ } {
+ p := filepath.Join(h.moduleCache, name)
+ if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(body), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ sum, err := dirhash.HashDir(filepath.Join(h.moduleCache, "fixture.invalid/cached@v1.0.0"), "fixture.invalid/cached@v1.0.0", dirhash.Hash1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(h.moduleCache, "cache/download/fixture.invalid/cached/@v/v1.0.0.ziphash"), []byte(sum), 0600); err != nil {
+ t.Fatal(err)
+ }
+ r := h.open(work, "implement", []string{"submit_candidate"}, "")
+ shellOK(t, h, r, `set -eu
+ test "$GOPROXY" = off
+ test "$GOSUMDB" = off
+ test "$GOTOOLCHAIN" = local
+ go test -mod=mod -run '^TestOffline$' .
+ python3 - <<'PY'
+import os
+for root in ['/opt/go','/opt/go-mod']:
+ assert os.statvfs(root).f_flag & os.ST_RDONLY, 'writable tree'
+ try: open(root+('/VERSION' if root=='/opt/go' else '/fixture.invalid/cached@v1.0.0/dep.go'),'r+')
+ except OSError: pass
+ else: raise AssertionError('writable tree')
+import subprocess
+os.mkdir('/workspace/missing')
+open('/workspace/missing/go.mod','w').write('module missing.invalid/app\ngo 1.26\n')
+open('/workspace/missing/app.go','w').write('package app\nimport _ "missing.invalid/uncached"\n')
+r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/workspace/missing',capture_output=True,text=True)
+assert r.returncode!=0 and 'module lookup disabled by GOPROXY=off' in r.stderr
+print('offline-go-ok')
+PY`, "offline-go-ok")
+}
+
+func TestPiRPCShellIsolation(t *testing.T) {
+ h := newHarness(t, realInstall(t))
+ r := h.open(t.TempDir(), "implement", []string{"submit_candidate"}, "")
+ state, err := r.launcher.state(r.session)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := contextTimeout(10 * time.Second)
+ defer cancel()
+ reply, err := state.client.Call(ctx, map[string]any{"type": "bash", "command": `test -z "${TENSORX_API_KEY+x}" && test ! -e /egress/proxy.sock && echo rpc-isolated`})
+ if err != nil || !strings.Contains(string(reply.Data), "rpc-isolated") {
+ t.Fatal("RPC shell bypassed isolation")
+ }
+}
+
+func TestPiNativeConfigGuard(t *testing.T) {
+ h := newHarness(t, realInstall(t))
+ work := t.TempDir()
+ if err := os.Symlink("/home/runner/agent", filepath.Join(work, "escape")); err != nil {
+ t.Fatal(err)
+ }
+ r := h.open(work, "implement", []string{"submit_candidate"}, "")
+ for _, path := range []string{"/home/runner/agent/settings.json", "escape/settings.json", "escape/new-file"} {
+ evs := r.prompt(t, call("write", map[string]string{"path": path, "content": "{}"}), "deny")
+ if res := results(evs); len(res) != 1 || !res[0].IsError {
+ t.Fatal("native write escaped workspace")
+ }
+ }
+ // Even an erroneous approval cannot overwrite the mounted settings file.
+ evs := r.prompt(t, call("write", map[string]string{"path": "/home/runner/agent/settings.json", "content": "{}"}), "allow")
+ if res := results(evs); len(res) != 1 || !res[0].IsError {
+ t.Fatal("settings file was writable")
+ }
+ shellOK(t, h, r, "test -z \"${TENSORX_API_KEY+x}\" && echo still-isolated", "still-isolated")
+}
+
+func TestPiShellIgnoresCLIPath(t *testing.T) {
+ h := newHarness(t, realInstall(t))
+ r := h.open(t.TempDir(), "implement", []string{"submit_candidate"}, "")
+ bin := filepath.Join(r.home, "agent", "bin")
+ if err := os.MkdirAll(bin, 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(bin, "mkdir"), []byte("#!/bin/sh\nexit 125\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ shellOK(t, h, r, "echo fixed-path", "fixed-path")
+}
diff --git a/internal/runner/provider/pi_extension.ts b/internal/runner/provider/pi_extension.ts
index 5470a7e0..85ee8c07 100644
--- a/internal/runner/provider/pi_extension.ts
+++ b/internal/runner/provider/pi_extension.ts
@@ -1,38 +1,66 @@
import { realpathSync } from "node:fs";
-import { isAbsolute, join, normalize } from "node:path";
+import { dirname, basename, isAbsolute, join, normalize } from "node:path";
// Equipo's gate for Pi (connectors spec 2026-11-12, §4.1). Pi has no
// permission layer of its own; this extension is the only one it loads
// besides its built-in MCP support. EQUIPO_PI_TOOLS lists the tools a
-// step may call without asking (the tools its role pins). For a
-// read-only role, EQUIPO_PI_CONFINE is the one directory its read tools
-// may look in. Anything else is asked of Equipo over RPC (an
+// step may call without asking (the tools its role pins). EQUIPO_PI_CONFINE is the one
+// directory its native file tools may use. Anything else is asked of Equipo over RPC (an
// extension_ui_request), and runs only on a yes.
export default function (pi: any) {
const allowed = new Set((process.env.EQUIPO_PI_TOOLS ?? "").split(",").filter((t) => t !== ""));
const confine = process.env.EQUIPO_PI_CONFINE ?? "";
- const readers = new Set(["read", "grep", "find", "ls"]);
+ const fileTools = new Set(["read", "grep", "find", "ls", "write", "edit"]);
const inside = (raw: unknown): boolean => {
let path = typeof raw === "string" && raw !== "" ? raw : ".";
path = normalize(isAbsolute(path) ? path : join(process.cwd(), path));
try {
path = realpathSync(path);
} catch {
- // A path that does not exist is judged as written.
+ // Resolve the nearest existing parent for new files, too.
+ const tail: string[] = [];
+ let parent = path;
+ while (parent !== "/") {
+ tail.unshift(basename(parent));
+ parent = dirname(parent);
+ try { path = join(realpathSync(parent), ...tail); break; } catch {}
+ }
}
return path === confine || path.startsWith(confine + "/");
};
+ // Pi gates every call in a message before running them together, so a
+ // shell command could swap a checked path for a link before a file tool
+ // opens it. A file tool and a shell command never run at the same time.
+ const running = new Map<string, string>();
+ const kindOf = (name: string): string => (name === "bash" ? "shell" : fileTools.has(name) ? "file" : "");
+ const clash = (kind: string): boolean =>
+ kind !== "" && [...running.values()].some((k) => k !== kind);
+ pi.on("tool_result", async (event: any) => {
+ running.delete(event.toolCallId);
+ return undefined;
+ });
+ pi.on("agent_end", async () => {
+ running.clear();
+ });
pi.on("tool_call", async (event: any, ctx: any) => {
+ const kind = kindOf(event.toolName);
+ if (clash(kind)) {
+ return { block: true, reason: "Run file tools and shell commands in separate messages." };
+ }
+ const allow = () => {
+ if (kind !== "") running.set(event.toolCallId, kind);
+ return undefined;
+ };
let ok = allowed.has(event.toolName);
- if (ok && confine !== "" && readers.has(event.toolName)) {
+ if (ok && confine !== "" && fileTools.has(event.toolName)) {
ok = inside(event.input?.path);
}
if (ok) {
- return undefined;
+ return allow();
}
const yes = await ctx.ui.confirm("equipo:tool_call", JSON.stringify({ id: event.toolCallId, tool: event.toolName, args: event.input }));
if (yes === true) {
- return undefined;
+ return clash(kind) ? { block: true, reason: "Run file tools and shell commands in separate messages." } : allow();
}
return { block: true, reason: "Equipo did not allow this call." };
});
diff --git a/internal/runner/provider/pi_go.go b/internal/runner/provider/pi_go.go
new file mode 100644
index 00000000..d5b46b44
--- /dev/null
+++ b/internal/runner/provider/pi_go.go
@@ -0,0 +1,54 @@
+package provider
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain"
+ "os"
+)
+
+// GoLease retains toolchain descriptors for a Pi attempt. It grants no account
+// authority; it uses the same tree validation and pins as an account lease.
+type GoLease struct{ lease AccountLease }
+
+func (l *GoLease) Close() {
+ l.lease.goMu.Lock()
+ defer l.lease.goMu.Unlock()
+ l.lease.goClosed = true
+ for _, pin := range l.lease.goPins {
+ pin.file.Close()
+ }
+ l.lease.goPins = nil
+}
+
+func piGoPolicy(in PiPolicyInputs, m *effectiveManifest) error {
+ if in.Action != "implement" || in.GoRoot == "" {
+ return nil
+ }
+ if in.GoLease == nil {
+ return ErrPolicy
+ }
+ mounts := []Mount{{Source: in.GoRoot, Target: "/opt/go", ReadOnly: true}}
+ if in.ModuleCache != "" {
+ if _, err := os.Lstat(in.ModuleCache); !os.IsNotExist(err) {
+ mounts = append(mounts, Mount{Source: in.ModuleCache, Target: "/opt/go-mod", ReadOnly: true})
+ }
+ }
+ for _, mount := range mounts {
+ for _, protected := range []string{in.Home, in.Workspace, in.Tree} {
+ if withinPath(mount.Source, protected) || withinPath(protected, mount.Source) {
+ return ErrPolicy
+ }
+ }
+ f, err := goTree(mount, Binding{provenance: &in.GoLease.lease})
+ if err != nil {
+ return err
+ }
+ m.Files = append(m.Files, f)
+ m.OuterMounts = append(m.OuterMounts, mount)
+ }
+ for k, v := range gotoolchain.Environment("pi") {
+ m.Env[k] = v
+ }
+ m.Env["GIT_CONFIG_GLOBAL"] = "/dev/null"
+ m.Env["GIT_CONFIG_NOSYSTEM"] = "1"
+ return nil
+}
diff --git a/internal/runner/provider/pi_guards_test.go b/internal/runner/provider/pi_guards_test.go
new file mode 100644
index 00000000..d6ffbf23
--- /dev/null
+++ b/internal/runner/provider/pi_guards_test.go
@@ -0,0 +1,70 @@
+package provider
+
+import (
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+)
+
+func TestPiShellPolicyGuards(t *testing.T) {
+ for _, name := range []string{"wrapper bytes", "shell setting", "go scope", "cache symlink", "go pin", "closed lease"} {
+ t.Run(name, func(t *testing.T) {
+ in := piFixture(t, "implement", []string{"bash", "read"})
+ in.GoLease = &GoLease{}
+ t.Cleanup(in.GoLease.Close)
+ in.GoRoot = t.TempDir()
+ in.ModuleCache = t.TempDir()
+ if err := os.WriteFile(filepath.Join(in.GoRoot, "VERSION"), []byte("fixture"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ switch name {
+ case "wrapper bytes":
+ os.WriteFile(in.Shell, []byte("#!/bin/sh\nexec /bin/bash \"$@\"\n"), 0700)
+ case "shell setting":
+ in.Settings = []byte(`{"defaultProjectTrust":"never","shellPath":"/bin/bash"}`)
+ if err := WritePiConfig(in); err != nil {
+ t.Fatal(err)
+ }
+ case "go scope":
+ in.Action = "inspect"
+ in.Tools = reviewTools
+ case "cache symlink":
+ alias := filepath.Join(t.TempDir(), "alias")
+ os.Symlink(in.ModuleCache, alias)
+ in.ModuleCache = alias
+ case "closed lease":
+ in.GoLease.Close()
+ }
+ p, err := BuildPiPolicy(in)
+ switch name {
+ case "go scope":
+ if err != nil || p.GoToolchain() {
+ t.Fatal("read-only role received Go")
+ }
+ case "go pin":
+ if err != nil {
+ t.Fatal(err)
+ }
+ mount := Mount{Source: in.GoRoot, Target: "/opt/go", ReadOnly: true}
+ if err := os.Rename(in.GoRoot, in.GoRoot+"-old"); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(in.GoRoot + "-old") })
+ os.Mkdir(in.GoRoot, 0700)
+ held, err := p.OpenGoTree(Binding{}, mount)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Close()
+ if _, err := os.Stat(filepath.Join("/proc/self/fd", strconv.Itoa(int(held.Fd())), "VERSION")); err != nil {
+ t.Fatal("source path replaced retained tree", err)
+ }
+ default:
+ if err == nil {
+ t.Fatal("unsafe policy admitted")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/runner/provider/pi_policy_test.go b/internal/runner/provider/pi_policy_test.go
index 818111a4..3caa776a 100644
--- a/internal/runner/provider/pi_policy_test.go
+++ b/internal/runner/provider/pi_policy_test.go
@@ -50,10 +50,10 @@ func piFixture(t *testing.T, action string, tools []string) PiPolicyInputs {
in := PiPolicyInputs{
Node: file("node", "node", 0755), NodeSHA256: digest([]byte("node")), Tree: tree, TreeSHA256: treeSum,
Bwrap: file("bwrap", "bwrap", 0755), ToolProxy: file("proxy", "proxy", 0755), Extension: file("equipo.ts", string(PiExtensionSource()), 0600),
- Home: home, Workspace: work, Action: action, Provider: "tensorx", Model: "z-ai/glm-5.3", KeyEnv: "TENSORX_API_KEY",
+ Shell: file("bash", string(PiShellSource()), 0700), Home: home, Workspace: work, Action: action, Provider: "tensorx", Model: "z-ai/glm-5.3", KeyEnv: "TENSORX_API_KEY",
Tools: tools, EgressHosts: []string{"api.tensorx.ai"},
Models: json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"$TENSORX_API_KEY","baseUrl":"https://api.tensorx.ai/v1","models":[{"id":"z-ai/glm-5.3"}]}}}`),
- Settings: json.RawMessage(`{"defaultProjectTrust":"never"}`),
+ Settings: PiSettings,
MCP: json.RawMessage(`{"autoEnableCodemode":false,"mcpServers":{"equipo":{"args":["--socket","/tool/equipo.sock"],"command":"/opt/equipo-tool-proxy","exposure":"direct"}}}`),
}
if err := WritePiConfig(in); err != nil {
@@ -107,7 +107,7 @@ func TestPiPolicyIsolatedConfiguration(t *testing.T) {
}
targets = append(targets, m.Target)
}
- if !slices.Equal(targets, []string{"/opt/node", "/opt/pi/node_modules", "/opt/equipo-tool-proxy", "/config/pi/equipo.ts"}) {
+ if !slices.Equal(targets, []string{"/opt/node", "/opt/pi/node_modules", "/opt/equipo-tool-proxy", "/config/pi/equipo.ts", "/opt/bwrap", PiShell}) {
t.Fatalf("mounts %v", targets)
}
in.Resume = "01a1d02a-2fc0-7066-b385-fa7d30fbd4fb"
@@ -115,10 +115,10 @@ func TestPiPolicyIsolatedConfiguration(t *testing.T) {
t.Fatalf("resume argv %q", got)
}
in.Resume = ""
- // Engineering: its tools inside the namespace, no confinement.
+ // Engineering keeps native file tools in the workspace.
eng := piFixture(t, "implement", []string{"read", "bash", "edit", "write", "grep", "find", "ls", "mcp__equipo__submit_candidate"})
ep, err := BuildPiPolicy(eng)
- if err != nil || ep.ReadOnlyWorkspace() || ep.Env["EQUIPO_PI_CONFINE"] != "" {
+ if err != nil || ep.ReadOnlyWorkspace() || ep.Env["EQUIPO_PI_CONFINE"] != "/workspace" {
t.Fatalf("engineering: %v %v", err, ep.Env)
}
}
diff --git a/internal/runner/provider/pi_shell.go b/internal/runner/provider/pi_shell.go
new file mode 100644
index 00000000..812fbb89
--- /dev/null
+++ b/internal/runner/provider/pi_shell.go
@@ -0,0 +1,13 @@
+package provider
+
+import (
+ "bytes"
+ _ "embed"
+)
+
+const PiShell = "/config/pi/bash"
+
+//go:embed pi_shell.sh
+var piShell []byte
+
+func PiShellSource() []byte { return bytes.Clone(piShell) }
diff --git a/internal/runner/provider/pi_shell.sh b/internal/runner/provider/pi_shell.sh
new file mode 100644
index 00000000..1cb0bccb
--- /dev/null
+++ b/internal/runner/provider/pi_shell.sh
@@ -0,0 +1,26 @@
+#!/bin/sh
+set -eu
+# Pi passes -c and the command as separate arguments. Never evaluate them here.
+[ "$#" -eq 2 ] && [ "$1" = '-c' ] || exit 125
+command=$2
+/usr/bin/mkdir -p /tmp/pi-shell/go-build /tmp/pi-shell/go-tmp
+set -- /opt/bwrap --die-with-parent --new-session \
+ --unshare-user --unshare-pid --unshare-net --unshare-ipc --unshare-uts \
+ --disable-userns --cap-drop ALL \
+ --ro-bind /usr /usr --ro-bind /etc /etc \
+ --symlink usr/bin /bin --symlink usr/lib /lib --symlink usr/lib64 /lib64 \
+ --proc /proc --dev /dev --dir /home/runner \
+ --bind /workspace /workspace --bind /tmp/pi-shell /tmp \
+ --chdir /workspace --clearenv \
+ --setenv HOME /home/runner --setenv TMPDIR /tmp --setenv LANG C.UTF-8 \
+ --setenv PATH /opt/go/bin:/usr/bin:/bin \
+ --setenv GIT_CONFIG_GLOBAL /dev/null --setenv GIT_CONFIG_NOSYSTEM 1
+if [ -d /opt/go ]; then
+ set -- "$@" --ro-bind /opt/go /opt/go --ro-bind-try /opt/go-mod /opt/go-mod \
+ --setenv GOROOT /opt/go --setenv GOMODCACHE /opt/go-mod \
+ --setenv GOCACHE /tmp/go-build --setenv GOTMPDIR /tmp/go-tmp \
+ --setenv GOPROXY off --setenv GOSUMDB off --setenv GOTOOLCHAIN local \
+ --setenv GOENV off --setenv GOWORK off --setenv GOFLAGS '' \
+ --setenv GOTELEMETRY off --setenv CGO_ENABLED 0
+fi
+exec /usr/bin/env -i "$@" -- /usr/bin/bash --noprofile --norc -c "$command"
diff --git a/internal/runner/provider/types.go b/internal/runner/provider/types.go
index 56d22ac0..0dac4eb7 100644
--- a/internal/runner/provider/types.go
+++ b/internal/runner/provider/types.go
@@ -53,6 +53,7 @@ type Mount struct {
}
type Policy struct {
+ goLease *GoLease
Hash string
ManifestHash, InstructionHash string
ThreadPolicy, TurnPolicy json.RawMessage
diff --git a/internal/runner/thin/opencodestep.go b/internal/runner/thin/opencodestep.go
index d8f14903..7566159c 100644
--- a/internal/runner/thin/opencodestep.go
+++ b/internal/runner/thin/opencodestep.go
@@ -91,7 +91,7 @@ func (e *Engineer) prepareMetered(tree workspace.TaskTree, spec specialistRun, s
if session == "" {
session = pi.NewSessionID()
}
- in, cleanup, err := pi.Prepare(o.Runner.ScratchRoot, pi.Run{Install: inst, Bwrap: o.Runner.Bwrap(), ToolProxy: o.Runner.ToolProxy(), Scratch: scratch, Workspace: tree.Dir, Action: spec.action, Provider: b.Provider, Model: b.Model, Equipo: spec.names, Resume: session, EgressHosts: hosts, ExtraCA: piTestCA()})
+ in, cleanup, err := pi.Prepare(o.Runner.ScratchRoot, pi.Run{GoRoot: o.Runner.GoRoot, ModuleCache: firstNonEmpty(o.Runner.ModuleCache, homeModuleCache()), Install: inst, Bwrap: o.Runner.Bwrap(), ToolProxy: o.Runner.ToolProxy(), Scratch: scratch, Workspace: tree.Dir, Action: spec.action, Provider: b.Provider, Model: b.Model, Equipo: spec.names, Resume: session, EgressHosts: hosts, ExtraCA: piTestCA()})
if err != nil {
e.log("step pi", err)
return meteredPrep{}, "policy_rejected"
diff --git a/internal/runner/thin/pi_go_test.go b/internal/runner/thin/pi_go_test.go
new file mode 100644
index 00000000..7bec704a
--- /dev/null
+++ b/internal/runner/thin/pi_go_test.go
@@ -0,0 +1,37 @@
+package thin
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+)
+
+func TestPiEngineeringToolchainConfiguration(t *testing.T) {
+ r := newPiRig(t, fakePiInstall(t), bigBudget)
+ r.e.O.Runner.GoRoot = t.TempDir()
+ r.e.O.Runner.ModuleCache = t.TempDir()
+ if err := os.WriteFile(filepath.Join(r.e.O.Runner.GoRoot, "VERSION"), []byte("fixture"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ bindings := r.conns.MeteredMine(r.ctx, connPerson)
+ if len(bindings) != 1 {
+ t.Fatal("missing metered binding")
+ }
+ for _, action := range []string{"implement", "inspect", "answer"} {
+ t.Run(action, func(t *testing.T) {
+ prep, reason := r.e.prepareMetered(workspace.TaskTree{Dir: t.TempDir()}, specialistRun{action: action, binding: bindings[0], names: []string{"ask_person"}}, t.TempDir(), []string{"api.tensorx.ai"})
+ if reason != "" {
+ t.Fatal(reason)
+ }
+ defer prep.cleanup()
+ if prep.policy.GoToolchain() != (action == "implement") {
+ t.Fatal("wrong toolchain scope")
+ }
+ if action == "implement" && prep.policy.Env["GOPROXY"] != "off" {
+ t.Fatal("Go is not offline")
+ }
+ })
+ }
+}
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index 2cbf7717..30f38453 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -14372,7 +14372,7 @@
},
{
"path": "internal/runner/provider/pi_extension.ts",
- "line_sha256": "a1247a361dad140ae013570f1d32d3ca28c5fd2bffc05193baf4a0681aeb44af",
+ "line_sha256": "327e97f9a6e24bcee4a7ee9ec15fb75ce7de765533d229c5b2386c27715dee1a",
"match": "node",
"count": 1,
"reason": "The Pi harness runs on the pinned Node with its npm tree (connectors spec S2, pinning and containment)."
@@ -14435,7 +14435,7 @@
},
{
"path": "internal/runner/provider/pi_policy_test.go",
- "line_sha256": "4f35e279c4069444556f07118ae714c1e7666a3fff5f02d4ecc100e3a4b69332",
+ "line_sha256": "bf9b035854ee04f48e39de27420155bf0c21fd77647d107977289209f558db14",
"match": "node",
"count": 2,
"reason": "Tests of the pinned Pi harness: Node, its npm tree and Pi's RPC mode (connectors spec S2)."