Skip to content

[Story] Close the OpenCode security-hook gap before write-capable agents #515

Description

@beatrizmcouto

👤 User Story

As a
security-conscious operator of FullSend + uf

I want to
compensating controls equivalent to Claude Code PreToolUse/PostToolUse before any write-capable uf agent runs in FullSend

So that
production use is not a non-starter given OpenCode permissions are a UX feature, not a security boundary

🎯 Acceptance Criteria

  • Spike compares options: OpenCode plugin shim, wrapper-enforced tool allowlisting, host-side diffing of sandbox writes
  • Chosen control covers: environment sanitization (strip secrets in pre-script), command/tool restriction (OpenShell/landlock/process identity), prompt-injection hardening at agent definition, network isolation via provider profiles, and write-path enforcement
  • Host-side scanners remain in place (runtime-agnostic)
  • Gap is closed before Increment 3 (first write-capable agent)
  • Security matrix / docs/runtimes.md updated with the residual risk
  • Read-only Increments 1–2 remain allowed without this landing

🚫 Out of Scope

  • Changing OpenCode's upstream threat model
  • Per-skill tool scoping (OpenCode is agent-level only; adapter may be noted as follow-up)
  • Dewey/Ollama attack surface (deferred from the image)

Dependencies

  • OpenCodeRuntime exists enough to attach controls; blocks Increments 3–5

Security + open design + prod-blocking. Comparable to ComplyTime L items (new subsystem / compliance constraints), not XL because options are named and scoped to the hook gap.

🏁 Definition of Done — 🛠️ Quality & Testing

  • Code has been peer-reviewed for bugs and vulnerabilities.
  • Proper testing has been completed and passes (Unit, Integration, E2E via GitHub Actions).
  • The feature has been demonstrated/validated successfully in the target environment.

🏁 Definition of Done — 📝 Architecture & Docs

  • Usage documentation or changelog updated (if user-facing changes introduced).
  • Local ADR written and verified by Tech Lead if technical architecture deviated.
  • Any newly introduced technical debt has been logged as a GitHub issue.

Context


Implementation Notes (added by @jflowers, Aug 2026)

OpenCode security posture (from SECURITY.md): "The permission system is a UX feature, not a security boundary." Headless mode grants all permissions by default. FullSend must own compensating controls.

Control options to spike (choose at least one per category):

Category Option Mechanism
Env sanitization Strip secrets in pre_script Host-side; secrets never enter sandbox
Command/tool restriction OpenShell landlock / policy Sandbox-level process identity + syscall filtering
Command/tool restriction OpenCode tool.execute.before/after plugins Agent-level; but upstream bugs #5894 (subagent bypass) + #6396 (SDK deny bypass) were CLOSED — re-verify
Command/tool restriction Wrapper-enforced tool allowlisting Custom shim around opencode run
Prompt-injection hardening Agent definition defensive prompting Agent-level; defense-in-depth only
Network isolation Provider profiles Restrict outbound to Vertex API only
Write-path enforcement Host-side diffing of sandbox writes Post-run validation; detect unauthorized file modifications

