akm-cli
Version:
akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur
214 lines (213 loc) • 11.3 kB
JavaScript
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
/**
* OpenCode command builder: the `opencode run` CLI of the opencode harness
* (#1244), for both majors, treated like the Claude and Codex CLIs. The user's
* OpenCode owns its config, logins and sessions; akm hands it a prompt and reads
* the reply from stdout.
*
* The prompt goes on stdin: `opencode run` alters an argv message (quotes change,
* inner quotes are escaped) and a prompt that starts with `-` could be taken for
* a flag; stdin is read verbatim. akm closes it after the write, which the CLI
* needs: with stdin open it waits for more input.
*
* Agent work is `opencode run`, the authored args as written, `--model` when akm names one,
* `--agent` when the asset names one, and the prompt on stdin. The run is the user's own, on
* their OpenCode as they have it set up. On OpenCode 1 it also adds `--format json` (an authored
* `--format` is replaced), which changes how OpenCode reports and nothing about what it runs:
* OpenCode 1 exits 0 when its turn ends on a refused tool call, and only its event stream says so
* ({@link readOpencode1Run}). The reply is the text OpenCode prints in its default format.
*
* Model work is akm's own process. It sets `OPENCODE_DISABLE_FREE_MODELS` (OpenCode 2.1.2 and
* later, where the variable first appears): with no usable provider, OpenCode 2 would
* otherwise send akm's data to its hosted free model. The variable deletes every zero-cost
* model of the `opencode` and `opencode-go` providers, so it has no place on agent work,
* where it would override a model the user chose. On OpenCode 2 model work also gets
* `--standalone`, which keeps the run to one process that ends with it (the default attaches
* to a background service that outlives the CLI, is shared across users on one port, ignores
* inline config and replays killed sessions at every start). On both majors it gets `--title`,
* which names the session and spares the second model request that would otherwise generate a
* title, and `--agent`, which selects {@link MODEL_WORK_AGENT} and its one-line system prompt.
*
* A binary whose version cannot be read runs as OpenCode 1, with one warning that says so.
*
* Model work drops the config's `args`, keeping the model they name, as the
* Claude and Codex shells do. It runs as {@link MODEL_WORK_AGENT}, an agent defined
* inline for the run, added to the user's own inline config. On both majors its tools
* are limited to reading and searching.
*/
import { warnOpencode1Use } from "../../../cli/deprecations.js";
import { asRecord, parseJsonc } from "../../../core/common.js";
import { warnOnce } from "../../../core/warn.js";
import { modelFromArgs, withoutFlag, withoutLeading, withoutModelFlag, } from "../harness.js";
import { readOpencode1Run } from "./run-events.js";
import { detectOpencodeMajor, isOpencode2 } from "./version.js";
/** The agent OpenCode runs akm's model work as, limited to reading and searching; the name also marks those sessions in the user's history (`./session-log-v2.ts`). */
export const MODEL_WORK_AGENT = "akm-model-work";
/**
* The agent's whole system prompt. akm's own instructions travel in the message; this replaces OpenCode's coding-agent
* prompt (about 9,000 characters on OpenCode 1.18), which made the judge stricter than a plain connection (akm-eval#189).
* OpenCode 2 reads it as `system`, OpenCode 1 as `prompt`.
*/
const MODEL_WORK_PROMPT = "Do the task in the message. Reply with exactly what it asks for.";
/**
* The tools model work may use: `read`, `glob` and `grep` and, when the akm plugin is installed, `akm_search`,
* `akm_show` and `akm_curate`. Both majors' permission rules are default-deny with these allowed after it (the last
* matching rule wins; measured on OpenCode 2.1.2 and 1.18.25): `*` denied removes every tool, one a plugin or an MCP
* server registers that akm has never heard of included, and a call to a denied tool is refused, not run. This limits
* the tools; a plugin's own `setup` and hooks still run.
*/
const MODEL_WORK_TOOLS = ["read", "glob", "grep", "akm_search", "akm_show", "akm_curate"];
/** The agent's definition, in OpenCode 2's native shape, passed inline so it merges over the user's config and is never written anywhere. */
const MODEL_WORK_AGENT_DEFINITION = {
mode: "primary",
system: MODEL_WORK_PROMPT,
permissions: [
{ action: "*", resource: "*", effect: "deny" },
...MODEL_WORK_TOOLS.map((action) => ({ action, resource: "*", effect: "allow" })),
],
};
/** The same rules in OpenCode 1's shape: a `permission` map, whose key order is the rule order. */
const MODEL_WORK_AGENT_PERMISSION = {
"*": "deny",
...Object.fromEntries(MODEL_WORK_TOOLS.map((tool) => [tool, "allow"])),
};
const CONFIG_CONTENT_ENV = "OPENCODE_CONFIG_CONTENT";
/**
* OpenCode's built-in browser plugin, removed from model work (a `-` entry in `plugins` removes a plugin, OpenCode 2.0.0
* and later). From 2.2.0 it appends a deny of its own skill after every agent's rules, and a rule on one skill keeps
* the `skill` tool listed for an agent that denies every tool; without the plugin, the `*` deny removes the tool again.
* Model work denies the browser anyway.
*/
const WITHOUT_BROWSER_PLUGIN = "-opencode.browser";
/**
* The inline config model work runs with: the user's own `OPENCODE_CONFIG_CONTENT` as it is, with akm's agent set on
* `agents.akm-model-work`, the one key akm's definition wins, and {@link WITHOUT_BROWSER_PLUGIN} after the user's
* `plugins`. OpenCode 2 reads that native `agents` map over the
* legacy `agent` one, so a same-named entry the user keeps in `agent` is left out rather than left to conflict. The
* child's value is built from the parent's, so a provider, model or key the user keeps only there stays. It is read as
* OpenCode reads it, as JSONC (comments and trailing commas), and written back as JSON; content that reads only once
* its `{env:NAME}` references are replaced (one written outside a string) is read the way OpenCode replaces them
* ({@link withEnvReferences}). Content that is not valid JSONC holding an object either way is left out, with one
* warning.
*/
function modelWorkConfig(oc2) {
const content = process.env[CONFIG_CONTENT_ENV]?.trim();
const user = content ? userConfig(content) : undefined;
if (content && !user) {
warnOnce("opencode-config-content", `${CONFIG_CONTENT_ENV} is not valid JSONC holding an object, so OpenCode model work runs without it.`);
}
if (!oc2) {
// OpenCode 1 reads the singular `agent` map and a `prompt`; it ignores `agents`. The `*` deny sends neither the
// denied tools nor, with `skill` among them, the listing of every skill it finds.
const agent = {
...asRecord(user?.agent),
[MODEL_WORK_AGENT]: { mode: "primary", prompt: MODEL_WORK_PROMPT, permission: MODEL_WORK_AGENT_PERMISSION },
};
return JSON.stringify({ ...user, agent });
}
const config = {
...user,
plugins: [...(Array.isArray(user?.plugins) ? user.plugins : []), WITHOUT_BROWSER_PLUGIN],
agents: { ...asRecord(user?.agents), [MODEL_WORK_AGENT]: MODEL_WORK_AGENT_DEFINITION },
};
const legacy = asRecord(user?.agent);
if (legacy && Object.hasOwn(legacy, MODEL_WORK_AGENT)) {
const { [MODEL_WORK_AGENT]: _replaced, ...others } = legacy;
config.agent = others;
}
return JSON.stringify(config);
}
function userConfig(content) {
return jsoncObject(content) ?? jsoncObject(withEnvReferences(content));
}
function jsoncObject(content) {
try {
return asRecord(parseJsonc(content));
}
catch {
return undefined;
}
}
/**
* `{env:NAME}` replaced as OpenCode replaces it in this variable before it parses it (`ConfigVariable.substitute`):
* by the variable's value, or nothing when it is unset or empty, as written where the result reads as JSONC, else
* escaped as the inside of a JSON string. A `{file:path}` is left for the OpenCode akm runs, which replaces it against
* its own directory, as it would in-process.
*/
function withEnvReferences(content) {
const replaced = (escaped) => content.replace(/\{env:([^}]+)\}/g, (_, name) => {
const value = process.env[name] || "";
return escaped ? JSON.stringify(value).slice(1, -1) : value;
});
const raw = replaced(false);
try {
parseJsonc(raw);
return raw;
}
catch {
return replaced(true);
}
}
const NO_FREE_MODELS = { OPENCODE_DISABLE_FREE_MODELS: "1" };
const JSON_FORMAT = ["--format", "json"];
/**
* What an OpenCode 1 run adds: its event stream is read for the outcome. The run is OpenCode 1 either because the binary
* says so, which is deprecated, or because it said nothing readable, which gets its own warning.
*/
function opencode1Run(bin) {
const { reportedMajor, version } = detectOpencodeMajor(bin);
if (reportedMajor === undefined) {
warnOnce(`opencode-version-unreadable:${bin}`, `Could not read the version of ${bin}, so akm runs it as OpenCode 1: agent and model work read its event stream (--format json), and model work gets no --standalone. An OpenCode 2 would be read wrongly. Check \`${bin} --version\`.`);
}
else {
warnOpencode1Use(bin, version);
}
return { report: readOpencode1Run };
}
export const opencodeBuilder = {
build({ bin, args }, req) {
const agent = req.agent ? ["--agent", req.agent] : [];
const model = req.model ? ["--model", req.model] : [];
const authored = withoutLeading(args, "run");
if (req.prompt === undefined) {
// An interactive launch is the TUI, which `run` (headless) is not.
return { argv: [bin, ...(req.model ? withoutModelFlag(authored) : authored), ...agent, ...model] };
}
const oc2 = isOpencode2(bin);
// OpenCode 2 writes its failure reason on stderr; OpenCode 1's comes from its event stream.
const oc1 = oc2 ? { failureStream: "stderr" } : opencode1Run(bin);
if (!req.modelWork) {
const extra = oc2 ? authored : withoutFlag(authored, "--format");
return {
argv: [
bin,
"run",
...(req.model ? withoutModelFlag(extra) : extra),
...agent,
...model,
...(oc2 ? [] : JSON_FORMAT),
],
stdin: req.prompt,
...oc1,
};
}
const named = req.model ?? modelFromArgs(args);
return {
argv: [
bin,
"run",
...(oc2 ? ["--standalone"] : JSON_FORMAT),
"--title",
"akm",
"--agent",
MODEL_WORK_AGENT,
...(named ? ["--model", named] : []),
],
env: { ...NO_FREE_MODELS, [CONFIG_CONTENT_ENV]: modelWorkConfig(oc2) },
stdin: req.prompt,
...oc1,
};
},
};