mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-11 23:36:51 +02:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The `opencode-local` adapter runs the OpenCode harness; its
model/provider routing assumes built-in providers (anthropic/openai/...)
and their default models
> - Deployments increasingly put an OpenAI/Anthropic-compatible LLM
gateway between the harness and the model for cost, governance, or
data-residency reasons: LiteLLM, OpenRouter, Portkey, Kong, a corporate
proxy, self-hosted models (vLLM/Ollama), or region-pinned/sovereign
endpoints. But OpenCode only resolves `--model provider/model` when the
model is registered in a provider's `models` map, and
`OPENCODE_ALLOW_ALL_MODELS` does NOT bypass its internal `getModel()`
> - Several lanes also fall back to built-in default models the gateway
may not serve: the auxiliary/title model (e.g. `claude-haiku-*`) and the
budget/recovery "cheap" lane (`openai/gpt-5.1-codex-mini`); these abort
runs with "no keys found that support model"
> - This pull request makes the adapter's provider/model wiring
declarative via env, so any such deployment can register gateway models
+ pin the auxiliary/budget lanes without code changes; nothing here is
specific to one hosting setup
> - The benefit is OpenCode works behind any compatible gateway with
config only; with no env set, behavior is unchanged
## Linked Issues or Issue Description
No existing issue; describing in-PR (feature / adapter enhancement).
- **Gap:** there is no supported way to register custom/gateway
providers + models for `opencode-local`, nor to pin the auxiliary
(title-gen) and budget (recovery) model lanes, so routing OpenCode
through a gateway fails at `getModel()` or on the default helper models.
- Related: #5737 (exe.dev sandbox installs for gemini/opencode local),
#5823 (unblock claude_local on remote sandbox providers).
> Note on ROADMAP: this is adapter-level, opt-in config (defaults
unchanged) that *enables* gateway routing for one harness; it is not the
core "Cloud / Sandbox agents" platform work itself. Happy to
redirect/discuss in #dev if preferred.
## What Changed
- `PAPERCLIP_OPENCODE_PROVIDERS`: merge custom/extended providers
(OpenCode `provider` shape) into the runtime `opencode.json`, so gateway
models are registered and `--model provider/model` resolves. `{env:VAR}`
placeholders are expanded server-side (so a key need not depend on the
sandbox run env).
- A malformed `PAPERCLIP_OPENCODE_PROVIDERS` is no longer silently
ignored: invalid JSON, a non-object value, and individual provider
entries with non-object values (which are skipped by name) each append a
visible note to the run notes so the misconfiguration is diagnosable
(addresses both review P1s).
- `PAPERCLIP_OPENCODE_SMALL_MODEL` / `PAPERCLIP_OPENCODE_CHEAP_MODEL`:
pin the auxiliary (title-generation) and budget (recovery-retry) lanes
to gateway-served models; defaults unchanged.
- Honour `OPENCODE_ALLOW_ALL_MODELS` on the **remote** execution path
too (was local-only, a parity gap).
- `PAPERCLIP_OPENCODE_PRINT_LOGS`: optional toggle adding `--print-logs`
so OpenCode logs surface on stderr for diagnosing remote/sandbox runs.
- `buildOpenCodeModelProfiles()` guards its `process.env` default with
`typeof process` so the shared client/server module stays browser-safe
(a bare `process.env` at module load threw ReferenceError in the browser
under Vite dev middleware and broke UI rendering in the e2e lane).
## Verification
- `pnpm --filter @paperclipai/adapter-opencode-local build` and
`typecheck` (tsc clean)
- `pnpm exec vitest run packages/adapters/opencode-local/src` shows 33
passing (incl. new tests for the provider merge, `{env:}` expansion, the
malformed/non-object/skipped-entry provider notes, small/cheap-model
resolution, and the remote allow-all bypass)
- Manually verified end-to-end against a real
OpenAI-/Anthropic-compatible gateway: with the providers + small/cheap
model set, both the title-gen and main task route to the configured
gateway model and the agent completes (a real completion is returned and
billed). That deployment supplies the verification evidence; the
mechanism is gateway-agnostic.
## Risks
Low. Everything is env-driven and opt-in; with no env set the generated
config output is unchanged, and the cheap model profile keeps its model
(the only difference is its updated human-readable description).
Defaults preserved: built-in providers, Codex-mini cheap lane with
`variant: low`, no `--print-logs`. No migration/UI impact.
## Model Used
Claude Opus 4.8 (`claude-opus-4-8`, 1M context), extended thinking +
tool use, via Claude Code.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md (adapter-level opt-in config enabling
gateway routing; not the core sandbox-platform work, noted above)
- [x] I have searched GitHub for duplicate or related PRs and linked
them above (#5737, #5823)
- [x] I have either (a) linked existing issues OR (b) described the
issue in-PR following the relevant issue template
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots (n/a, no UI)
- [ ] I have updated relevant documentation to reflect my changes (env
vars documented inline via comments; no central doc references the
adapter env yet)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(the P1 about silently dropped malformed providers JSON is addressed in
6eeb803, the follow-up P1 about silently skipped non-object entries in
2f4045a; the latest review has no further findings, and a re-review is
requested for the final note-copy/test-fixture polish at head)
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
141 lines
7.4 KiB
TypeScript
141 lines
7.4 KiB
TypeScript
import type { AdapterModelProfileDefinition } from "@paperclipai/adapter-utils";
|
|
|
|
export const type = "opencode_local";
|
|
export const label = "OpenCode (local)";
|
|
|
|
// Use OpenCode's official installer instead of `npm install -g opencode-ai`.
|
|
// The npm package reifies four large Linux x64 prebuilt-binary subpackages
|
|
// (linux-x64, linux-x64-musl, linux-x64-baseline, linux-x64-baseline-musl) in
|
|
// parallel even though only one matches the sandbox; on bandwidth-constrained
|
|
// sandboxes (e.g. Cloudflare) that exceeded the 240s install budget. The
|
|
// official installer fetches a single arch-specific binary into
|
|
// `$HOME/.opencode/bin` and tries to add it to PATH via `~/.bashrc`. That
|
|
// rc-file path is only sourced by interactive/login shells, so non-login
|
|
// `sh -c` probe invocations (used by the runtime PATH check) cannot find the
|
|
// binary. We fix that by symlinking the installed binary into a directory on
|
|
// the non-login `sh -c` PATH: prefer `/usr/local/bin` (universally on the
|
|
// default PATH on Linux distros) when root or passwordless sudo is available,
|
|
// otherwise fall back to `$HOME/.local/bin` (which is on the default PATH on
|
|
// the exe.dev sandbox image and most modern home-managed Linux images).
|
|
//
|
|
// Security tradeoff: this is `curl | bash` without a SHA-256 verification of
|
|
// the install script. We accept this because:
|
|
// 1. The install runs inside an isolated, ephemeral sandbox — blast radius
|
|
// is bounded to that sandbox's secrets and disk.
|
|
// 2. The prior `npm install -g opencode-ai` is also unverified code
|
|
// execution from a third-party registry; this is not strictly worse.
|
|
// 3. OpenCode does not publish per-release SHA-256 checksums in a stable
|
|
// location, and pinning a version + hash here would require manual
|
|
// version bumps on every OpenCode release.
|
|
// The `set -e` (implied by Bash's default with `-fsSL` upstream of a piped
|
|
// shell) and `curl -fsSL` give us fail-fast behavior on HTTP errors. If
|
|
// OpenCode starts publishing a stable checksum/signature, switch to fetching
|
|
// a versioned tarball + verifying the digest before exec.
|
|
export const SANDBOX_INSTALL_COMMAND =
|
|
'curl -fsSL https://opencode.ai/install | bash && ' +
|
|
'if [ -x "$HOME/.opencode/bin/opencode" ]; then ' +
|
|
'if [ "$(id -u)" -eq 0 ]; then ' +
|
|
'ln -sf "$HOME/.opencode/bin/opencode" /usr/local/bin/opencode; ' +
|
|
'elif command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then ' +
|
|
'sudo ln -sf "$HOME/.opencode/bin/opencode" /usr/local/bin/opencode; ' +
|
|
'else ' +
|
|
'mkdir -p "$HOME/.local/bin" && ' +
|
|
'ln -sf "$HOME/.opencode/bin/opencode" "$HOME/.local/bin/opencode"; ' +
|
|
'fi; ' +
|
|
'fi';
|
|
|
|
export const DEFAULT_OPENCODE_LOCAL_MODEL = "openai/gpt-5.2-codex";
|
|
|
|
export function isValidOpenCodeModelId(value: unknown): value is string {
|
|
if (typeof value !== "string") return false;
|
|
const trimmed = value.trim();
|
|
const slashIndex = trimmed.indexOf("/");
|
|
return Boolean(trimmed) && slashIndex > 0 && slashIndex !== trimmed.length - 1;
|
|
}
|
|
|
|
export const models: Array<{ id: string; label: string }> = [
|
|
{ id: DEFAULT_OPENCODE_LOCAL_MODEL, label: DEFAULT_OPENCODE_LOCAL_MODEL },
|
|
{ id: "openai/gpt-5.4", label: "openai/gpt-5.4" },
|
|
{ id: "openai/gpt-5.2", label: "openai/gpt-5.2" },
|
|
{ id: "openai/gpt-5.1-codex-max", label: "openai/gpt-5.1-codex-max" },
|
|
{ id: "openai/gpt-5.1-codex-mini", label: "openai/gpt-5.1-codex-mini" },
|
|
];
|
|
|
|
export const DEFAULT_OPENCODE_CHEAP_MODEL = "openai/gpt-5.1-codex-mini";
|
|
|
|
// The "cheap" budget profile (used for recovery retries and other low-cost lanes).
|
|
// Defaults to OpenCode's known Codex mini model, but is overridable so a deployment
|
|
// routing through a gateway that does not serve that model (e.g. an EU LLM gateway)
|
|
// can point the budget lane at a gateway-served model instead -- otherwise recovery
|
|
// retries fail with "model not found". PAPERCLIP_OPENCODE_CHEAP_MODEL takes priority;
|
|
// PAPERCLIP_OPENCODE_SMALL_MODEL (the auxiliary/title model) is reused as a sensible
|
|
// fallback so a single setting covers both budget lanes. The default keeps the
|
|
// upstream behaviour (with the Codex `variant: "low"`).
|
|
//
|
|
// This module is shared client/server code (the UI imports it for
|
|
// DEFAULT_OPENCODE_LOCAL_MODEL etc.), so it must not touch the global `process`
|
|
// unguarded: in the browser (Vite dev middleware serves it untransformed)
|
|
// a bare `process.env` throws ReferenceError at module load and takes the whole
|
|
// app down. Guard with `typeof process` and fall back to an empty env.
|
|
export function buildOpenCodeModelProfiles(
|
|
env: NodeJS.ProcessEnv = typeof process === "undefined" ? {} : process.env,
|
|
): AdapterModelProfileDefinition[] {
|
|
const override = (env.PAPERCLIP_OPENCODE_CHEAP_MODEL ?? env.PAPERCLIP_OPENCODE_SMALL_MODEL)?.trim();
|
|
return [
|
|
{
|
|
key: "cheap",
|
|
label: "Cheap",
|
|
description: "Budget lane model for recovery retries and other low-cost tasks.",
|
|
adapterConfig: override
|
|
? { model: override }
|
|
: { model: DEFAULT_OPENCODE_CHEAP_MODEL, variant: "low" },
|
|
source: "adapter_default",
|
|
},
|
|
];
|
|
}
|
|
|
|
export const modelProfiles: AdapterModelProfileDefinition[] = buildOpenCodeModelProfiles();
|
|
|
|
export const agentConfigurationDoc = `# opencode_local agent configuration
|
|
|
|
Adapter: opencode_local
|
|
|
|
Use when:
|
|
- You want Paperclip to run OpenCode locally as the agent runtime
|
|
- You want provider/model routing in OpenCode format (provider/model)
|
|
- You want OpenCode session resume across heartbeats via --session
|
|
|
|
Don't use when:
|
|
- You need webhook-style external invocation (use openclaw_gateway or http)
|
|
- You only need one-shot shell commands (use process)
|
|
- OpenCode CLI is not installed on the machine
|
|
|
|
Core fields:
|
|
- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible)
|
|
- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to the run prompt
|
|
- model (string, required): OpenCode model id in provider/model format (for example anthropic/claude-sonnet-4-5)
|
|
- variant (string, optional): provider-specific reasoning/profile variant passed as --variant (for example minimal|low|medium|high|xhigh|max)
|
|
- dangerouslySkipPermissions (boolean, optional): inject a runtime OpenCode config that allows \`external_directory\` access without interactive prompts; defaults to true for unattended Paperclip runs
|
|
- promptTemplate (string, optional): run prompt template
|
|
- command (string, optional): defaults to "opencode"
|
|
- extraArgs (string[], optional): additional CLI args
|
|
- env (object, optional): KEY=VALUE environment variables
|
|
|
|
Operational fields:
|
|
- timeoutSec (number, optional): run timeout in seconds
|
|
- graceSec (number, optional): SIGTERM grace period in seconds
|
|
|
|
Notes:
|
|
- OpenCode supports multiple providers and models. Use \
|
|
\`opencode models\` to list available options in provider/model format.
|
|
- Paperclip requires an explicit \`model\` value for \`opencode_local\` agents.
|
|
- Runs are executed with: opencode run --format json ...
|
|
- Sessions are resumed with --session when stored session cwd matches current cwd.
|
|
- The adapter sets OPENCODE_DISABLE_PROJECT_CONFIG=true to prevent OpenCode from \
|
|
writing an opencode.json config file into the project working directory. Model \
|
|
selection is passed via the --model CLI flag instead.
|
|
- When \`dangerouslySkipPermissions\` is enabled, Paperclip injects a temporary \
|
|
runtime config with \`permission.external_directory=allow\` so headless runs do \
|
|
not stall on approval prompts.
|
|
`;
|