Key context:

  • OpenCode only scopes tools at agent level, not per-skill. Per-skill scoping = follow-up / adapter pattern.
  • Host-side scanners (DeBERTa/LLM Guard, unicode, SSRF) are runtime-agnostic — they already work for both Claude and opencode.
  • Credential isolation tiers (ADR 0017/0025): tiers 1-3 keep real creds out of sandbox, so hooks are defense-in-depth. Tier 4 (GCP Vertex host files) being migrated (#1813).

Read-only Inc1-2 allowed without this story. This story MUST close before any write-capable increment (Inc3, Inc4, Inc5).

Deliverable: chosen control(s) implemented + docs/runtimes.md security matrix updated with OpenCode column showing actual controls (not "N/A — stub") + residual risk documented.


Clarification: external artifact references (added Aug 2026, per review feedback)

docs/runtimes.md referenced in this story is a fullsend-repo file (fullsend/docs/runtimes.md), not an unbound-force file. The security-matrix update deliverable of this story is a net-new upstream edit to that fullsend file — adding the OpenCode column with actual control status (replacing the current "N/A — stub" entries). This edit ships as part of the upstream PR2 alongside #510's docs update.

Activity

  1. added
    enhancement
    llm_assisted
    on Aug 17, 2026
  2. added this to the FullSend BYOA milestone on Aug 18, 2026
  3. jflowers commented on Aug 24, 2026

    @jflowers
    Contributor

    Reframe around ADR 0090 (runtime-neutral hooks) — now a precedented task, not a gap

    Commit 6cf88b15 + ADR 0090 made sandbox hooks runtime-neutral. New shape:

    • runtime.SandboxHooksBootstrap interface (sandbox_hooks_bootstrap.go): a runtime type-asserts it in Bootstrap, installs security.HookFiles via installHookScripts, and wires security.HookPlan through its own plugin mechanism.
    • docs/runtimes.md names the OpenCode path explicitly: wire hooks via OpenCode tool.execute.before/after (analog of pi's tool_call/tool_result).
    • Reference implementation: internal/runtime/pi_extension/fullsend-hooks.js.

    So this becomes: "implement OpenCode's SandboxHooksBootstrap + a fullsend-hooks OpenCode plugin, mirroring pi_extension/." Tool names must be translated to Claude vocabulary first (fullsend-ai/fullsend#608). Because it's now precedented, consider pulling parity earlier than Inc3.

    Fallback mechanisms if the plugin path stalls: ACP proxy chains (fullsend-ai/fullsend#587), transparent tool proxies (fullsend-ai/fullsend#5242/fullsend-ai/fullsend#5243).

    Non-Anthropic model caveat: if OpenCode BYOA uses non-Anthropic providers, add the ML input scan per fullsend-ai/fullsend#6538.

  4. jflowers commented on Aug 24, 2026

    @jflowers
    Contributor

    Correction: tool.execute.before/after confirmed real (plugins ≠ custom tools)

    Follow-up to the plan refresh comment and the #509 spike Aug 20 note that claimed these hooks "don't exist."

    Verified against opencode.ai/docs/plugins (Aug 24): tool.execute.before and tool.execute.after are real Tool Events in the OpenCode plugin system (.opencode/plugins/*.ts). The official docs include a .env-protection example using tool.execute.before to intercept bash commands.

    The #509 spike tested custom tools (.opencode/tools/*.ts) — a separate, simpler extension mechanism that does NOT have before/after hooks. The security-hook adapter needs plugins, not custom tools.

    What this means for #515

    The approach in the plan refresh comment is correct:

    1. Create .opencode/plugins/fullsend-hooks.ts (analogous to pi's pi_extension/fullsend-hooks.js)
    2. Wire security.HookPlan scripts via tool.execute.before (pre-tool checks: Tirith, SSRF, canary, tool allowlist) and tool.execute.after (post-tool checks: secret redaction, unicode, context suppression, canary post)
    3. Use shell.env hook to inject TIRITH_FAIL_ON / TIRITH_REQUIRED — this also addresses the Spike 3 finding that opencode doesn't auto-source .env files

    Additional plugin capabilities relevant to hooks

    • Plugins receive $ (Bun shell API) for executing commands — perfect for calling hook scripts
    • Plugin tools take precedence over built-ins with the same name
    • Plugins support package.json dependencies via .opencode/package.json (bun install at startup)
    • Plugin load order: global config → project config → global plugins dir → project plugins dir

    The fullsend-opencode image (#511) should bake this plugin + its dependencies.

  5. yvonnedevlinrh commented on Aug 26, 2026

    @yvonnedevlinrh
    Contributor

    Reframed (verified against fullsend main 90ee8d6f + OpenCode dev)

    This is no longer "close a gap" — it's "implement the precedented pi-style pattern." fullsend#6355 (ADR 0090) already made hooks runtime-neutral, and sandbox_hooks_bootstrap.go states runtimes provide their own plugin/extension implementing security.HookPlan.

    Approach: an OpenCode plugin (not a custom tool) implementing security.HookPlan, mirroring pi's vendored extension.

    Requirements verified upstream:

    • Hook contract is formally v2 (PostToolUse consumes tool_response, rewrite via hookSpecificOutput.updatedToolOutput).
    • Adapter must be runner-owned + SHA-256 integrity-checked, fail-closed, before .env is sourced. pi does this via piHooksGuard() → sha256sum on the adapter, exit 97 if missing/modified (pi_run.go). Depends on [Story] Contribute OpenCodeRuntime to FullSend #510 moving ConfigDir() off the agent-writable path.
    • Bake @opencode-ai/plugin + zod into the [Story] Publish a digest-pinned fullsend-opencode sandbox image #511 image (npm/Bun through the gateway ECONNRESETs).
    • Pin OpenCode V1 (verified: V1 runtime is where the hooks live).

    Open design item (the real gap, needs gsun co-design): OpenCode's tool.execute.before has no structured block channel — a hook can only mutate args or throw, and a throw surfaces to the model as a generic tool error with no denial reason. There is a structured allow/deny channel, but on the permission.ask event, not on tool.execute.before. gsun's HookPlan contract needs to decide which carries a FullSend block and how throw→denial maps.

    Also in scope: nested Task sub-agent hook coverage — see the note added to #518. (fullsend#6538 ML input-scan is latent/host-side only, not a run-path blocker.)

    Replaces the stale "re-verify bugs #5894/#6396" row.

  6. yvonnedevlinrh commented on Aug 27, 2026

    @yvonnedevlinrh
    Contributor

    Nested sub-agent coverage: verified stronger than ADR 0090 assumes

    Finding. ADR 0090's runtime-neutral hook contract is modeled on pi's shape, where tool calls are top-level. OpenCode differs: the
    Task tool spawns a child session that runs the same prompt loop (session/prompt.ts), so nested sub-agent tool calls also fire
    tool.execute.before / tool.execute.after
    . Verified on dev — nested calls are intercepted by the same plugin, not bypassed.

    This is better than the ADR's top-level-only assumption: our hook plugin (.opencode/plugins/fullsend-hooks.ts) covers the
    Divisor council / uf-forge multi-agent case without extra wiring.

    Contract note to pin (blocks nothing, but fixes the convention before #510 codes the ConfigDir move):

    • Adapter wires security.HookPlan via tool.execute.before (Tirith / SSRF / canary / allowlist) and tool.execute.after
      (secret redaction / unicode / canary).
    • Block signaling per docs/contributing/runtime-implementation.md:97(exit 1 + {"decision":"block","reason":"..."}).
    • Tool-output rewrite per Contract v2 (:90,hookSpecificOutput.updatedToolOutput).
    • Integrity/fail-closed mirrors pi (pi_run.go:308 piHooksGuard → sha256sum → exit 97, before .env is sourced).
    • Plugin is runner-owned + SHA-256 integrity-checked.

    **Open question (scope, not design) — surface in the OpenCodeRuntime

    Does fullsend consider ADR 0090's contract to cover nested OpenCode sub-agent (Task) tool calls, or was top-level-only the
    intended scope? We treat nested coverage as in-contract (and have it working); confirming avoids it later being read as a divergence.

  7. yvonnedevlinrh commented on Aug 27, 2026

    @yvonnedevlinrh
    Contributor

    Update: block-channel is documented at the script layer — co-design largely resolved

    Correcting the "Open design item (needs gsun co-design)" in the Reframed comment above. The "tool.execute.before has no structured block channel" concern is about the OpenCode plugin JS API (throw vs. mutate args). But the runtime-neutral contract doesn't block at that layer — it blocks at the hook-script layer, which the plugin invokes via $ (Bun shell):

    • Block signaling — docs/contributing/runtime-implementation.md:97: a blocking script exits 1 and prints {"decision":"block","reason":"..."} on stdout; the adapter stops the call (PreToolUse) or drops the post-tool result and surfaces the
      reason (PostToolUse). Same mechanism pi uses. hook_io.py emit_block() at line 260; PreToolUse scripts (tirith_check.py, ssrf_pretool.py) use exit 0 = allow / exit 1 = block.
    • Tool-output rewrite — Contract v2 (:90): PostToolUse reads tool_response (fallback tool_result), replaces via
      hookSpecificOutput.updatedToolOutput.
    • Integrity/fail-closed — already captured in the Reframed comment (mirror piHooksGuard() → sha256sum → exit 97 before .env, pi_run.go:308).

    Net: our plugin's job is to marshal {tool_name,tool_input,tool_result, tool_response} (Claude vocabulary, fullsend#608) to the scripts and read back their exit code + stdout — exactly like pi_extension/fullsend-hooks.js. No open block-channel design question remains; ADR 0090 line 65 already names "OpenCode: tool.execute.before/after plugin" as the prescribed mechanism.

    Nested sub-agent coverage (the #518 pointer was dangling — capturing here)

    The Reframed comment pointed to "a note added to #518," but no such note exists there. Recording it here instead:

    Verified on dev — OpenCode's Task tool spawns a child session running the same prompt loop (session/prompt.ts), so nested sub-agent tool calls also fire tool.execute.before/after, stronger than ADR 0090's top-level-shaped model assumes. The only residual is a scope confirmation, not a design ask: does fullsend treat ADR 0090 as covering nested Task calls, or was top-level-only the intended scope? Surface this in the OpenCodeRuntime PR description (real code in front of reviewers) Load-bearing only at #517/#518.

  8. yvonnedevlinrh commented on Aug 31, 2026

    @yvonnedevlinrh
    Contributor

    Pinned conventions for #510: ConfigDir path + plugin integrity gate

    This pins the two conventions #510 (OpenCodeRuntime) needs so it can code the ConfigDir() move against a fixed contract without later rework by #515. This is convention only — the full hook-plugin adapter, block-channel wiring, and ValidRuntimes()/guard-test changes are out of scope here (see Guardrails).

    Verified this session against the fullsend clone (HEAD 73ce2b2) and the OpenCode source (sst/opencode HEAD 8615731d46).

    1. Runner-owned ConfigDir path

    Pin: OpenCodeRuntime.ConfigDir() returns /sandbox/opencode-config (new sandbox.SandboxOpenCodeConfig const), pointed at OpenCode via the OPENCODE_CONFIG_DIR env var in EnvExports().

    • Mirrors the existing precedent exactly:
      Runtime const value
      Claude SandboxClaudeConfig /sandbox/claude-config
      pi SandboxPiConfig /sandbox/pi-config
      OpenCode (pin) SandboxOpenCodeConfig /sandbox/opencode-config
    • Replaces today's agent-writable sandbox.SandboxWorkspace + "/.opencode" (= /sandbox/workspace/.opencode) at internal/runtime/opencode.go:33. That path is inside the cloned repo tree, so the target repo can pre-seed it and a workspace reset clears it — the exact failure the existing opencode.go:29-32 doc comment already flags ("place config outside the agent-writable workspace, like Claude's /sandbox/claude-config").

    Why OPENCODE_CONFIG_DIR and not a .opencode dir name — verified in the OpenCode source that the dir name is not load-bearing:

    • config/config.ts:425 — a dir is treated as a config dir when dir.endsWith(".opencode") || dir === Flag.OPENCODE_CONFIG_DIR. The env var branch means the runner-owned dir needs no .opencode suffix.
    • config/paths.ts:39 — OPENCODE_CONFIG_DIR is appended to the config discovery set.
    • config/flag/flag.ts:63 — OPENCODE_CONFIG_DIR reads process.env at access time.
    • Inside the dir OpenCode reads opencode.json / opencode.jsonc (config.ts:426) and auto-discovers plugins by glob
      {plugin,plugins}/*.{ts,js} (config/plugin.ts:21).

    This is a cleaner boundary than pi's: pi's config dir is not a permission boundary and it must pass --no-extensions to stop auto-loading. OpenCode gives us an explicit env pointer to a runner-owned dir, so the agent-writable workspace is never on the config search path.

    2. Plugin file location + sha256 integrity gate

    Pin: the hook plugin is runner-owned at /sandbox/opencode-config/plugins/fullsend-hooks.ts — i.e. ConfigDir() + "/plugins/" + <hooks file> — SHA-256 integrity-checked, fail-closed, before .env is sourced, mirroring pi's piHooksGuard
    (internal/runtime/pi_run.go:308).

    • The plugins/ subdir matches OpenCode's auto-discovery glob ({plugin,plugins}/*.{ts,js}, config/plugin.ts:21), so no explicit
      registration in opencode.json is required for load — but load alone is not a control (the dir is not a permission boundary; the agent runs as the same user and can rewrite the plugin between iterations, same residue Claude/pi have). Hence the guard.
    • Guard contract (copy pi exactly): before OpenCode starts and before the agent-writable .env is sourced, emit a POSIX-sh fragment that:
      1. test -f the plugin file and the manifest file,
      2. compares command -p sha256sum <plugin> | command -p cut -d' ' -f1 against the hex of sha256.Sum256(<embedded plugin bytes>),
      3. on any mismatch/missing, prints to stderr and exits the dedicated missing-hook code, terminating the sh -c before OpenCode runs.
    • command -p is mandatory — it bypasses shell functions and uses the system default PATH so nothing the agent left in the environment can stand in for sha256sum/cut (pi_run.go:310-312). test/[/echo are builtins.
    • Exit code: define an openCodeHooksMissingExit const mirroring piHooksMissingExit = 97 (pi_run.go:161). (Keep the name runtime-specific; reuse the value 97 for cross-runtime consistency unless [Story] Contribute OpenCodeRuntime to FullSend #510 has a reason
      to differ — flag it if so.)
    • Ordering rationale: the guard runs before . .env because .env is agent-writable and could otherwise shadow the guard's tools
      (pi_run.go:186-188).

    Reference fragment to mirror (pi_run.go:308-315):

    { test -f <plugin> && test -f <manifest> \
      && [ "$(command -p sha256sum <plugin> | command -p cut -d' ' -f1)" = <hash> ] \
      || { echo 'fullsend: opencode hook plugin or manifest missing or modified; refusing to run unhooked' >&2; exit 97; }; }

    Interception mechanism (already contracted; recorded here for #510 context)

    Per ADR 0090 (line 65) and the v2 sandbox hook contract (docs/contributing/runtime-implementation.md:90), OpenCode wires HookPlan through the tool.execute.before / tool.execute.after plugin hooks. Block signaling at the script layer is already resolved and unchanged: blocking scripts exit 1 + print {"decision":"block","reason":"..."} on stdout (runtime-implementation.md:97); the plugin translates that into OpenCode's tool.execute.before/after denial. #510 does not implement the adapter — it only needs to know the plugin will live at the pinned path and be integrity-
    gated as above.

    Guardrails / out of scope for #510

    Net for #510

    ConfigDir() → /sandbox/opencode-config; add sandbox.SandboxOpenCodeConfig; export OPENCODE_CONFIG_DIR=<ConfigDir()> in
    EnvExports(); reserve ConfigDir()+"/plugins/fullsend-hooks.ts" as the runner-owned, sha256-gated plugin path and an openCodeHooksMissingExit (=97) const. Everything else stays #515.

  9. yvonnedevlinrh commented on Sep 29, 2026

    @yvonnedevlinrh
    Contributor

    Deferred enforcement from fullsend PR #7103

    PR fullsend-ai/fullsend#7103 (OpenCode runtime) shipped with read-only agent support. The following enforcement items are deferred to this issue and are now tracked on the fullsend side at fullsend-ai/fullsend#7824

    1. Bash command-pattern restrictions

    When an agent declares Bash(gh,jq), the OpenCode runtime currently collapses this to unrestricted bash: "allow" with a warning. The hook adapter must preserve per-argument Bash restrictions — either by translating them into OpenCode's argument-aware permission form or by enforcing the restriction in the tool.execute.before hook.

    Current behavior: opencode_bootstrap.go emits a warning: "Agent Bash allowlist (gh, jq) is recorded but not enforced on opencode"

    Required behavior: The hook adapter enforces the command allowlist, matching pi's first-token allowlist or codex's FULLSEND_TOOL_ALLOWLIST behavior.

    2. Write-capable agent role gate

    The exit-97 guard is keyed on security.enabled, not agent role. With security disabled (the documented workaround for read-only agents), write-capable agents (code, fix) run without hook protection. Once this issue delivers the adapter, either:

    • Re-enable security for all OpenCode agents (the adapter makes exit-97 pass), or
    • Add a role-aware gate that rejects write-capable roles when the adapter is absent

    References

    • internal/config/config.go NOTE
    • docs/runtimes/opencode.md callout
    • docs/contributing/runtime-implementation.md tool-allowlist row
  10. yvonnedevlinrh commented on Oct 19, 2026

    @yvonnedevlinrh
    Contributor

    Triage update: Fullsend implementation scope and remaining checks

    Reviewed this issue’s discussion alongside fullsend-ai/fullsend#7824 and the current Fullsend implementation. #515 remains actionable: the runtime has the reserved plugin path and fail-closed guard scaffolding, but the hook adapter itself is still missing.

    #515 tracks the broader security requirement; fullsend-ai/fullsend#7824 tracks the Fullsend implementation. Keeping the scope clarification here so it remains available alongside the original requirements.

    Established approach

    The later comments narrow the original spike to the existing runtime-neutral hook pattern:

    • Implement an OpenCode plugin, rather than a custom tool, wiring security.HookPlan through tool.execute.before/after.
    • Follow the shared v2 hook contract, including tool-name translation, script-layer block decisions, and hookSpecificOutput.updatedToolOutput.
    • Install at /sandbox/opencode-config/plugins/fullsend-hooks.ts, with runner-held SHA-256 verification and fail-closed exit 97 before sourcing .env.

    The earlier block-channel design question was resolved in the subsequent discussion. The remaining work is implementing and testing that contract against the supported OpenCode version.

    Bash allowlist enforcement is included

    When an agent declares restrictions such as Bash(gh,jq), the current implementation collapses them to unrestricted bash: "allow" with a warning. Preserving and enforcing those restrictions belongs in this work alongside the hook adapter.

    An argument-aware permission map is one possible implementation; enforcement in tool.execute.before is another. The acceptance criterion should be demonstrated enforcement, rather than a particular map format. Tests should cover allowed commands, disallowed commands, and shell-composition bypass attempts.

    Write-capable role gate needs explicit coverage

    The current exit-97 guard is conditional on security.enabled, not agent role. Disabling security therefore does not itself prevent write-capable agents from running without hooks.

    Before enabling write-capable agents, verify that they cannot run without the required adapter and security controls, including when security is disabled. Read-only support should remain available under the documented constraints.

    Verification before closing

    • Pre-tool denial prevents execution; post-tool blocking withholds unsafe output and surfaces the reason.
    • Secret redaction, canary detection, environment handling, and write-path restrictions work through the adapter.
    • Nested Task/sub-agent tool calls receive the same enforcement. The discussion reports this working on dev; retain regression coverage for the supported version.
    • Missing or modified adapter files fail closed, and incompatible harness plugin kinds continue to warn and skip.
    • Required plugin dependencies are available in the image without relying on startup downloads.
    • Runtime documentation and security matrices describe actual controls and residual risks, with host-side scanners and external sandbox controls retained.

    This remains a prerequisite for write-capable increments. Completing the plugin wiring alone is insufficient without the enforcement and role-gate checks above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

enhancementllm_assisted

Projects

Relationships

None yet

Development

No branches or pull requests

Issue actions