fix(opencode-local): keep global instructions and skill paths stable across runs (#17209)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The `opencode_local` adapter runs each heartbeat with a runtime
OpenCode config. It copies the user OpenCode config directory into a new
`mkdtemp` directory for every run.
> - OpenCode writes the path of the global `AGENTS.md` ("Instructions
from: <path>") and the location of each config skill into the system
prompt.
> - Because the directory name is random, the system prompt is different
in every run, at about token 2,000.
> - Provider prompt caching matches a prompt prefix only. Each run
therefore pays for the full prompt again, and the model waits longer
before it answers.
> - This pull request loads the global `AGENTS.md` and the config skill
folders from the source config directory instead of copying them into
the per-run directory.
> - The benefit is a stable system prompt across runs, so providers can
reuse cached prompt tokens.

## Linked Issues or Issue Description

Refs #16678
Refs #15440

I found no issue or pull request for this problem. #16678 and #15440
also change how this adapter builds the runtime OpenCode config
(run-scoped MCP servers). They do not change the copy of `AGENTS.md` or
skills.

**What happened?**

Every `opencode_local` run with a global `~/.config/opencode/AGENTS.md`
sent a different system prompt. With OpenRouter and
`deepseek/deepseek-v4.1-flash-1017`, each run read only 1,792–2,048
cached tokens of about 48,000 prompt tokens. A short message ("halo")
took 9–20 seconds, depending on the model, and the full prompt was
billed every time.

**Expected behavior**

Two runs of the same agent with the same OpenCode config send the same
system prompt. Prompt caching then covers the system prompt.

**Steps to reproduce**

1. Put an `AGENTS.md` (and optionally a `skills/<name>/SKILL.md`) in
`~/.config/opencode`.
2. Create an agent with the `opencode_local` adapter and an OpenRouter
model that supports implicit prompt caching.
3. Run the agent twice with a short prompt.
4. Compare `cachedInputTokens` in the usage of the two runs. It stays at
about 2,000 tokens.
5. Run `XDG_CONFIG_HOME=<per-run dir> opencode debug skill` for two
per-run directories. The skill `location` contains the random
`paperclip-opencode-config-*` directory.

**Agent adapter(s) involved**

`opencode_local` (OpenCode 1.18.34; the same config keys exist in
1.19.3).

**Relevant logs or output**

System prompt layout that OpenCode sends, captured with an OpenCode
plugin that records `experimental.chat.system.transform`:

| Characters | Content | Same in each run? |
|---|---|---|
| 0–8,740 | OpenCode base prompt | Yes |
| about 8,970 | `Instructions from:
/tmp/paperclip-opencode-config-<random>/opencode/AGENTS.md` | No |
| about 13,000 to end | `<available_skills>`, with the `location` of
config skills under the same random directory | No |

## What Changed

- `packages/adapters/opencode-local/src/server/runtime-config.ts`: after
the adapter copies the source config directory, it removes the copied
`AGENTS.md` and the copied `skill`/`skills` folders from the per-run
directory. It adds the source `AGENTS.md` path to `instructions` and the
source skill folders to `skills.paths` in the runtime `opencode.json`.
Existing `instructions`, `skills.paths` and `skills.urls` values stay in
the config. The adapter adds a note to the run when it does this.
- `packages/adapters/opencode-local/src/server/runtime-config.test.ts`:
a test for two runs from the same source config: different per-run
directories, no copied `AGENTS.md` or `skills`, the same `instructions`
and `skills` values, and existing user entries kept. A test for a source
config without `AGENTS.md` or skills: the adapter does not add
`instructions` or `skills`.

## Verification

- `pnpm --filter @paperclipai/adapter-opencode-local exec vitest run`
passes (84 tests).
- `pnpm --filter @paperclipai/adapter-opencode-local exec tsc --noEmit`
passes.
- `opencode debug skill` and `opencode debug config` with a per-run
directory from this change: all 26 skills load, the config skill
`location` is the source path, and no `paperclip-opencode-config-*` path
is in the output.
- Direct `opencode run` test (DeepSeek through OpenRouter, "halo"): with
a new random config directory for each run, 0 of 6 runs read cached
tokens past 2,000. With a fixed config directory, the system prompt was
the same byte for byte in three runs.
- Self-hosted instance (Linux, systemd user unit, embedded Postgres),
one `opencode_local` agent with `deepseek/deepseek-v4.1-flash-1017`,
before and after this change:

| Run | Cached input tokens before | Cached input tokens after |
|---|---|---|
| First message of a new session | 1,792 | 1,536–1,792 |
| Second message in the same session | 1,792 | 7,680–29,978 |

The first message of a new session still reads about 1,800 cached
tokens. OpenRouter sends requests for this model to many providers, and
each provider keeps its own cache.

## Risks

- Low. Remote execution targets do not use this code path. Configs
without a global `AGENTS.md` or config skills do not change.
- Behavior shift: OpenCode now loads the global `AGENTS.md` through
`instructions`. It is the first entry, before other configured
instructions. The text in the prompt is the same. Only the path in
"Instructions from" changes to the source path.
- The run reads `AGENTS.md` and the config skills from the source
directory, not from a copy. The adapter does not change these files.
- `skills.paths` must be a supported OpenCode config key. OpenCode
1.18.34 and 1.19.3 support it.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code CLI, with tool
use (file edits, shell, test runs) and extended reasoning. A human
reviewed the diff.

## 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 and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-12-05 00:08:54 -08:00
1 parent d1cdd217a2
commit 797680a5ff
4 files changed
+109 -2

No files matched your search

@@ -332,7 +332,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
env.PAPERCLIP_API_KEY = authToken;
}
const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({
env, config,
env,
config,
useSourceGlobalPaths: !executionTargetIsRemote,
sandboxToolOomPreference: executionTarget?.kind === "remote" && executionTarget.transport === "sandbox",
});
const localRuntimeConfigHome =
@@ -190,6 +190,59 @@ describe("prepareOpenCodeRuntimeConfig", () => {
await prepared.cleanup();
});
it("loads global instructions and skills from the source config so the prompt is the same in every run", async () => {
const configHome = await makeConfigHome({ instructions: ["/team/RULES.md"], skills: { paths: ["/team/skills"], urls: ["https://skills.example/"] } });
const sourceDir = path.join(configHome, "opencode");
await fs.writeFile(path.join(sourceDir, "AGENTS.md"), "Global rules\n", "utf8");
await fs.mkdir(path.join(sourceDir, "skills", "notes"), { recursive: true });
await fs.writeFile(path.join(sourceDir, "skills", "notes", "SKILL.md"), "---\nname: notes\n---\n", "utf8");
const runs = await Promise.all([1, 2].map(() => prepareOpenCodeRuntimeConfig({ env: { XDG_CONFIG_HOME: configHome }, config: {}, useSourceGlobalPaths: true })));
const configs = await Promise.all(runs.map(async (prepared) => {
cleanupPaths.add(prepared.env.XDG_CONFIG_HOME);
const runtimeDir = path.join(prepared.env.XDG_CONFIG_HOME, "opencode");
await expect(fs.stat(path.join(runtimeDir, "AGENTS.md"))).rejects.toThrow();
await expect(fs.stat(path.join(runtimeDir, "skills"))).rejects.toThrow();
return JSON.parse(await fs.readFile(path.join(runtimeDir, "opencode.json"), "utf8"));
}));
expect(runs[0]!.env.XDG_CONFIG_HOME).not.toBe(runs[1]!.env.XDG_CONFIG_HOME);
expect(configs[0].instructions).toEqual([path.join(sourceDir, "AGENTS.md"), "/team/RULES.md"]);
expect(configs[0].skills).toEqual({ paths: ["/team/skills", path.join(sourceDir, "skills")], urls: ["https://skills.example/"] });
expect({ instructions: configs[1].instructions, skills: configs[1].skills })
.toEqual({ instructions: configs[0].instructions, skills: configs[0].skills });
expect(await fs.readFile(path.join(sourceDir, "AGENTS.md"), "utf8")).toBe("Global rules\n");
await Promise.all(runs.map((prepared) => prepared.cleanup()));
});
it("keeps copied global instructions and skills when source paths are not used, as for remote targets", async () => {
const configHome = await makeConfigHome({ instructions: ["/team/RULES.md"] });
const sourceDir = path.join(configHome, "opencode");
await fs.writeFile(path.join(sourceDir, "AGENTS.md"), "Global rules\n", "utf8");
await fs.mkdir(path.join(sourceDir, "skills", "notes"), { recursive: true });
await fs.writeFile(path.join(sourceDir, "skills", "notes", "SKILL.md"), "---\nname: notes\n---\n", "utf8");
const prepared = await prepareOpenCodeRuntimeConfig({ env: { XDG_CONFIG_HOME: configHome }, config: {} });
cleanupPaths.add(prepared.env.XDG_CONFIG_HOME);
const runtimeDir = path.join(prepared.env.XDG_CONFIG_HOME, "opencode");
expect(await fs.readFile(path.join(runtimeDir, "AGENTS.md"), "utf8")).toBe("Global rules\n");
await expect(fs.stat(path.join(runtimeDir, "skills", "notes", "SKILL.md"))).resolves.toBeTruthy();
const config = JSON.parse(await fs.readFile(path.join(runtimeDir, "opencode.json"), "utf8"));
expect(config.instructions).toEqual(["/team/RULES.md"]);
expect(config).not.toHaveProperty("skills");
await prepared.cleanup();
});
it("leaves instructions and skills unset when the source config has neither", async () => {
const configHome = await makeConfigHome({});
const prepared = await prepareOpenCodeRuntimeConfig({ env: { XDG_CONFIG_HOME: configHome }, config: {}, useSourceGlobalPaths: true });
cleanupPaths.add(prepared.env.XDG_CONFIG_HOME);
const config = JSON.parse(await fs.readFile(path.join(prepared.env.XDG_CONFIG_HOME, "opencode", "opencode.json"), "utf8"));
expect(config).not.toHaveProperty("instructions");
expect(config).not.toHaveProperty("skills");
await prepared.cleanup();
});
it("allows all tools and connected tools by default", async () => {
const configHome = await makeConfigHome({
permission: {
@@ -128,6 +128,12 @@ export function applyOpenCodeProviderEnvAliases(
export async function prepareOpenCodeRuntimeConfig(input: {
env: Record<string, string>;
config: Record<string, unknown>;
/**
* Point OpenCode at the global AGENTS.md and skills in the source config dir
* instead of the per-run copy. Only valid when the run can read host paths;
* remote targets get the copied dir shipped instead.
*/
useSourceGlobalPaths?: boolean;
sandboxToolOomPreference?: boolean;
}): Promise<PreparedOpenCodeRuntimeConfig> {
const skipPermissions = asBoolean(input.config.dangerouslySkipPermissions, true);
@@ -152,6 +158,9 @@ export async function prepareOpenCodeRuntimeConfig(input: {
}
}
const sourcePaths = input.useSourceGlobalPaths
? await detachSourcePathEntries(sourceConfigDir, runtimeConfigDir)
: { instructions: [], skills: [] };
const existingConfig = await readJsonObject(runtimeConfigPath);
const notes = [
skipPermissions ? "Injected runtime OpenCode config with permission=allow for all tools and connections." : "Prepared isolated OpenCode provider configuration.",
@@ -210,6 +219,16 @@ export async function prepareOpenCodeRuntimeConfig(input: {
...existingConfig,
...(skipPermissions ? { permission: "allow" } : {}),
};
if (sourcePaths.instructions.length > 0) {
nextConfig.instructions = uniqueStrings([...sourcePaths.instructions, ...stringList(existingConfig.instructions)]);
}
if (sourcePaths.skills.length > 0) {
const skills = isPlainObject(existingConfig.skills) ? existingConfig.skills : {};
nextConfig.skills = { ...skills, paths: uniqueStrings([...stringList(skills.paths), ...sourcePaths.skills]) };
}
if (sourcePaths.instructions.length > 0 || sourcePaths.skills.length > 0) {
notes.push("Loaded OpenCode global instructions and skills from their source paths, so the prompt does not change between runs.");
}
const inlineContent = input.env.OPENCODE_CONFIG_CONTENT ?? process.env.OPENCODE_CONFIG_CONTENT;
let inlineConfig: Record<string, unknown> | undefined;
if (inlineContent) {
@@ -261,6 +280,35 @@ export async function prepareOpenCodeRuntimeConfig(input: {
};
}
async function detachSourcePathEntries(sourceDir: string, runtimeDir: string): Promise<{ instructions: string[]; skills: string[] }> {
const instructions: string[] = [];
const skills: string[] = [];
if (await isEntry(path.join(sourceDir, "AGENTS.md"), "file")) {
await fs.rm(path.join(runtimeDir, "AGENTS.md"), { force: true });
instructions.push(path.join(sourceDir, "AGENTS.md"));
}
for (const name of ["skill", "skills"]) {
if (await isEntry(path.join(sourceDir, name), "directory")) {
await fs.rm(path.join(runtimeDir, name), { recursive: true, force: true });
skills.push(path.join(sourceDir, name));
}
}
return { instructions, skills };
}
async function isEntry(target: string, kind: "file" | "directory"): Promise<boolean> {
const stat = await fs.stat(target).catch(() => null);
return kind === "file" ? Boolean(stat?.isFile()) : Boolean(stat?.isDirectory());
}
function stringList(value: unknown): string[] {
return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];
}
function uniqueStrings(values: string[]): string[] {
return [...new Set(values)];
}
/** Managed credentials must never leave host-only homes in a remote process. */
export function prepareManagedOpenCodeRemoteHomes(input: {
env: Record<string, string>;
@@ -128,7 +128,11 @@ export async function testEnvironment(
// Prevent OpenCode from writing an opencode.json into the working directory.
env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({ env, config });
const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({
env,
config,
useSourceGlobalPaths: !targetIsRemote,
});
const localRuntimeConfigHome =
preparedRuntimeConfig.notes.length > 0 ? preparedRuntimeConfig.env.XDG_CONFIG_HOME : "";
if (asBoolean(config.dangerouslySkipPermissions, true)) {