Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(computer): refuse TeamHub text the shell would rewrite
LeoXing1e8b3e6a2c79
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.mdindex 357160e2..3e988987 100644--- a/apps/computer/local-daemon/README.md+++ b/apps/computer/local-daemon/README.md@@ -230,6 +230,30 @@ Computer user's own instruction files:The user's own Claude Skills and the Skills of plugins they installed are stilloffered to Agents (`internal/workspace/claude_skills.go`).+## Shell text check++An Agent's shell rewrites text in double quotes, an unquoted heredoc, or a bare+word before a command reads it: `$1` to `$9` become empty and backquoted text+runs as a command, so `teamhub message send --content "$180"` sends `80`.+Before a shell command runs, the Daemon refuses a `teamhub` command whose+arguments, heredoc or here-string, or a pipeline stage that feeds it, hold such+text, and the refusal tells the Agent to pass the text on stdin with a quoted+heredoc (`internal/permission/shell_text.go`). Named variables such as `"$id"`,+`$(...)`, and the positional parameters of a shell function pass.++- Claude checks it in its tool policy, on both the PreToolUse hook and+ `can_use_tool`.+- Codex 0.163.0 and later run `linger-computer-daemon shell-text-hook` as a+ PreToolUse hook for every shell command. Codex on Windows runs PowerShell,+ so it gets no hook.+- Pi loads the managed extension (`extensions/pi-mcp.mjs`) for every Run. It+ runs the same hook before a `bash` call that names `teamhub` and holds `$` or+ a backquote.+- Antigravity is not checked: its permission request can only allow or reject+ a call, with no reason the Agent would read.++A hook that cannot run lets the command through.+## AntigravityThe Antigravity CLI (`agy`) runs through its Agent Client Protocol (ACP)diff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.goindex d3eb6b4f..3cb8961e 100644--- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go+++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go@@ -41,6 +41,11 @@ import ()func main() {+ // Codex runs this before every shell command, and the managed Pi+ // extension before a bash call that may need it.+ if len(os.Args) == 2 && os.Args[1] == "shell-text-hook" {+ os.Exit(permission.ShellTextHook(os.Stdin, os.Stderr))+ }// Codex runs this for every PermissionRequest of a reviewed Run; it only// forwards the hook to the running Daemon.if len(os.Args) == 3 && os.Args[1] == "permission-hook" {@@ -395,6 +400,7 @@ func run(args []string) (resultErr error) {TempBase: operationTempBase, RuntimeHomeRoot: filepath.Join(computer.StateDirectory, "runtime-homes"),CodexModelSessionHome: codexModelSessions.Home(),PiMCPExtension: piExtension,+ ShellTextHook: executable,}, OperationResolver: resolver,Ledger: daemon.NewMemoryLedger(), Registrations: registrationStore, Assignments: assignmentStore, ContextViews: views,LocalSkills: localSkills, LocalTools: toolBinder,diff --git a/apps/computer/local-daemon/go.mod b/apps/computer/local-daemon/go.modindex aa25bdbe..b4fa9fa4 100644--- a/apps/computer/local-daemon/go.mod+++ b/apps/computer/local-daemon/go.mod@@ -11,10 +11,11 @@ require (github.com/simplexai-labs/linger/contracts-go/runnergateway v0.0.0-00010101000000-000000000000golang.org/x/net v0.56.0golang.org/x/sys v0.48.0- golang.org/x/term v0.44.0+ golang.org/x/term v0.45.0golang.org/x/text v0.39.0gopkg.in/yaml.v3 v3.0.1modernc.org/sqlite v1.60.1+ mvdan.cc/sh/v3 v3.14.1)require (diff --git a/apps/computer/local-daemon/go.sum b/apps/computer/local-daemon/go.sumindex 5c1994ae..34dec9f1 100644--- a/apps/computer/local-daemon/go.sum+++ b/apps/computer/local-daemon/go.sum@@ -2,6 +2,10 @@ github.com/Microsoft/go-winio v0.6.3 h1:M/52tsoyTfwaxajLnXZm7PqkbMGRH8iSWP+8fcg9github.com/Microsoft/go-winio v0.6.3/go.mod h1:ma0QpxizD4fyyzJ1C7MIblymTD2Nxz5Mho/3CepwIZg=github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=+github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474=+github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=@@ -12,6 +16,10 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFsgithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=@@ -20,6 +28,8 @@ github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf4github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=+github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc=+github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=@@ -28,8 +38,8 @@ golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=-golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=-golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=+golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=+golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=@@ -66,3 +76,5 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=+mvdan.cc/sh/v3 v3.14.1 h1:bXkhQWNHCs0KZEChF8hYS6FC+T2N9mUZLbQv9blditI=+mvdan.cc/sh/v3 v3.14.1/go.mod h1:syYCoFET8w9tvevxiXUtY8/ICrU+l26jHmhJDra3Vwo=diff --git a/apps/computer/local-daemon/internal/permission/shell_text.go b/apps/computer/local-daemon/internal/permission/shell_text.gonew file mode 100644index 00000000..2bd47499--- /dev/null+++ b/apps/computer/local-daemon/internal/permission/shell_text.go@@ -0,0 +1,149 @@+package permission++import (+ "encoding/json"+ "fmt"+ "io"+ "path"+ "strings"++ "mvdan.cc/sh/v3/syntax"+)++// ShellTextMessage refuses a TeamHub command whose text the shell would+// rewrite before the CLI reads it.+const ShellTextMessage = "Not run: the shell would change this teamhub command's text before teamhub reads it. " ++ "In double quotes, an unquoted heredoc, or a bare word, $1 to $9 become empty, so \"$180\" arrives as \"80\", " ++ "and text in backticks runs as a command. Pass the text on stdin through the command's --file - " ++ "(or --requirement-file -, --message-file -, --prompt-file -) with a quoted heredoc, which keeps every character:\n" ++ "teamhub message send --file - <<'EOF'\nThe quote is $180/store; run `npm test` first.\nEOF\n" ++ "Put a short value such as a title in single quotes instead."++// ShellTextRewritten reports whether a POSIX shell command runs teamhub with+// text the shell rewrites before teamhub reads it: a positional parameter,+// such as the $1 of "$180", or a backquoted command, in an argument, a+// heredoc or here-string of the command, or in a pipeline stage that feeds+// it. An Agent's shell has no positional parameters and means backquoted+// text as Markdown, so either is a mistake there. Inside a function the+// parameters are its arguments, so functions are not checked. A command the+// parser cannot read is not judged.+func ShellTextRewritten(command string) bool {+ if !strings.Contains(command, "teamhub") || !strings.ContainsAny(command, "$`") {+ return false+ }+ file, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "")+ if err != nil {+ return false+ }+ rewritten := false+ syntax.Walk(file, func(node syntax.Node) bool {+ switch node := node.(type) {+ case *syntax.FuncDecl:+ return false+ case *syntax.BinaryCmd:+ if node.Op == syntax.Pipe || node.Op == syntax.PipeAll {+ stages := pipelineStages(node, nil)+ for _, stage := range stages {+ if runsTeamHub(stage) {+ for _, each := range stages {+ rewritten = rewritten || stageRewritten(each)+ }+ break+ }+ }+ }+ case *syntax.Stmt:+ rewritten = rewritten || runsTeamHub(node) && stageRewritten(node)+ }+ return !rewritten+ })+ return rewritten+}++// pipelineStages lists the statements of a pipeline in order.+func pipelineStages(command *syntax.BinaryCmd, stages []*syntax.Stmt) []*syntax.Stmt {+ for _, side := range []*syntax.Stmt{command.X, command.Y} {+ if inner, ok := side.Cmd.(*syntax.BinaryCmd); ok && (inner.Op == syntax.Pipe || inner.Op == syntax.PipeAll) {+ stages = pipelineStages(inner, stages)+ } else {+ stages = append(stages, side)+ }+ }+ return stages+}++func runsTeamHub(stmt *syntax.Stmt) bool {+ call, ok := stmt.Cmd.(*syntax.CallExpr)+ return ok && len(call.Args) > 0 && path.Base(call.Args[0].Lit()) == "teamhub"+}++// stageRewritten reports a rewrite in a simple command's arguments or in the+// heredocs and here-strings that feed it.+func stageRewritten(stmt *syntax.Stmt) bool {+ call, ok := stmt.Cmd.(*syntax.CallExpr)+ if !ok {+ return false+ }+ nodes := make([]syntax.Node, 0, len(call.Args)+len(stmt.Redirs))+ for _, arg := range call.Args[1:] {+ nodes = append(nodes, arg)+ }+ for _, redirect := range stmt.Redirs {+ if redirect.Hdoc != nil {+ nodes = append(nodes, redirect.Hdoc)+ } else if redirect.Op == syntax.WordHdoc {+ nodes = append(nodes, redirect.Word)+ }+ }+ rewritten := false+ for _, node := range nodes {+ syntax.Walk(node, func(node syntax.Node) bool {+ switch node := node.(type) {+ case *syntax.ParamExp:+ rewritten = rewritten || node.Param != nil && positional(node.Param.Value)+ case *syntax.CmdSubst:+ rewritten = rewritten || node.Backquotes+ }+ return !rewritten+ })+ }+ return rewritten+}++func positional(name string) bool {+ return name != "" && strings.Trim(name, "0123456789") == ""+}++// ShellTextHook is the shell-text-hook command, Codex's PreToolUse hook for+// shell commands and the check behind the Pi extension. It reads the hook+// input on stdin and refuses a rewritten TeamHub command by exiting 2 with+// the reason on stderr. Any other input passes.+func ShellTextHook(stdin io.Reader, stderr io.Writer) int {+ var input struct {+ ToolInput struct {+ Command string `json:"command"`+ } `json:"tool_input"`+ }+ if json.NewDecoder(io.LimitReader(stdin, maxHookEventBytes)).Decode(&input) != nil {+ return 0+ }+ if ShellTextRewritten(input.ToolInput.Command) {+ _, _ = fmt.Fprintln(stderr, ShellTextMessage)+ return 2+ }+ return 0+}++// ShellTextHookTimeout is Codex's limit, in seconds, for one shell-text-hook+// run. Codex runs the shell command when the hook times out.+const ShellTextHookTimeout = 10++// CodexShellTextHooks is the Codex PreToolUse configuration that runs the+// Daemon's own executable as shell-text-hook for every shell command.+func CodexShellTextHooks(daemonExecutable string) []any {+ return []any{map[string]any{"matcher": "^Bash$", "hooks": []any{map[string]any{+ "type": "command",+ "command": shellQuote(daemonExecutable) + " shell-text-hook",+ "timeout": ShellTextHookTimeout,+ }}}}+}diff --git a/apps/computer/local-daemon/internal/permission/shell_text_test.go b/apps/computer/local-daemon/internal/permission/shell_text_test.gonew file mode 100644index 00000000..803529ef--- /dev/null+++ b/apps/computer/local-daemon/internal/permission/shell_text_test.go@@ -0,0 +1,73 @@+package permission++import (+ "bytes"+ "strings"+ "testing"+)++// An Agent's Room message lost its prices: "$180/store/month" arrived as+// "80/store/month" because its shell expanded the empty $1.+func TestShellTextRewrittenFindsTextTheShellChanges(t *testing.T) {+ for _, command := range []string{+ `teamhub message send --content "Quote: $180/store/month, the separately itemized $450/store"`,+ "teamhub message send --content \"Run `npm test` before merging\"",+ `teamhub message send --content "${1} items"`,+ `teamhub message send --content Price:$5`,+ "teamhub message send --file - <<EOF\nPrice $180\nEOF",+ `teamhub message send --file - <<< "Price $180"`,+ `cd /tmp && teamhub task send --task-id workitem_1 --message "Keep $180" --steer`,+ `echo ok; teamhub room handoff --inbox room:room_1 --content "Budget $450"`,+ `/usr/local/bin/teamhub message direct --content "Spent $3 today"`,+ `printf '%s\n' "Price $180" | teamhub message send --file -`,+ "cat <<EOF | sed 's/a/b/' | teamhub message send --file -\nRun `x`\nEOF",+ `teamhub message send --content "$(printf '%s' "$1")"`,+ } {+ if !ShellTextRewritten(command) {+ t.Errorf("ShellTextRewritten(%q) = false, want true", command)+ }+ }+}++func TestShellTextRewrittenLeavesLiteralAndIntendedExpansionsAlone(t *testing.T) {+ for _, command := range []string{+ "teamhub message send --file - <<'EOF'\nPrice $180, run `npm test`\nEOF",+ "teamhub message send --file - <<\\EOF\nPrice $180\nEOF",+ "teamhub message send --file - <<\"EOF\"\nPrice `date`\nEOF",+ `teamhub message send --content 'Price $180, run ` + "`npm test`" + `'`,+ "teamhub message send --content \"Price \\$180, run \\`npm test\\`\"",+ `id=$(teamhub task create --name "Rivals" --json | jq -r .id) && teamhub task send --task-id "$id" --message "Go"`,+ `teamhub message send --content "Total: $TOTAL, exit $?"`,+ `send() { teamhub message send --content "$1"; }; send hello`,+ `awk '{print $1}' sales.csv | teamhub message send --file -`,+ `git commit -m "Price $180"`,+ `echo "$1" > note.md && teamhub message send --file note.md`,+ `teamhub message send --content "unterminated $1`,+ `teamhub message send --content "Done."`,+ } {+ if ShellTextRewritten(command) {+ t.Errorf("ShellTextRewritten(%q) = true, want false", command)+ }+ }+}++func TestShellTextHookRefusesWithTheReasonOnStderr(t *testing.T) {+ var stderr bytes.Buffer+ input := `{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"teamhub message send --content \"$180\""}}`+ if code := ShellTextHook(strings.NewReader(input), &stderr); code != 2 {+ t.Fatalf("exit %d, want 2", code)+ }+ if !strings.Contains(stderr.String(), "<<'EOF'") {+ t.Fatalf("stderr = %q, want the heredoc fix", stderr.String())+ }+ for _, input := range []string{+ `{"tool_name":"Bash","tool_input":{"command":"teamhub message send --content \"Done.\""}}`,+ `{"tool_name":"apply_patch","tool_input":{"command":"*** Begin Patch"}}`,+ `not json`,+ } {+ stderr.Reset()+ if code := ShellTextHook(strings.NewReader(input), &stderr); code != 0 || stderr.Len() != 0 {+ t.Errorf("ShellTextHook(%q) = %d with %q, want 0 and no output", input, code, stderr.String())+ }+ }+}diff --git a/apps/computer/local-daemon/internal/provider/executor.go b/apps/computer/local-daemon/internal/provider/executor.goindex b716ffdc..91d45c52 100644--- a/apps/computer/local-daemon/internal/provider/executor.go+++ b/apps/computer/local-daemon/internal/provider/executor.go@@ -117,6 +117,9 @@ type Executor struct {// of a models cache for a Context's new home.CodexModelSessionHome stringPiMCPExtension string+ // ShellTextHook is the Daemon's own executable, which Runs start as+ // shell-text-hook before a shell command; empty runs no hook.+ ShellTextHook string}type Result struct {@@ -552,6 +555,7 @@ func (e Executor) Start(ctx context.Context, spec OperationSpec, emit EmitFunc)HumanInteraction: questions,PermissionReviewer: reviewer,CodexPermissionHook: codexHook,+ ShellTextHook: e.ShellTextHook,RuntimeHome: runtimeHomePath,Dir: spec.WorkingDirectory,SharedTaskLink: permission.CodexTaskLink{Path: spec.SharedTask.WritableTaskLink, Target: spec.SharedTask.WritableTaskRoot},diff --git a/apps/computer/local-daemon/internal/provider/native/claude_policy.go b/apps/computer/local-daemon/internal/provider/native/claude_policy.goindex 1d3ba4b4..dfe5c9dc 100644--- a/apps/computer/local-daemon/internal/provider/native/claude_policy.go+++ b/apps/computer/local-daemon/internal/provider/native/claude_policy.go@@ -92,6 +92,9 @@ func (p *ClaudeToolPolicy) denyReason(tool string, input map[string]any, agentIDif (tool == "Agent" || tool == "Bash") && (input["run_in_background"] == true || input["background"] == true) {return "background execution disabled"}+ if command, _ := input["command"].(string); tool == "Bash" && permission.ShellTextRewritten(command) {+ return permission.ShellTextMessage+ }if tool == "Skill" {name, _ := input["skill"].(string)for _, allowed := range p.SkillNames {diff --git a/apps/computer/local-daemon/internal/provider/native/claude_turn_test.go b/apps/computer/local-daemon/internal/provider/native/claude_turn_test.goindex 17023d49..2c5037fd 100644--- a/apps/computer/local-daemon/internal/provider/native/claude_turn_test.go+++ b/apps/computer/local-daemon/internal/provider/native/claude_turn_test.go@@ -141,6 +141,7 @@ func TestClaudeToolPolicyOnBothControlPaths(t *testing.T) {{"Agent", `{"prompt":"x"}`, "agent-1", false},{"Agent", `{"background":true}`, "", false},{"Bash", `{"command":"ls","run_in_background":true}`, "", false},+ {"Bash", `{"command":"teamhub message send --content \"Quote: $180/store\""}`, "", false},}for _, c := range cases {canUse := `{"subtype":"can_use_tool","tool_name":"` + c.tool + `","input":` + c.input + `,"agent_id":"` + c.agentID + `","tool_use_id":"tool-1"}`diff --git a/apps/computer/local-daemon/internal/provider/native/codex_binding.go b/apps/computer/local-daemon/internal/provider/native/codex_binding.goindex 7c6edfc7..e57d43ae 100644--- a/apps/computer/local-daemon/internal/provider/native/codex_binding.go+++ b/apps/computer/local-daemon/internal/provider/native/codex_binding.go@@ -5,9 +5,13 @@ import ("encoding/json""errors""fmt"+ "maps"+ "runtime""slices""strings""time"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/permission")var (@@ -219,10 +223,19 @@ func (op *codexOperation) openThread(ctx context.Context) error {if limit := toolOutputTokenLimit(spec.ContextWindow); limit != toolOutputTokens && stableCodexAtLeast(op.proc.version, codexToolOutputLimitVersion) {config["tool_output_token_limit"] = limit}+ hooks := map[string]any{}+ // Codex runs a Windows command under PowerShell, whose quoting the shell+ // text rule does not describe.+ if spec.ShellTextHook != "" && runtime.GOOS != "windows" && stableCodexAtLeast(op.proc.version, codexHooksVersion) {+ hooks["PreToolUse"] = permission.CodexShellTextHooks(spec.ShellTextHook)+ }if hook := spec.CodexPermissionHook; hook != nil {params["approvalPolicy"], params["approvalsReviewer"] = "untrusted", "user"+ maps.Copy(hooks, hook.Config)+ }+ if len(hooks) > 0 {config["bypass_hook_trust"] = true- config["hooks"] = hook.Config+ config["hooks"] = hooks}if len(config) > 0 {params["config"] = configdiff --git a/apps/computer/local-daemon/internal/provider/native/codex_home_config.go b/apps/computer/local-daemon/internal/provider/native/codex_home_config.goindex a65bd873..64fd1e9d 100644--- a/apps/computer/local-daemon/internal/provider/native/codex_home_config.go+++ b/apps/computer/local-daemon/internal/provider/native/codex_home_config.go@@ -266,6 +266,7 @@ func codexBindingFingerprint(home, configDigest string, spec RunSpec) string {optional(codexDeveloperInstructions(spec))field(spec.Title)field(fmt.Sprint(spec.CodexPermissionHook != nil))+ field(spec.ShellTextHook)field(configDigest)return hex.EncodeToString(hash.Sum(nil))}diff --git a/apps/computer/local-daemon/internal/provider/native/codex_runtime_test.go b/apps/computer/local-daemon/internal/provider/native/codex_runtime_test.goindex fba87a3a..0e6c65bd 100644--- a/apps/computer/local-daemon/internal/provider/native/codex_runtime_test.go+++ b/apps/computer/local-daemon/internal/provider/native/codex_runtime_test.go@@ -990,6 +990,34 @@ func TestCodexSteerNeedsConsumptionEvidence(t *testing.T) {}}+func TestCodexThreadRunsTheShellTextHookBeforeShellCommands(t *testing.T) {+ cases := []struct {+ name, version string+ want bool+ }{+ {"Codex with hooks", "0.165.0", true},+ {"Codex without hooks", "0.100.0", false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ fake := newCodexFake(t, []codexFakeTurn{{Status: "completed"}}, nil)+ fake.version = tc.version+ codexResidentCapForTest(t, 0)+ spec := fake.spec()+ spec.ShellTextHook = "/opt/linger/linger-computer-daemon"+ if out, _ := codexDrain(t, fake.runtime(nil), "hello", spec); out.Status != statusCompleted {+ t.Fatalf("outcome = %+v", out)+ }+ config, _ := fake.requests("thread/start")[0]["params"].(map[string]any)["config"].(map[string]any)+ hooks, _ := json.Marshal(config["hooks"])+ found := strings.Contains(string(hooks), `"PreToolUse":[{"hooks":[{"command":"'/opt/linger/linger-computer-daemon' shell-text-hook"`) && strings.Contains(string(hooks), `"matcher":"^Bash$"`)+ if found != tc.want || (config["bypass_hook_trust"] == true) != tc.want {+ t.Fatalf("config = %v", config)+ }+ })+ }+}+func TestCodexThreadToolOutputLimitFollowsContextWindow(t *testing.T) {cases := []struct {name, version stringdiff --git a/apps/computer/local-daemon/internal/provider/native/pi_fake_test.go b/apps/computer/local-daemon/internal/provider/native/pi_fake_test.goindex 5ea0061e..5942d060 100644--- a/apps/computer/local-daemon/internal/provider/native/pi_fake_test.go+++ b/apps/computer/local-daemon/internal/provider/native/pi_fake_test.go@@ -97,6 +97,7 @@ func piFake(mode string, args []string) int {if path := os.Getenv(piFakeArgvEnv); path != "" {_ = os.WriteFile(path, []byte(strings.Join(args, "\n")), 0o600)_ = os.WriteFile(path+".node_path", []byte(os.Getenv(piNodePathKey)), 0o600)+ _ = os.WriteFile(path+".shell_text_hook", []byte(os.Getenv(piShellTextHookEnvKey)), 0o600)}reader := bufio.NewReader(os.Stdin)for {diff --git a/apps/computer/local-daemon/internal/provider/native/pi_mcp.go b/apps/computer/local-daemon/internal/provider/native/pi_mcp.goindex 9dd92feb..edda34c6 100644--- a/apps/computer/local-daemon/internal/provider/native/pi_mcp.go+++ b/apps/computer/local-daemon/internal/provider/native/pi_mcp.go@@ -14,20 +14,21 @@ const (piNodePathKey = "NODE_PATH"// The NODE_PATH Pi would have had without the Computer tools.piInheritedNodePathKey = "LINGER_PI_INHERITED_NODE_PATH"+ // The Daemon executable the managed extension runs as shell-text-hook.+ piShellTextHookEnvKey = "LINGER_PI_SHELL_TEXT_HOOK")// piMCPWiring is the managed MCP set prepared for one Pi process. A zero// value wires nothing.type piMCPWiring struct {- extension stringconfigPath string}func (w piMCPWiring) wired() bool { return w.configPath != "" }-// piPrepareMCP writes the caller's MCP bytes unchanged next to the session-// and names the managed extension that loads them. Pi never falls back to-// an ambient MCP configuration.+// piPrepareMCP writes the caller's MCP bytes unchanged next to the session,+// once the managed extension that loads them is installed. Pi never falls+// back to an ambient MCP configuration.func piPrepareMCP(raw json.RawMessage, extension, sessionDir string) (piMCPWiring, error) {raw = mcpNamespace(raw)var config struct {@@ -50,7 +51,7 @@ func piPrepareMCP(raw json.RawMessage, extension, sessionDir string) (piMCPWirinif err := piWritePrivate(path, raw); err != nil {return piMCPWiring{}, fmt.Errorf("managed Pi MCP configuration could not be written: %w", err)}- return piMCPWiring{extension: extension, configPath: path}, nil+ return piMCPWiring{configPath: path}, nil}// piExtensionNodePath puts the Computer tools' node_modules on Pi's modulediff --git a/apps/computer/local-daemon/internal/provider/native/pi_runtime.go b/apps/computer/local-daemon/internal/provider/native/pi_runtime.goindex 04d6eb32..615c0034 100644--- a/apps/computer/local-daemon/internal/provider/native/pi_runtime.go+++ b/apps/computer/local-daemon/internal/provider/native/pi_runtime.go@@ -206,7 +206,12 @@ func (p *piRuntime) spawn(ctx context.Context, plan piLaunchPlan, lock *os.File)}if mcp.wired() {env[piMCPConfigEnvKey] = mcp.configPath- piExtensionNodePath(env, mcp.extension)+ }+ if mcp.wired() || p.guardsShellText(spec) {+ piExtensionNodePath(env, p.profile.ManagedMCPExtension)+ }+ if p.guardsShellText(spec) {+ env[piShellTextHookEnvKey] = spec.ShellTextHook}if p.profile.RetainProcessTemp != nil {if releaseTemp, err = p.profile.RetainProcessTemp(); err != nil {@@ -264,13 +269,21 @@ func (p *piRuntime) args(plan piLaunchPlan, instructions string, wired bool) []s}}tools := piBaseTools- if wired {+ if wired || p.guardsShellText(spec) {args = append(args, "--extension", p.profile.ManagedMCPExtension)+ }+ if wired {tools += ",mcp__*"}return append(args, "--tools", tools)}+// guardsShellText reports whether the managed extension runs the+// shell-text-hook before the Run's bash calls.+func (p *piRuntime) guardsShellText(spec RunSpec) bool {+ return spec.ShellTextHook != "" && p.profile.ManagedMCPExtension != ""+}+// piResolveProgram finds the Pi executable on the Daemon's own search path.// The lookup error is returned unchanged.func piResolveProgram(program string) (string, error) {diff --git a/apps/computer/local-daemon/internal/provider/native/pi_runtime_test.go b/apps/computer/local-daemon/internal/provider/native/pi_runtime_test.goindex 334e39f7..4e36d9d0 100644--- a/apps/computer/local-daemon/internal/provider/native/pi_runtime_test.go+++ b/apps/computer/local-daemon/internal/provider/native/pi_runtime_test.go@@ -480,6 +480,19 @@ func TestPiLaunchArguments(t *testing.T) {if nodePath, _ := os.ReadFile(argv + ".node_path"); len(nodePath) != 0 {t.Fatalf("NODE_PATH without an extension = %q", nodePath)}++ // The managed extension runs the shell-text-hook without MCP servers.+ _, outcome = piCollect(t, h.start(t.Context(), "go", RunSpec{Model: piDefaultModel, ShellTextHook: "/opt/linger/linger-computer-daemon"}))+ data, _ = os.ReadFile(argv)+ if outcome.Status != statusCompleted || !strings.HasSuffix(string(data), "--extension\n"+extension+"\n--tools\n"+piBaseTools) {+ t.Fatalf("shell text argv = %q (%+v)", data, outcome)+ }+ if hook, _ := os.ReadFile(argv + ".shell_text_hook"); string(hook) != "/opt/linger/linger-computer-daemon" {+ t.Fatalf("%s = %q", piShellTextHookEnvKey, hook)+ }+ if nodePath, _ := os.ReadFile(argv + ".node_path"); string(nodePath) != filepath.Join(filepath.Dir(filepath.Dir(extension)), "node_modules") {+ t.Fatalf("NODE_PATH = %q", nodePath)+ }}func TestPiExtensionNodePath(t *testing.T) {diff --git a/apps/computer/local-daemon/internal/provider/native/runtime.go b/apps/computer/local-daemon/internal/provider/native/runtime.goindex 06738f7a..71e5ecfc 100644--- a/apps/computer/local-daemon/internal/provider/native/runtime.go+++ b/apps/computer/local-daemon/internal/provider/native/runtime.go@@ -110,6 +110,11 @@ type RunSpec struct {RuntimeHome stringSharedTaskLink permission.CodexTaskLinkClaudePolicy *ClaudeToolPolicy+ // ShellTextHook is the Daemon executable that Codex and the managed Pi+ // extension run as shell-text-hook before a shell command, to refuse a+ // TeamHub command whose text the shell would rewrite. Claude checks the+ // same rule in its own tool policy. Empty runs no hook.+ ShellTextHook string// ContextWindow is the model's context length in tokens; zero when// unknown.ContextWindow intdiff --git a/apps/computer/local-daemon/internal/provider/native/version.go b/apps/computer/local-daemon/internal/provider/native/version.goindex cc321719..e4b8488f 100644--- a/apps/computer/local-daemon/internal/provider/native/version.go+++ b/apps/computer/local-daemon/internal/provider/native/version.go@@ -23,8 +23,11 @@ var MinimumVersions = map[string]string{}const (- codexDirectToolsVersion = "0.163.0"- codexPermissionHookVersion = "0.163.0"+ codexDirectToolsVersion = "0.163.0"+ // codexHooksVersion is the first release whose thread hooks the Daemon+ // configures: the PermissionRequest review and the PreToolUse+ // shell-text-hook.+ codexHooksVersion = "0.163.0")var (@@ -154,7 +157,7 @@ func CodexSupportsDirectTools(version string) bool {}func CodexSupportsPermissionHook(version string) bool {- return stableCodexAtLeast(version, codexPermissionHookVersion)+ return stableCodexAtLeast(version, codexHooksVersion)}var versionProbePipeBudget = 2 * time.Seconddiff --git a/apps/computer/tests/computer-tools.test.ts b/apps/computer/tests/computer-tools.test.tsindex 747a42aa..37a10952 100644--- a/apps/computer/tests/computer-tools.test.ts+++ b/apps/computer/tests/computer-tools.test.ts@@ -1,5 +1,5 @@import { execFile } from "node:child_process";-import { mkdtemp, rm } from "node:fs/promises";+import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { promisify } from "node:util";@@ -55,3 +55,55 @@ it("keeps Pi's public MCP extension bound to private Operation proxies", async (await rm(root, { recursive: true, force: true });}}, 30_000);++it.skipIf(process.platform === "win32")(+ "refuses a bash call the Daemon's shell-text-hook refuses",+ async () => {+ const root = await mkdtemp(path.join(tmpdir(), "linger-pi-shell-text-"));+ try {+ const hook = path.join(root, "daemon");+ await writeFile(+ hook,+ `#!${process.execPath}+let input = "";+process.stdin.on("data", (chunk) => (input += chunk));+process.stdin.on("end", () => {+ const { tool_input } = JSON.parse(input);+ if (process.argv[2] !== "shell-text-hook" || !tool_input.command.includes("$1")) process.exit(0);+ process.stderr.write("Not run: use a quoted heredoc\\n");+ process.exit(2);+});+`,+ { mode: 0o700 },+ );+ const result = await run(+ process.execPath,+ [+ "--input-type=module",+ "--eval",+ `+ import assert from "node:assert/strict";+ import { refuseRewrittenShellText } from ${JSON.stringify(new URL("../tools/pi-mcp.mjs", import.meta.url).href)};+ const hook = ${JSON.stringify(hook)};+ const bash = (command) => ({ toolName: "bash", input: { command } });+ assert.deepEqual(+ await refuseRewrittenShellText(bash('teamhub message send --content "Quote: $180"'), hook),+ { block: true, reason: "Not run: use a quoted heredoc" },+ );+ assert.equal(await refuseRewrittenShellText(bash('teamhub message send --content "Total $TOTAL"'), hook), undefined);+ assert.equal(await refuseRewrittenShellText(bash('teamhub message send --content "Done."'), hook), undefined);+ assert.equal(await refuseRewrittenShellText({ toolName: "read", input: { path: "$1" } }, hook), undefined);+ assert.equal(await refuseRewrittenShellText(bash('teamhub message send --content "$180"'), ${JSON.stringify(path.join(root, "missing"))}), undefined);+ assert.equal(await refuseRewrittenShellText(bash('teamhub message send --content "$180"'), undefined), undefined);+ console.log("shell text check passed");+ `,+ ],+ { timeout: 20_000 },+ );+ expect(result.stdout).toContain("shell text check passed");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ },+ 30_000,+);diff --git a/apps/computer/tools/pi-mcp.mjs b/apps/computer/tools/pi-mcp.mjsindex 701e1f8c..13c36642 100644--- a/apps/computer/tools/pi-mcp.mjs+++ b/apps/computer/tools/pi-mcp.mjs@@ -1,3 +1,4 @@+import { execFile } from "node:child_process";import { readFileSync, lstatSync } from "node:fs";import { isAbsolute } from "node:path";// The Daemon puts the Computer tools on NODE_PATH so Pi can load this@@ -9,6 +10,10 @@ if (process.env.LINGER_PI_INHERITED_NODE_PATH !== undefined) {else delete process.env.NODE_PATH;delete process.env.LINGER_PI_INHERITED_NODE_PATH;}+// The Daemon executable that judges a bash command before Pi runs it; the+// commands Pi starts do not inherit it.+const shellTextHook = process.env.LINGER_PI_SHELL_TEXT_HOOK;+delete process.env.LINGER_PI_SHELL_TEXT_HOOK;// An installed Pi may alias bare package imports to its own version. Resolve// the pinned public entry by URL so this adapter keeps its shipped API.const { createMcpExtension } = await import(@@ -64,10 +69,49 @@ export function loadManagedMcpConfig(configPath) {return { servers, autoEnableCodemode: false, errors: [] };}-export default createMcpExtension({+/**+ * Refuses a bash call whose TeamHub text the shell would rewrite, by the+ * Daemon's shell-text-hook, the check Codex runs before its shell commands.+ * Only a command that names teamhub and holds $ or a backquote can be+ * refused, so no other call starts the hook. A hook that cannot run lets the+ * call proceed.+ */+export async function refuseRewrittenShellText(event, hook = shellTextHook) {+ const command = event.toolName === "bash" ? event.input?.command : undefined;+ if (+ !hook ||+ typeof command !== "string" ||+ !command.includes("teamhub") ||+ !/[$`]/u.test(command)+ ) {+ return undefined;+ }+ const reason = await new Promise((resolve) => {+ const child = execFile(+ hook,+ ["shell-text-hook"],+ { timeout: 10_000 },+ (error, _stdout, stderr) => {+ resolve(error?.code === 2 ? stderr.trim() : "");+ },+ );+ child.stdin?.on("error", () => {});+ child.stdin?.end(JSON.stringify({ tool_input: { command } }));+ });+ return reason ? { block: true, reason } : undefined;+}++const mcpExtension = createMcpExtension({loadConfig: () =>loadManagedMcpConfig(process.env.LINGER_PI_MANAGED_MCP_CONFIG),updateConfig: () => {throw new Error("Operation MCP configuration is immutable");},});++// The Daemon loads this extension for the shell text check, and for the+// Operation's MCP servers when it has any.+export default async function managedExtension(pi) {+ pi.on("tool_call", (event) => refuseRewrittenShellText(event));+ if (process.env.LINGER_PI_MANAGED_MCP_CONFIG) await mcpExtension(pi);+}