opencode-rag-plugin 2.9.2 → 2.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ReadMe.md +27 -2
- package/dist/cli/commands/init-helpers.js +7 -0
- package/dist/cli/commands/init.js +7 -4
- package/dist/core/bootstrap.js +13 -10
- package/dist/core/config.d.ts +112 -1
- package/dist/core/config.js +167 -5
- package/dist/embedder/health.d.ts +8 -2
- package/dist/embedder/health.js +12 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/opencode/system-guidance.d.ts +4 -0
- package/dist/opencode/system-guidance.js +19 -0
- package/dist/plugin.d.ts +14 -9
- package/dist/plugin.js +126 -29
- package/dist/safety/shell-guard.d.ts +157 -0
- package/dist/safety/shell-guard.js +412 -0
- package/dist/v2/v2-adapter.d.ts +57 -4
- package/dist/v2/v2-adapter.js +90 -13
- package/package.json +1 -1
|
@@ -81,6 +81,20 @@ export const DECISION_ROUTING_GUIDANCE_LINE = "- Before asking the user to choos
|
|
|
81
81
|
* Build the flat guidance lines array for the runtime system-prompt injector.
|
|
82
82
|
* Returns a new array each call.
|
|
83
83
|
*/
|
|
84
|
+
export function buildShellBackgroundGuidanceLines(shell) {
|
|
85
|
+
if (shell?.backgroundGuidance === false)
|
|
86
|
+
return [];
|
|
87
|
+
const thresholdMs = shell?.longRunningThresholdMs ?? 30000;
|
|
88
|
+
const timeoutMs = shell?.foregroundTimeoutMs ?? 120000;
|
|
89
|
+
const thresholdSec = Math.max(1, Math.round(thresholdMs / 1000));
|
|
90
|
+
return [
|
|
91
|
+
"",
|
|
92
|
+
"Long-running commands:",
|
|
93
|
+
`- Any \`shell\` call expected to take more than ${thresholdSec}s MUST set \`background: true\` (returns immediately; the session is notified on completion) or set an explicit \`timeout\` (ms).`,
|
|
94
|
+
`- Default foreground timeout: ${timeoutMs}ms. Never run builds/tests/indexes in the foreground beyond ${thresholdSec}s; if a call is already running, press Ctrl+B to background it (OpenCode: \`session.background\`).`,
|
|
95
|
+
"- OpenCodeRAG measures foreground shell duration and records a quirk when a call exceeds the threshold, so repeated foreground runs become visible.",
|
|
96
|
+
];
|
|
97
|
+
}
|
|
84
98
|
export function buildSystemGuidanceLines(opts) {
|
|
85
99
|
const lines = [...MANDATORY_GUIDANCE_LINES];
|
|
86
100
|
if (opts.decisionEnabled) {
|
|
@@ -100,6 +114,7 @@ export function buildSystemGuidanceLines(opts) {
|
|
|
100
114
|
if (opts.promptEnforcement) {
|
|
101
115
|
lines.push(...QUIRK_ENFORCEMENT_LINES);
|
|
102
116
|
}
|
|
117
|
+
lines.push(...buildShellBackgroundGuidanceLines(opts.shell));
|
|
103
118
|
return lines;
|
|
104
119
|
}
|
|
105
120
|
/**
|
|
@@ -182,6 +197,10 @@ export function buildAgentsMdDirective(opts) {
|
|
|
182
197
|
if (opts.promptEnforcement) {
|
|
183
198
|
lines.push("", "### MANDATORY quirk capture rules — you MUST call `add_quirk` when", "- A build, test, or type-check command fails and you resolve it", "- You discover an undocumented library constraint, peer dep, or workaround", "- You learn an environment-specific requirement (OS, tool version, etc.)", "- You make a design decision that future sessions should remember", "- You resolve a gotcha that cost more than one attempt", "", "### MANDATORY quirk hygiene — you MUST call `update_quirk` or `delete_quirk` when", "- A stored quirk is outdated, wrong, or has been fixed — update it or delete it instead of adding a contradicting duplicate", "- NEVER finish a coding session without adding quirks for resolved errors.");
|
|
184
199
|
}
|
|
200
|
+
const shellLines = buildShellBackgroundGuidanceLines(opts.shell);
|
|
201
|
+
if (shellLines.length > 0) {
|
|
202
|
+
lines.push("", "### Long-running commands", ...shellLines.filter((l) => l.trim().length > 0));
|
|
203
|
+
}
|
|
185
204
|
lines.push(END_MARKER);
|
|
186
205
|
return lines.join("\n");
|
|
187
206
|
}
|
package/dist/plugin.d.ts
CHANGED
|
@@ -9,23 +9,28 @@ import { type RagConfig } from "./core/config.js";
|
|
|
9
9
|
import { createEmbedder } from "./embedder/factory.js";
|
|
10
10
|
import { retrieve } from "./retriever/retriever.js";
|
|
11
11
|
/**
|
|
12
|
-
* Load the RAG configuration for a directory,
|
|
13
|
-
*
|
|
12
|
+
* Load the RAG configuration for a directory: DEFAULT_CONFIG, then the global
|
|
13
|
+
* layer (`~/.config/opencode/opencode-rag.json`), then the first workspace
|
|
14
|
+
* config found (`opencode-rag.json`, `.opencode/opencode-rag.json`,
|
|
15
|
+
* `.opencode/rag.json`).
|
|
14
16
|
*
|
|
15
|
-
* The result is cached per directory and re-read whenever
|
|
16
|
-
* changes on disk, so an edited API key
|
|
17
|
+
* The result is cached per directory and re-read whenever either config file
|
|
18
|
+
* changes on disk, so an edited API key, baseUrl, or global `shellGuard` switch
|
|
19
|
+
* does not require a restart.
|
|
17
20
|
*/
|
|
18
21
|
export declare function getConfig(directory: string): Promise<RagConfig>;
|
|
19
22
|
/**
|
|
20
|
-
* Re-read a workspace's config
|
|
23
|
+
* Re-read a workspace's config when either the global or workspace file
|
|
24
|
+
* changed on disk.
|
|
21
25
|
*
|
|
22
26
|
* Only a config that this module loaded from a file is refreshed — the cache
|
|
23
|
-
* entry is the proof that the
|
|
24
|
-
* A caller that supplies its own configuration (tests, embedders)
|
|
27
|
+
* entry is the proof that the files are the source of truth for that
|
|
28
|
+
* workspace. A caller that supplies its own configuration (tests, embedders)
|
|
29
|
+
* keeps it.
|
|
25
30
|
*
|
|
26
31
|
* Synchronous on purpose: this runs on the hot path (every effective-config
|
|
27
|
-
* lookup) and `
|
|
28
|
-
* (`loadChunkersFromConfig`) mutates a global registry and is therefore
|
|
32
|
+
* lookup) and `loadWorkspaceConfig` is synchronous. The pluggable-chunker side
|
|
33
|
+
* effect (`loadChunkersFromConfig`) mutates a global registry and is therefore
|
|
29
34
|
* re-applied asynchronously — it is not needed by the embedding path this
|
|
30
35
|
* refresh exists to fix.
|
|
31
36
|
*
|
package/dist/plugin.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import { tool } from "@opencode-ai/plugin/tool";
|
|
7
7
|
import { CODE_SEARCH_FILTER } from "./core/interfaces.js";
|
|
8
8
|
import { normalizeFileExtensions } from "./core/filters.js";
|
|
9
|
-
import {
|
|
9
|
+
import { loadWorkspaceConfig, resolveConfigPaths, findConfigFile, DEFAULT_CONFIG, resolveLogConfig, persistProbedDimension } from "./core/config.js";
|
|
10
10
|
import { createEmbedder, probeEmbeddingDimension } from "./embedder/factory.js";
|
|
11
11
|
import { readStoreDimension } from "./vectorstore/lancedb.js";
|
|
12
12
|
import { createDescriptionProvider } from "./describer/factory.js";
|
|
@@ -44,6 +44,7 @@ const MAX_SESSION_MAP_SIZE = 50;
|
|
|
44
44
|
const MAX_SESSION_TOOL_RESULTS = 20;
|
|
45
45
|
/** Pending tool-error quirk blocks older than this (ms) are dropped instead of injected. */
|
|
46
46
|
const TOOL_ERROR_PENDING_TTL_MS = 120_000;
|
|
47
|
+
const SHELL_NUDGE_TTL_MS = 60_000;
|
|
47
48
|
/** How long the tool-error quirk list is cached before it is re-read (ms). */
|
|
48
49
|
const TOOL_GOTCHA_CACHE_MS = 30_000;
|
|
49
50
|
/** Cache of loaded RAG configurations keyed by workspace directory. */
|
|
@@ -233,24 +234,39 @@ function configFileMtime(configPath) {
|
|
|
233
234
|
return -1;
|
|
234
235
|
}
|
|
235
236
|
}
|
|
237
|
+
/** Identity of the config layers (global + workspace paths and mtimes). */
|
|
238
|
+
function configStamp(paths) {
|
|
239
|
+
return [
|
|
240
|
+
paths.global ? `${paths.global}:${configFileMtime(paths.global)}` : "",
|
|
241
|
+
paths.workspace ? `${paths.workspace}:${configFileMtime(paths.workspace)}` : "",
|
|
242
|
+
].join("|");
|
|
243
|
+
}
|
|
236
244
|
/**
|
|
237
|
-
* Load the RAG configuration for a directory,
|
|
238
|
-
*
|
|
245
|
+
* Load the RAG configuration for a directory: DEFAULT_CONFIG, then the global
|
|
246
|
+
* layer (`~/.config/opencode/opencode-rag.json`), then the first workspace
|
|
247
|
+
* config found (`opencode-rag.json`, `.opencode/opencode-rag.json`,
|
|
248
|
+
* `.opencode/rag.json`).
|
|
239
249
|
*
|
|
240
|
-
* The result is cached per directory and re-read whenever
|
|
241
|
-
* changes on disk, so an edited API key
|
|
250
|
+
* The result is cached per directory and re-read whenever either config file
|
|
251
|
+
* changes on disk, so an edited API key, baseUrl, or global `shellGuard` switch
|
|
252
|
+
* does not require a restart.
|
|
242
253
|
*/
|
|
243
254
|
export async function getConfig(directory) {
|
|
244
|
-
const
|
|
245
|
-
const
|
|
255
|
+
const paths = resolveConfigPaths(directory);
|
|
256
|
+
const stamp = configStamp(paths);
|
|
246
257
|
const cached = configCache.get(directory);
|
|
247
|
-
if (cached && cached.
|
|
258
|
+
if (cached && cached.stamp === stamp) {
|
|
248
259
|
return cached.cfg;
|
|
249
260
|
}
|
|
250
|
-
if (
|
|
261
|
+
if (paths.global || paths.workspace) {
|
|
251
262
|
try {
|
|
252
|
-
const cfg =
|
|
253
|
-
|
|
263
|
+
const cfg = loadWorkspaceConfig(directory);
|
|
264
|
+
const baseDir = paths.workspace
|
|
265
|
+
? path.dirname(paths.workspace)
|
|
266
|
+
: paths.global
|
|
267
|
+
? path.dirname(paths.global)
|
|
268
|
+
: directory;
|
|
269
|
+
await loadChunkersFromConfig(cfg, baseDir);
|
|
254
270
|
const hadKey = !!cfg.embedding.apiKey;
|
|
255
271
|
resolveApiKey(cfg, directory);
|
|
256
272
|
if (!hadKey && cfg.embedding.apiKey) {
|
|
@@ -259,13 +275,13 @@ export async function getConfig(directory) {
|
|
|
259
275
|
message: `Resolved embedding API key from ${process.env.OPENAI_API_KEY ? "OPENAI_API_KEY env var" : "OpenCode provider config"}`,
|
|
260
276
|
});
|
|
261
277
|
}
|
|
262
|
-
configCache.set(directory, { cfg,
|
|
278
|
+
configCache.set(directory, { cfg, stamp });
|
|
263
279
|
return cfg;
|
|
264
280
|
}
|
|
265
281
|
catch (err) {
|
|
266
282
|
appendDebugLog(path.resolve(directory, ".opencode", "opencode-rag.log"), {
|
|
267
283
|
scope: "config",
|
|
268
|
-
message: `Failed to load config from ${
|
|
284
|
+
message: `Failed to load config from ${paths.workspace ?? paths.global}`,
|
|
269
285
|
error: err,
|
|
270
286
|
});
|
|
271
287
|
}
|
|
@@ -273,19 +289,21 @@ export async function getConfig(directory) {
|
|
|
273
289
|
// Deep-clone so a later resolveApiKey() cannot mutate the shared
|
|
274
290
|
// DEFAULT_CONFIG singleton.
|
|
275
291
|
const cfg = structuredClone(DEFAULT_CONFIG);
|
|
276
|
-
configCache.set(directory, { cfg,
|
|
292
|
+
configCache.set(directory, { cfg, stamp });
|
|
277
293
|
return cfg;
|
|
278
294
|
}
|
|
279
295
|
/**
|
|
280
|
-
* Re-read a workspace's config
|
|
296
|
+
* Re-read a workspace's config when either the global or workspace file
|
|
297
|
+
* changed on disk.
|
|
281
298
|
*
|
|
282
299
|
* Only a config that this module loaded from a file is refreshed — the cache
|
|
283
|
-
* entry is the proof that the
|
|
284
|
-
* A caller that supplies its own configuration (tests, embedders)
|
|
300
|
+
* entry is the proof that the files are the source of truth for that
|
|
301
|
+
* workspace. A caller that supplies its own configuration (tests, embedders)
|
|
302
|
+
* keeps it.
|
|
285
303
|
*
|
|
286
304
|
* Synchronous on purpose: this runs on the hot path (every effective-config
|
|
287
|
-
* lookup) and `
|
|
288
|
-
* (`loadChunkersFromConfig`) mutates a global registry and is therefore
|
|
305
|
+
* lookup) and `loadWorkspaceConfig` is synchronous. The pluggable-chunker side
|
|
306
|
+
* effect (`loadChunkersFromConfig`) mutates a global registry and is therefore
|
|
289
307
|
* re-applied asynchronously — it is not needed by the embedding path this
|
|
290
308
|
* refresh exists to fix.
|
|
291
309
|
*
|
|
@@ -299,26 +317,31 @@ export function refreshConfig(directory, fallback) {
|
|
|
299
317
|
// No file-backed config for this workspace — the caller's config stands.
|
|
300
318
|
return fallback;
|
|
301
319
|
}
|
|
302
|
-
const
|
|
303
|
-
const
|
|
304
|
-
if (cached.
|
|
320
|
+
const paths = resolveConfigPaths(directory);
|
|
321
|
+
const stamp = configStamp(paths);
|
|
322
|
+
if (cached.stamp === stamp) {
|
|
305
323
|
return cached.cfg;
|
|
306
324
|
}
|
|
307
|
-
if (!
|
|
308
|
-
// The config
|
|
325
|
+
if (!paths.global && !paths.workspace) {
|
|
326
|
+
// The config files were removed — keep serving the last known config.
|
|
309
327
|
return cached.cfg;
|
|
310
328
|
}
|
|
311
329
|
try {
|
|
312
|
-
const cfg =
|
|
330
|
+
const cfg = loadWorkspaceConfig(directory);
|
|
313
331
|
resolveApiKey(cfg, directory);
|
|
314
|
-
|
|
315
|
-
|
|
332
|
+
const baseDir = paths.workspace
|
|
333
|
+
? path.dirname(paths.workspace)
|
|
334
|
+
: paths.global
|
|
335
|
+
? path.dirname(paths.global)
|
|
336
|
+
: directory;
|
|
337
|
+
void loadChunkersFromConfig(cfg, baseDir).catch(() => { });
|
|
338
|
+
configCache.set(directory, { cfg, stamp });
|
|
316
339
|
return cfg;
|
|
317
340
|
}
|
|
318
341
|
catch (err) {
|
|
319
342
|
appendDebugLog(path.resolve(directory, ".opencode", "opencode-rag.log"), {
|
|
320
343
|
scope: "config",
|
|
321
|
-
message: `Failed to reload config from ${
|
|
344
|
+
message: `Failed to reload config from ${paths.workspace ?? paths.global}`,
|
|
322
345
|
error: err,
|
|
323
346
|
});
|
|
324
347
|
return cached.cfg;
|
|
@@ -660,6 +683,10 @@ export function createRagHooks(options) {
|
|
|
660
683
|
// Auto-capture maps: previous user request per session, tool results, and full transcript
|
|
661
684
|
const sessionPrevUserReq = new Map();
|
|
662
685
|
const sessionToolResults = new Map();
|
|
686
|
+
// Foreground shell-call timing for the long-running-command feature.
|
|
687
|
+
const sessionShellStart = new Map();
|
|
688
|
+
const sessionPendingShellNudge = new Map();
|
|
689
|
+
const sessionShellLongCount = new Map();
|
|
663
690
|
const sessionTranscript = new Map();
|
|
664
691
|
// Track quirk IDs already injected per session to avoid duplicate injection
|
|
665
692
|
const sessionInjectedQuirks = new Map();
|
|
@@ -1261,10 +1288,73 @@ export function createRagHooks(options) {
|
|
|
1261
1288
|
}
|
|
1262
1289
|
},
|
|
1263
1290
|
tool: tools,
|
|
1291
|
+
async "tool.execute.before"(input, output) {
|
|
1292
|
+
try {
|
|
1293
|
+
const toolName = String(input.tool ?? "").toLowerCase();
|
|
1294
|
+
if (toolName !== "shell" && toolName !== "bash")
|
|
1295
|
+
return;
|
|
1296
|
+
const args = (output?.args ?? {});
|
|
1297
|
+
const command = typeof args.command === "string" ? args.command : (typeof args.cmd === "string" ? args.cmd : "");
|
|
1298
|
+
sessionShellStart.set(String(input.callID), {
|
|
1299
|
+
sessionID: input.sessionID,
|
|
1300
|
+
start: Date.now(),
|
|
1301
|
+
command: command.slice(0, 200),
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
catch {
|
|
1305
|
+
// Non-critical — must never throw
|
|
1306
|
+
}
|
|
1307
|
+
},
|
|
1264
1308
|
async "tool.execute.after"(input, output) {
|
|
1265
1309
|
try {
|
|
1266
1310
|
const results = sessionToolResults.get(input.sessionID) ?? [];
|
|
1267
1311
|
results.push({ tool: input.tool, output: output.output ?? "" });
|
|
1312
|
+
// Long-running shell command handling: measure foreground duration and,
|
|
1313
|
+
// when it exceeds the configured threshold, nudge the agent next turn
|
|
1314
|
+
// (and optionally record a quirk) so repeated foreground runs become
|
|
1315
|
+
// visible. True auto-backgrounding is an OpenCode-core feature; this is
|
|
1316
|
+
// the in-plugin approximation.
|
|
1317
|
+
try {
|
|
1318
|
+
const toolName = String(input.tool ?? "").toLowerCase();
|
|
1319
|
+
if (toolName === "shell" || toolName === "bash") {
|
|
1320
|
+
const startInfo = sessionShellStart.get(String(input.callID));
|
|
1321
|
+
sessionShellStart.delete(String(input.callID));
|
|
1322
|
+
const cfg = getEffectiveCfg();
|
|
1323
|
+
const shellCfg = cfg.openCode.shell;
|
|
1324
|
+
const thresholdMs = shellCfg?.longRunningThresholdMs ?? 30000;
|
|
1325
|
+
const durationMs = startInfo ? Date.now() - startInfo.start : undefined;
|
|
1326
|
+
if (durationMs != null && thresholdMs > 0 && durationMs >= thresholdMs) {
|
|
1327
|
+
const durSec = (durationMs / 1000).toFixed(1);
|
|
1328
|
+
const cmd = startInfo?.command || "(unknown command)";
|
|
1329
|
+
const nudgeText = `⚠ The previous foreground shell command took ${durSec}s ` +
|
|
1330
|
+
`(\`${cmd}\`). Prefer \`background: true\` or an explicit \`timeout\` for commands expected to exceed ` +
|
|
1331
|
+
`${Math.round(thresholdMs / 1000)}s; press Ctrl+B to background an already-running call.`;
|
|
1332
|
+
sessionPendingShellNudge.set(input.sessionID, { text: nudgeText, ts: Date.now() });
|
|
1333
|
+
if (shellCfg?.captureLongRunningQuirk !== false) {
|
|
1334
|
+
// Bound per-session recording to avoid runaway quirk spam.
|
|
1335
|
+
const counterKey = `shell-long:${input.sessionID}`;
|
|
1336
|
+
const current = (sessionShellLongCount.get(counterKey) ?? 0);
|
|
1337
|
+
if (current < 3) {
|
|
1338
|
+
sessionShellLongCount.set(counterKey, current + 1);
|
|
1339
|
+
const quirkDeps = { embedder, store, keywordIndex: keywordIndex, cfg: getEffectiveCfg(), storePath: options.storePath };
|
|
1340
|
+
void addQuirk(quirkDeps, {
|
|
1341
|
+
content: `A foreground shell command took ${durSec}s: \`${cmd}\`. Prefer \`background: true\` or an explicit \`timeout\` for long commands; press Ctrl+B to background a running call.`,
|
|
1342
|
+
quirkType: "gotcha",
|
|
1343
|
+
tags: ["tool:shell", "cause:long-foreground"],
|
|
1344
|
+
sourceRef: "opencode-rag:shell-auto-background",
|
|
1345
|
+
}).catch(() => { });
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
appendDebugLog(options.logFilePath, {
|
|
1349
|
+
scope: "shell.long-running",
|
|
1350
|
+
message: `foreground shell took ${durSec}s (threshold ${thresholdMs}ms): ${cmd}`,
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
catch {
|
|
1356
|
+
// Non-critical — must never throw
|
|
1357
|
+
}
|
|
1268
1358
|
// Failed tool calls: feed the auto-capture pipeline (learning loop) and
|
|
1269
1359
|
// recall matching quirks for injection into the next model request.
|
|
1270
1360
|
// `output.error` is set by the V2 adapter's error branch; the status
|
|
@@ -1354,7 +1444,7 @@ export function createRagHooks(options) {
|
|
|
1354
1444
|
// Non-critical — must never throw
|
|
1355
1445
|
}
|
|
1356
1446
|
if (injectGuidance) {
|
|
1357
|
-
const guidance = buildSystemGuidanceLines({ promptEnforcement: !!cfg.memory?.promptEnforcement, decisionEnabled: !!cfg.decision?.enabled, routeBeforeAsking: !!cfg.decision?.routeBeforeAsking });
|
|
1447
|
+
const guidance = buildSystemGuidanceLines({ promptEnforcement: !!cfg.memory?.promptEnforcement, decisionEnabled: !!cfg.decision?.enabled, routeBeforeAsking: !!cfg.decision?.routeBeforeAsking, shell: cfg.openCode.shell });
|
|
1358
1448
|
output.system.unshift(guidance.join("\n"));
|
|
1359
1449
|
}
|
|
1360
1450
|
// Inject a one-time update prompt so the agent asks the user to install.
|
|
@@ -1439,6 +1529,13 @@ export function createRagHooks(options) {
|
|
|
1439
1529
|
}
|
|
1440
1530
|
sessionPendingToolErrorQuirk.delete(sessionId);
|
|
1441
1531
|
}
|
|
1532
|
+
const shellNudge = sessionPendingShellNudge.get(sessionId);
|
|
1533
|
+
if (shellNudge) {
|
|
1534
|
+
if (Date.now() - shellNudge.ts < SHELL_NUDGE_TTL_MS) {
|
|
1535
|
+
output.system.unshift(shellNudge.text);
|
|
1536
|
+
}
|
|
1537
|
+
sessionPendingShellNudge.delete(sessionId);
|
|
1538
|
+
}
|
|
1442
1539
|
}
|
|
1443
1540
|
}
|
|
1444
1541
|
catch {
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Optional shell-command safety guard.
|
|
3
|
+
*
|
|
4
|
+
* Every `shell`/`bash` command is classified by a local decision model
|
|
5
|
+
* (tev1 via Ollama, or Clef/Jev via llama-swap — all speak the same
|
|
6
|
+
* `/v1/systemone` protocol) before it runs. A command whose `destructive` or
|
|
7
|
+
* `malicious` probability reaches the configured threshold is escalated to
|
|
8
|
+
* OpenCode's permission prompt (V2 `permission.hook("evaluate")` sets
|
|
9
|
+
* `effect = "ask"`); a clean command executes unchanged.
|
|
10
|
+
*
|
|
11
|
+
* Design constraints learned from the OpenCode V2 plugin API:
|
|
12
|
+
* - The V1 `tool.execute.before` hook cannot block a call (throwing is
|
|
13
|
+
* swallowed by the adapter), so the guard uses the permission `evaluate`
|
|
14
|
+
* hook, which runs AFTER rules are evaluated and BEFORE the action runs.
|
|
15
|
+
* - That hook runs for `allow` and `ask` decisions but not for `deny`.
|
|
16
|
+
* - The check sits on the critical path of every shell command: the timeout
|
|
17
|
+
* is short (default 10 s), verdicts are cached, and failures default to
|
|
18
|
+
* fail-open (`onError: "allow"`).
|
|
19
|
+
*
|
|
20
|
+
* @see https://opencode.ai/v2/docs/build/plugins (Permissions)
|
|
21
|
+
*/
|
|
22
|
+
import type { DecisionConfig, LoggingConfig, RagConfig, ShellGuardConfig } from "../core/config.js";
|
|
23
|
+
import type { DecisionProvider, DecisionQuestion, DecisionResult } from "../core/interfaces.js";
|
|
24
|
+
/** Tool names whose command text is vetted (V2 `shell`, V1-style `bash`). */
|
|
25
|
+
export declare const SHELL_GUARD_TOOL_NAMES: readonly string[];
|
|
26
|
+
/**
|
|
27
|
+
* Questions asked of the decision model for every command.
|
|
28
|
+
*
|
|
29
|
+
* Two `noul` questions drive the pass/fail decision (either one reaching the
|
|
30
|
+
* threshold flags the command); the `choice` question only labels the risk so
|
|
31
|
+
* the confirmation prompt explains *why* it was flagged.
|
|
32
|
+
*/
|
|
33
|
+
export declare const SHELL_GUARD_QUESTIONS: readonly DecisionQuestion[];
|
|
34
|
+
/** Live configuration resolved for one guard evaluation. */
|
|
35
|
+
export interface ShellGuardRuntimeConfig {
|
|
36
|
+
guard: ShellGuardConfig;
|
|
37
|
+
decision: DecisionConfig;
|
|
38
|
+
logging: LoggingConfig;
|
|
39
|
+
}
|
|
40
|
+
/** Outcome of classifying a single shell command. */
|
|
41
|
+
export interface ShellGuardVerdict {
|
|
42
|
+
/** True when the command must be confirmed before it runs. */
|
|
43
|
+
flagged: boolean;
|
|
44
|
+
/** Probability that the command is destructive (0-1). */
|
|
45
|
+
destructive: number;
|
|
46
|
+
/** Probability that the command is malicious (0-1). */
|
|
47
|
+
malicious: number;
|
|
48
|
+
/** Risk label chosen by the model (`none` when clean). */
|
|
49
|
+
category: string;
|
|
50
|
+
/** Human-readable explanation for the permission prompt. */
|
|
51
|
+
reason: string;
|
|
52
|
+
/** Decision provider name (e.g. "ollama"). */
|
|
53
|
+
provider: string;
|
|
54
|
+
/** Decision model name (e.g. "tev1:0.8b" / "Clef-Flash"). */
|
|
55
|
+
model: string;
|
|
56
|
+
/** Classification duration in ms. */
|
|
57
|
+
latencyMs: number;
|
|
58
|
+
/** True when the verdict was served from the cache. */
|
|
59
|
+
cached: boolean;
|
|
60
|
+
/** True when no config was available (guard disabled). */
|
|
61
|
+
skipped?: boolean;
|
|
62
|
+
/** Classifier failure (timeout / endpoint error); `flagged` follows `onError`. */
|
|
63
|
+
error?: string;
|
|
64
|
+
}
|
|
65
|
+
/** Injectable dependencies (tests provide a fake provider and clock). */
|
|
66
|
+
export interface ShellGuardDeps {
|
|
67
|
+
/** Resolve the live runtime config; `undefined` disables the guard. */
|
|
68
|
+
getConfig?: () => ShellGuardRuntimeConfig | undefined;
|
|
69
|
+
/** Provider factory override (defaults to the decision-model factory). */
|
|
70
|
+
createProvider?: (config: DecisionConfig) => DecisionProvider;
|
|
71
|
+
/** Clock override for cache tests. */
|
|
72
|
+
now?: () => number;
|
|
73
|
+
}
|
|
74
|
+
/** Case-insensitive test for a shell-execution tool name. */
|
|
75
|
+
export declare function isShellToolName(name: string | undefined): boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Truncate an oversized command for the decision model.
|
|
78
|
+
*
|
|
79
|
+
* The model's effective context is small (~2k tokens), so keep the head and
|
|
80
|
+
* the tail — destructive payloads usually appear at one end — and mark the
|
|
81
|
+
* omission explicitly.
|
|
82
|
+
*/
|
|
83
|
+
export declare function buildShellGuardState(command: string, maxChars?: number): string;
|
|
84
|
+
/**
|
|
85
|
+
* Convert raw decision answers into a guard verdict.
|
|
86
|
+
*
|
|
87
|
+
* Exported for tests; production callers use {@link ShellGuard.evaluate}.
|
|
88
|
+
*/
|
|
89
|
+
export declare function verdictFromDecisionResult(result: DecisionResult, opts: {
|
|
90
|
+
threshold: number;
|
|
91
|
+
provider: string;
|
|
92
|
+
model: string;
|
|
93
|
+
latencyMs: number;
|
|
94
|
+
cached?: boolean;
|
|
95
|
+
}): ShellGuardVerdict;
|
|
96
|
+
/** Build the message shown in the permission prompt. */
|
|
97
|
+
export declare function formatShellGuardReason(verdict: ShellGuardVerdict): string;
|
|
98
|
+
/**
|
|
99
|
+
* Classify shell commands and cache verdicts.
|
|
100
|
+
*
|
|
101
|
+
* One instance lives for the lifetime of the plugin registration. Provider
|
|
102
|
+
* instances are re-created only when the endpoint/model signature changes, so
|
|
103
|
+
* a config edit (e.g. switching tev1 → Clef-Flash) takes effect without a
|
|
104
|
+
* restart.
|
|
105
|
+
*/
|
|
106
|
+
export declare class ShellGuard {
|
|
107
|
+
private readonly deps;
|
|
108
|
+
private readonly cache;
|
|
109
|
+
private readonly now;
|
|
110
|
+
private readonly createProvider;
|
|
111
|
+
private providerState;
|
|
112
|
+
constructor(deps?: ShellGuardDeps);
|
|
113
|
+
/**
|
|
114
|
+
* Classify one command.
|
|
115
|
+
*
|
|
116
|
+
* Returns a non-flagged verdict when the guard is disabled or when the
|
|
117
|
+
* classifier fails under `onError: "allow"` (fail-open). Never throws.
|
|
118
|
+
*/
|
|
119
|
+
evaluate(command: string, abort?: AbortSignal): Promise<ShellGuardVerdict>;
|
|
120
|
+
/** Reset cached verdicts (tests / config reload). */
|
|
121
|
+
clearCache(): void;
|
|
122
|
+
private getProvider;
|
|
123
|
+
/**
|
|
124
|
+
* Build a verdict from a (possibly cached) classifier outcome using the
|
|
125
|
+
* CURRENT threshold and `onError` policy — editing either in
|
|
126
|
+
* `opencode-rag.json` takes effect on the next command even while cached
|
|
127
|
+
* probabilities are still valid.
|
|
128
|
+
*/
|
|
129
|
+
private verdictFromOutcome;
|
|
130
|
+
private store;
|
|
131
|
+
private log;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Resolve the guard's live config from a loaded `RagConfig`.
|
|
135
|
+
*
|
|
136
|
+
* Returns `undefined` when the guard is disabled — callers use that as the
|
|
137
|
+
* single gate. `decision.enabled` deliberately does NOT gate the guard: the
|
|
138
|
+
* guard has its own switch and may run against a backend the `make_decision`
|
|
139
|
+
* tool does not expose.
|
|
140
|
+
*
|
|
141
|
+
* @param cfg - Fully merged workspace configuration.
|
|
142
|
+
* @param directory - Workspace root; when given, the log file path is
|
|
143
|
+
* resolved against it (the plugin's process cwd is not necessarily the
|
|
144
|
+
* workspace).
|
|
145
|
+
*/
|
|
146
|
+
export declare function resolveShellGuardRuntimeConfig(cfg: RagConfig, directory?: string): ShellGuardRuntimeConfig | undefined;
|
|
147
|
+
/**
|
|
148
|
+
* Build a config reader that re-reads the global + workspace config when
|
|
149
|
+
* either changes.
|
|
150
|
+
*
|
|
151
|
+
* A shell command is classified at most a few seconds apart, so the stat
|
|
152
|
+
* check is cheap; re-reading makes an edit (global enabled flag, threshold,
|
|
153
|
+
* model) take effect without restarting OpenCode.
|
|
154
|
+
*/
|
|
155
|
+
export declare function createShellGuardConfigReader(directory: string): () => ShellGuardRuntimeConfig | undefined;
|
|
156
|
+
/** Convenience factory used by the V2 adapter. */
|
|
157
|
+
export declare function createShellGuardForDirectory(directory: string): ShellGuard;
|